text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { LegacyAPIClientInterface } from './legacy-api-client.interface'; import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from '../../types'; import * as models from '../../models'; export const USE_DOMAIN = new InjectionToken<string>('LegacyAPIClient_USE_DOMAIN'); export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('LegacyAPIClient_USE_HTTP_OPTIONS'); type APIHttpOptions = HttpOptions & { headers: HttpHeaders; params: HttpParams; }; @Injectable() export class LegacyAPIClient implements LegacyAPIClientInterface { readonly options: APIHttpOptions; readonly domain: string = `https://api.github.com`; constructor( private readonly http: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { if (domain != null) { this.domain = domain; } this.options = { headers: new HttpHeaders(options && options.headers ? options.headers : {}), params: new HttpParams(options && options.params ? options.params : {}), ...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}), ...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {}) }; } /** * Find issues by state and keyword. * Response generated for [ 200 ] HTTP response code. */ getLegacyIssuesSearchOwnerRepositoryStateKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyIssuesSearchOwnerRepositoryStateKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.SearchIssuesByKeyword>; getLegacyIssuesSearchOwnerRepositoryStateKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyIssuesSearchOwnerRepositoryStateKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.SearchIssuesByKeyword>>; getLegacyIssuesSearchOwnerRepositoryStateKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyIssuesSearchOwnerRepositoryStateKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.SearchIssuesByKeyword>>; getLegacyIssuesSearchOwnerRepositoryStateKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyIssuesSearchOwnerRepositoryStateKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.SearchIssuesByKeyword | HttpResponse<models.SearchIssuesByKeyword> | HttpEvent<models.SearchIssuesByKeyword>> { const path = `/legacy/issues/search/${args.owner}/${args.repository}/${args.state}/${args.keyword}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.SearchIssuesByKeyword>(`${this.domain}${path}`, options); } /** * Find repositories by keyword. Note, this legacy method does not follow the v3 pagination pattern. This method returns up to 100 results per page and pages can be fetched using the start_page parameter. * Response generated for [ 200 ] HTTP response code. */ getLegacyReposSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyReposSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.SearchRepositoriesByKeyword>; getLegacyReposSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyReposSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.SearchRepositoriesByKeyword>>; getLegacyReposSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyReposSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.SearchRepositoriesByKeyword>>; getLegacyReposSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyReposSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.SearchRepositoriesByKeyword | HttpResponse<models.SearchRepositoriesByKeyword> | HttpEvent<models.SearchRepositoriesByKeyword>> { const path = `/legacy/repos/search/${args.keyword}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('order' in args) { options.params = options.params.set('order', String(args.order)); } if ('language' in args) { options.params = options.params.set('language', String(args.language)); } if ('startPage' in args) { options.params = options.params.set('start_page', String(args.startPage)); } if ('sort' in args) { options.params = options.params.set('sort', String(args.sort)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.SearchRepositoriesByKeyword>(`${this.domain}${path}`, options); } /** * This API call is added for compatibility reasons only. * Response generated for [ 200 ] HTTP response code. */ getLegacyUserEmail( args: Exclude<LegacyAPIClientInterface['getLegacyUserEmailParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.SearchUserByEmail>; getLegacyUserEmail( args: Exclude<LegacyAPIClientInterface['getLegacyUserEmailParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.SearchUserByEmail>>; getLegacyUserEmail( args: Exclude<LegacyAPIClientInterface['getLegacyUserEmailParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.SearchUserByEmail>>; getLegacyUserEmail( args: Exclude<LegacyAPIClientInterface['getLegacyUserEmailParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.SearchUserByEmail | HttpResponse<models.SearchUserByEmail> | HttpEvent<models.SearchUserByEmail>> { const path = `/legacy/user/email/${args.email}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.SearchUserByEmail>(`${this.domain}${path}`, options); } /** * Find users by keyword. * Response generated for [ 200 ] HTTP response code. */ getLegacyUserSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyUserSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.SearchUsersByKeyword>; getLegacyUserSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyUserSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.SearchUsersByKeyword>>; getLegacyUserSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyUserSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.SearchUsersByKeyword>>; getLegacyUserSearchKeyword( args: Exclude<LegacyAPIClientInterface['getLegacyUserSearchKeywordParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.SearchUsersByKeyword | HttpResponse<models.SearchUsersByKeyword> | HttpEvent<models.SearchUsersByKeyword>> { const path = `/legacy/user/search/${args.keyword}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('order' in args) { options.params = options.params.set('order', String(args.order)); } if ('startPage' in args) { options.params = options.params.set('start_page', String(args.startPage)); } if ('sort' in args) { options.params = options.params.set('sort', String(args.sort)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.SearchUsersByKeyword>(`${this.domain}${path}`, options); } }
the_stack
import * as jsonStringify from 'json-stringify-safe'; import { clone } from "lodash-es"; import { Observable, of, Subject, throwError } from "rxjs"; import { catchError, map, mergeMap, switchMap, tap } from "rxjs/operators"; import { ApiCallType } from "./api/api-calls/api-call.model"; import { DataEntityType } from "./api/entity/data-entity.base"; import { EntityRelationshipRepositoryType, IEntityRelationshipRepositoryType } from "./api/entity/entity-relationship-repository-type"; import { EntityErrorEvent, EntityErrorTypes } from "./api/events/entity-error.event"; import { RemoveEntitiesEvent } from "./api/events/remove-entities.event"; import { SaveEntityEvent } from "./api/events/save-entity.event"; import { ReadonlyRepository } from "./api/repository/readonly-repository"; import { IRelationshipRepository, RelationshipRepository } from "./api/repository/relationship-repository"; import { Repository } from "./api/repository/repository"; import { IRepository } from "./api/repository/repository.interface"; import { ApiCallBackendConfigInterface } from "./config/api-call-backend-config.interface"; import { EntityModelBase } from "./config/entity-model.base"; import { EntityBackendConfig, EntityConfig } from "./config/entity.config"; import { EntityConfigBase } from "./config/model-config"; import { ModelBase } from "./config/model.base"; import { defaultConfig, ParisConfig } from "./config/paris-config"; import { entitiesService } from "./config/services/entities.service"; import { valueObjectsService } from "./config/services/value-objects.service"; import { DataCache, DataCacheSettings } from "./data_access/cache"; import { DataQuery } from "./data_access/data-query"; import { DataStoreService } from "./data_access/data-store.service"; import { DataOptions, defaultDataOptions } from "./data_access/data.options"; import { DataSet } from "./data_access/dataset"; import { HttpOptions, RequestMethod, UrlParams } from "./data_access/http.service"; import { queryToHttpOptions } from "./data_access/query-to-http"; import { DataTransformersService } from "./modeling/data-transformers.service"; import { EntityId } from "./modeling/entity-id.type"; import { Modeler } from "./modeling/modeler"; import { AjaxRequest } from "rxjs/ajax"; export class Paris<TConfigData = any> { private readonly repositories:Map<DataEntityType, IRepository<ModelBase>> = new Map; private readonly relationshipRepositories:Map<IEntityRelationshipRepositoryType<ModelBase, ModelBase>, IRelationshipRepository<ModelBase>> = new Map; readonly modeler:Modeler; readonly dataStore:DataStoreService; private _config:ParisConfig<TConfigData>; get config() { return this._config; } /** * Observable that fires whenever an {@link Entity} is saved */ readonly save$:Observable<SaveEntityEvent>; private readonly _saveSubject$:Subject<SaveEntityEvent> = new Subject; /** * Observable that fires whenever an {@link Entity} is removed */ readonly remove$:Observable<RemoveEntitiesEvent>; private readonly _removeSubject$:Subject<RemoveEntitiesEvent> = new Subject; /** * Observable that fires whenever there is an error in Paris. * Relevant both to errors parsing data and to HTTP errors */ readonly error$:Observable<EntityErrorEvent>; private readonly _errorSubject$:Subject<EntityErrorEvent> = new Subject; private readonly apiCallsCache:Map<ApiCallType, DataCache> = new Map<ApiCallType, DataCache>(); constructor(config?:ParisConfig<TConfigData>){ this.setConfig(config); this.dataStore = new DataStoreService(this.config); this.modeler = new Modeler(this); this.save$ = this._saveSubject$.asObservable(); this.remove$ = this._removeSubject$.asObservable(); this.error$ = this._errorSubject$.asObservable(); } /** * Returns the {@link Repository} for the specified class. If no Repository can be found, returns null. * @param {DataEntityType<TEntity extends ModelBase>} entityConstructor A class, should have a decorator of either @Entity or @ValueObject. */ getRepository<TEntity extends ModelBase>(entityConstructor:DataEntityType<TEntity>):Repository<TEntity> | null{ let repository:Repository<TEntity> = <Repository<TEntity>>this.repositories.get(entityConstructor); if (!repository) { let entityConfig:EntityConfig<TEntity> = entitiesService.getEntityByType(entityConstructor) || valueObjectsService.getEntityByType(entityConstructor); if (!entityConfig) return null; repository = new Repository<TEntity>(entityConstructor, this); this.repositories.set(entityConstructor, repository); // If the entity has an endpoint, it means it connects to the backend, so subscribe to save/delete events to enable global events: if (entityConfig.endpoint){ repository.save$.subscribe((saveEvent:SaveEntityEvent) => this._saveSubject$.next(saveEvent)); repository.remove$.subscribe((removeEvent:RemoveEntitiesEvent) => this._removeSubject$.next(removeEvent)); repository.error$.subscribe((error) => this._errorSubject$.next(error)) } } return repository; } /** * Returns a {@link RelationshipRepository} for the specified relationship class. * @param {Function} relationshipConstructor Class that has a @EntityRelationship decorator */ getRelationshipRepository<T extends ModelBase, U extends ModelBase>(relationshipConstructor:Function):RelationshipRepository<T, U>{ const relationship:EntityRelationshipRepositoryType<T, U> = <EntityRelationshipRepositoryType<T, U>>relationshipConstructor; let repository:RelationshipRepository<T, U> = <RelationshipRepository<T, U>>this.relationshipRepositories.get(relationship); if (!repository) { repository = new RelationshipRepository<T, U>(relationship.sourceEntityType, relationship.dataEntityType, relationship.allowedTypes, this); this.relationshipRepositories.set(relationship, repository); } return repository; } /** * Returns the configuration for the specified Entity/ValueObject class, if the specified class is indeed one of those. * @param {DataEntityType} entityConstructor */ getModelBaseConfig(entityConstructor:DataEntityType):EntityConfigBase{ return entityConstructor.entityConfig || entityConstructor.valueObjectConfig; } /** * Fetches multiple item data from backend * @param {DataEntityType<TEntity extends ModelBase>} entityConstructor The {@link Entity} class for which to fetch data * @param {DataQuery} query {@link DataQuery} object with configuration for the backend API, such as page, page size, order, or any custom data required * @param {DataOptions} dataOptions General options for the query. * @returns {Observable<DataSet<TEntity extends ModelBase>>} An Observable of DataSet<TEntity> */ query<TEntity extends ModelBase>(entityConstructor:DataEntityType<TEntity>, query?: DataQuery, dataOptions: DataOptions = defaultDataOptions): Observable<DataSet<TEntity>>{ let repository:Repository<TEntity> = this.getRepository(entityConstructor); if (repository) return repository.query(query, dataOptions); else throw new Error(`Can't query, no repository exists for ${entityConstructor}.`); } /** * Calls a backend API, which is defined by an ApiCallType. * @param {ApiCallType<TResult, TInput>} apiCallType The class which defines the ApiCallType. Should be decorated with @ApiCall and extend {@link ApiCallModel}. * @param {TInput} input Any data required to be sent to the backend in the API call * @param {DataOptions} dataOptions General options for the call * @returns {Observable<TResult>} An Observable of the api call's result data type */ apiCall<TResult = any, TInput = any>(apiCallType:ApiCallType<TResult, TInput>, input?:TInput, dataOptions:DataOptions = defaultDataOptions):Observable<TResult>{ const cacheKey:string = jsonStringify(input || {}); if (dataOptions.allowCache) { const apiCallTypeCache: DataCache<TResult> = this.getApiCallCache<TResult, TInput>(apiCallType); if (apiCallTypeCache) { return apiCallTypeCache.get(cacheKey).pipe( switchMap((value:TResult) => value !== undefined && value !== null ? of(value) : this.apiCall(apiCallType, input, { ...dataOptions, allowCache: false }) ) ); } } let httpOptions: HttpOptions = ((input !== undefined) && (input !== null)) ? apiCallType.config.parseQuery ? apiCallType.config.parseQuery(input, this.config) : apiCallType.config.method !== "GET" ? {data: input} : {params: input} : null; if (!httpOptions){ httpOptions = {}; } if (apiCallType.config.customHeaders){ httpOptions.customHeaders = apiCallType.config.customHeaders instanceof Function ? apiCallType.config.customHeaders(input, this.config) : apiCallType.config.customHeaders; } let requestOptions: AjaxRequest = apiCallType.config.responseType ? {responseType: apiCallType.config.responseType} : null; if (apiCallType.config.timeout) { requestOptions = Object.assign({}, requestOptions, {timeout: apiCallType.config.timeout}); } let apiCall$: Observable<any> = this.makeApiCall( apiCallType.config, apiCallType.config.method || "GET", httpOptions, undefined, requestOptions) .pipe( catchError((err: EntityErrorEvent) => { this._errorSubject$.next(err); return throwError(err.originalError || err) })); let typeRepository: ReadonlyRepository<TResult> = apiCallType.config.type ? this.getRepository(apiCallType.config.type) : null; if (typeRepository) { apiCall$ = apiCall$.pipe( mergeMap((data: any) => { const createItem$: Observable<TResult | Array<TResult>> = data instanceof Array ? this.modeler.modelArray<TResult>(data, apiCallType.config.type, dataOptions) : this.createItem<TResult>(apiCallType.config.type, data, dataOptions); return createItem$.pipe( tap(null, (err) => { this._errorSubject$.next({ originalError: err, type: EntityErrorTypes.DataParseError, entity: typeRepository.entityConstructor }) }) ) } ) ); } else if (apiCallType.config.type){ apiCall$ = apiCall$.pipe( map((data:any) => { try { return DataTransformersService.parse(apiCallType.config.type, data) } catch (err) { this._errorSubject$.next({ originalError: err.originalError || err, type: EntityErrorTypes.DataParseError, entity: typeRepository && typeRepository.entityConstructor }); throw err; } }) ); } if (apiCallType.config.parse) { apiCall$ = apiCall$.pipe( map((data: any) => { try { return apiCallType.config.parse(data, input) } catch (err) { this._errorSubject$.next({ originalError: err.originalError || err, type: EntityErrorTypes.DataParseError, entity: typeRepository && typeRepository.entityConstructor }); throw err; } }) ); } if (apiCallType.config.cache){ apiCall$ = apiCall$.pipe( tap((data:any) => { this.getApiCallCache(apiCallType, true).add(cacheKey, data); }) ); } return apiCall$; } /** * Clears all or specific ApiCallType caches * @param {ApiCallType<TResult, TInput>} apiCallType Optional ApiCallType class or array of classes. if omitted, all ApiCallType caches will be cleared. otherwise, only the caches of the specified ApiCallType(s) will be cleared. * @returns {void} */ clearApiCallCache(apiCallType?:ApiCallType | Array<ApiCallType>): void { if (!apiCallType) { this.apiCallsCache.clear(); return; } const apiCallTypes = apiCallType instanceof Array ? apiCallType : [apiCallType]; apiCallTypes.forEach(apiCallType => { const apiCallTypeCache = this.getApiCallCache(apiCallType); if (apiCallTypeCache) { apiCallTypeCache.clear(); } }) } private getApiCallCache<TResult, TInput>(apiCallType:ApiCallType<TResult, TInput>, addIfNotExists:boolean = false):DataCache<TResult>{ let apiCallCache:DataCache<TResult> = this.apiCallsCache.get(apiCallType); if (!apiCallCache && addIfNotExists){ let cacheSettings:DataCacheSettings = apiCallType.config.cache instanceof Object ? <DataCacheSettings>apiCallType.config.cache : null; this.apiCallsCache.set(apiCallType, apiCallCache = new DataCache<TResult>(cacheSettings)); } return apiCallCache; } private makeApiCall<TResult, TParams = UrlParams, TData = any, TRawDataResult = TResult>(backendConfig:ApiCallBackendConfigInterface<TResult, TRawDataResult>, method:RequestMethod, httpOptions:Readonly<HttpOptions<TData, TParams>>, query?: DataQuery, requestOptions?: AjaxRequest):Observable<TResult>{ const dataQuery: DataQuery = query || { where: httpOptions && httpOptions.params }; let endpoint:string; if (backendConfig.endpoint instanceof Function) endpoint = backendConfig.endpoint(this.config, dataQuery); else if (backendConfig.endpoint) endpoint = backendConfig.endpoint; else throw new Error(`Can't call API, no endpoint specified.`); const baseUrl:string = backendConfig.baseUrl instanceof Function ? backendConfig.baseUrl(this.config, dataQuery) : backendConfig.baseUrl; let apiCallHttpOptions:HttpOptions<TData> = clone(httpOptions) || {}; if (backendConfig.separateArrayParams) { apiCallHttpOptions.separateArrayParams = true; } if (backendConfig.fixedData){ if (!apiCallHttpOptions.params) apiCallHttpOptions.params = <TParams>{}; Object.assign(apiCallHttpOptions.params, backendConfig.fixedData); } const self = this; function makeRequest$<T>(): Observable<T> { return self.dataStore.request<T>(method || "GET", endpoint, apiCallHttpOptions, baseUrl, requestOptions).pipe( catchError(err => { return throwError({ originalError: err, type: EntityErrorTypes.HttpError, entity: null }) })) } if (backendConfig.parseData) { return makeRequest$<TRawDataResult>().pipe( map((rawData: TRawDataResult) => { try { return backendConfig.parseData(rawData, this.config, dataQuery) } catch (err) { throw { originalError: err, type: EntityErrorTypes.DataParseError, entity: null } } }), ); } return makeRequest$<TResult>() } /** * Underlying method for {@link query}. Different in that it accepts an {@link EntityBackendConfig}, to configure the call. * @param {DataEntityType<TEntity extends ModelBase>} entityConstructor * @param {EntityBackendConfig} backendConfig * @param {DataQuery} query * @param {DataOptions} dataOptions * @returns {Observable<DataSet<TEntity extends ModelBase>>} */ callQuery<TEntity extends ModelBase>(entityConstructor:DataEntityType<TEntity>, backendConfig:EntityBackendConfig<TEntity>, query?: DataQuery, dataOptions: DataOptions = defaultDataOptions):Observable<DataSet<TEntity>>{ let httpOptions:HttpOptions = backendConfig.parseDataQuery ? { params: backendConfig.parseDataQuery(query, this.config) } : queryToHttpOptions(query); if (!httpOptions){ httpOptions = {}; } if (backendConfig.customHeaders){ httpOptions.customHeaders = backendConfig.customHeaders instanceof Function ? backendConfig.customHeaders(query, this.config) : backendConfig.customHeaders; } const endpoint:string = backendConfig.endpoint instanceof Function ? backendConfig.endpoint(this.config, query) : backendConfig.endpoint; const apiCallConfig:ApiCallBackendConfigInterface = Object.assign({}, backendConfig, { endpoint: `${endpoint}${backendConfig.allItemsEndpointTrailingSlash !== false && !backendConfig.allItemsEndpoint ? '/' : ''}${backendConfig.allItemsEndpoint || ''}` }); let requestOptions: AjaxRequest; if (backendConfig.timeout) { requestOptions = {timeout: backendConfig.timeout}; } return this.makeApiCall<TEntity>(apiCallConfig, "GET", httpOptions, query, requestOptions).pipe( catchError((error: EntityErrorEvent) => { this._errorSubject$.next(Object.assign({}, error, {entity: entityConstructor})); return throwError(error.originalError || error) }), mergeMap((rawDataSet: TEntity) => { return this.modeler.rawDataToDataSet<TEntity>( rawDataSet, entityConstructor, backendConfig.allItemsProperty || this.config.allItemsProperty, dataOptions, query ).pipe( tap(null, (error) => { this._errorSubject$.next({ originalError: error, type: EntityErrorTypes.DataParseError, entity: entityConstructor }); } ) ) }), ); } /** * Creates an instance of a model - given an Entity/ValueObject class and data, creates a root model, with full model tree, meaning - all sub-models are modeled as well. * Sub-models that require being fetched from backend will be fetched. * @param {DataEntityType<TEntity extends ModelBase>} entityConstructor * @param data {TRawData} The raw JSON data for creating the item, as it arrives from backend. * @param {DataOptions} dataOptions * @param {DataQuery} query */ createItem<TEntity extends ModelBase, TRawData extends any = object>(entityConstructor:DataEntityType<TEntity>, data:TRawData, dataOptions: DataOptions = defaultDataOptions, query?:DataQuery):Observable<TEntity>{ return this.modeler.modelEntity<TEntity, TRawData>(data, entityConstructor.entityConfig || entityConstructor.valueObjectConfig, dataOptions, query); } /** * Gets an item by ID from backend and returns an Observable with the model * * @example <caption>Get a TodoItem with ID 1</caption> * ```typescript * const toDo$:Observable<TodoItem> = paris.getItemById<TodoItem>(TodoItem, 1); * toDo$.subscribe((toDo:TodoItem) => console.log('Found TodoItem item: ', toDo); * ``` * @param {DataEntityType<TEntity extends ModelBase>} entityConstructor * @param {string | number} itemId * @param {DataOptions} options * @param {{[p: string]: any}} params * @returns {Observable<TEntity extends ModelBase>} */ getItemById<TEntity extends EntityModelBase<TId>, TId extends EntityId, TTId extends TId>(entityConstructor:DataEntityType<TEntity, any, TId>, itemId: TTId, options?:DataOptions, params?:{ [index:string]:any }): Observable<TEntity>{ options = options || defaultDataOptions; const repository:Repository<TEntity> = this.getRepository(entityConstructor); if (repository) return repository.getItemById(itemId, options, params); else throw new Error(`Can't get item by ID, no repository exists for ${entityConstructor}.`); } /** * Gets all the items for an entity type. If all the items are cached, no backend call shall be performed (as in the case the the Entity is configured with `loadAll: true` and has already fetched data). * @param {DataEntityType<TEntity extends EntityModelBase>} entityConstructor * @returns {Observable<Array<TEntity extends EntityModelBase>>} */ allItems<TEntity extends EntityModelBase<TId>, TId extends EntityId>(entityConstructor:DataEntityType<TEntity, any, TId>):Observable<Array<TEntity>>{ const repository:Repository<TEntity> = this.getRepository(entityConstructor); if (repository) return repository.allItems$; else throw new Error(`Can't get all items, no repository exists for ${entityConstructor}.`); } /** * Query items in a relationship - fetches multiple items that relate to a specified item. * * @example <caption>Get all the TodoItem items in a TodoList</caption> * * ```typescript * const toDoListId = 1; * const toDoList$:Observable<TodoList> = paris.getItemById(TodoList, toDoListId); * * const toDoListItems$:Observable<DataSet<TodoItem>> = toDoList$.pipe( * mergeMap((toDoList:TodoList) => paris.queryForItem<TodoList, Todo>(TodoListItemsRelationship, toDoList)) * ); * * toDoListItems$.subscribe((toDoListItems:DataSet<TodoItem>) => console.log(`Items in TodoList #${toDoListId}:`, toDoListItems.items)); * ``` * @param {Function} relationshipConstructor * @param {ModelBase} item * @param {DataQuery} query * @param {DataOptions} dataOptions * @returns {Observable<DataSet<U extends ModelBase>>} */ queryForItem<TSource extends ModelBase, TResult extends ModelBase>(relationshipConstructor:Function, item:TSource, query?: DataQuery, dataOptions?:DataOptions): Observable<DataSet<TResult>>{ dataOptions = dataOptions || defaultDataOptions; let relationshipRepository:RelationshipRepository<TSource,TResult> = this.getRelationshipRepository<TSource, TResult>(relationshipConstructor); if (relationshipRepository) return relationshipRepository.queryForItem(item, query, dataOptions); else throw new Error(`Can't query for related item, no relationship repository exists for ${relationshipConstructor}.`); } /** * Gets an item that's related to another item, as defined in a relationship. * * @example <caption>Get an item for another item</caption> * ```typescript * const toDoListId = 1; * const toDoList$:Observable<TodoList> = paris.getItemById(TodoList, toDoListId); * * const toDoListHistory$:Observable<ToDoListHistory> = toDoList$.pipe( * mergeMap((toDoList:TodoList) => paris.getRelatedItem<TodoList, ToDoListHistory>(TodoListItemsRelationship, toDoList)) * ); * * toDoListHistory$.subscribe((toDoListHistory$:ToDoListHistory) => console.log(`History for TodoList #${toDoListId}:`, toDoListHistory)); * ``` * @param {Function} relationshipConstructor * @param {ModelBase} item * @param {DataQuery} query * @param {DataOptions} dataOptions * @returns {Observable<U extends ModelBase>} */ getRelatedItem<TSource extends ModelBase, TResult extends ModelBase>(relationshipConstructor:Function, item:TSource, query?: DataQuery, dataOptions: DataOptions = defaultDataOptions): Observable<TResult>{ let relationshipRepository:RelationshipRepository<TSource,TResult> = this.getRelationshipRepository<TSource, TResult>(relationshipConstructor); if (relationshipRepository) return relationshipRepository.getRelatedItem(item, query, dataOptions); else throw new Error(`Can't get related item, no relationship repository exists for ${relationshipConstructor}.`); } /** * Gets an entity value by its ID. The value has to be defined in the Entity's values property * * @example <caption>Get the value with id === 'open' from Entity ToDoStatus</caption> * ```typescript * const openStatusId = 'open'; * const toDoStatus = paris.getValue(ToDoStatus, openStatusId); * * console.log("TodoItem 'open' status: ", toDoStatus); * ``` * @param {DataEntityType<TEntity extends ModelBase>} entityConstructor * @param valueId * @returns {TEntity} */ getValue<TEntity extends ModelBase, TId extends EntityId>(entityConstructor:DataEntityType<TEntity, any, TId>, valueId:TId | ((value:TEntity) => boolean)):TEntity { let repository:Repository<TEntity> = this.getRepository(entityConstructor); if (!repository) return null; let values:Array<TEntity> = repository.entity.values; if (!values) return null; if (valueId instanceof Function){ for(let i=0, value; value = values[i]; i++){ if (valueId(value)) return value; } return null; } else return repository.entity.getValueById(valueId); } /** * Set the config object, merged with the default config object * @param {ParisConfig} config */ setConfig(config: ParisConfig){ this._config = Object.freeze(Object.assign({}, defaultConfig, config)); } /** * Reset the config object back to default */ resetConfig(){ this._config = Object.freeze(Object.assign({}, defaultConfig)); } }
the_stack
declare namespace dojox { namespace app { /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/main.html * * * @param config * @param node */ interface main{(config: any, node: any): void} /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/Controller.html * * * @param app dojox/app application instance. * @param events {event : handler} */ class Controller { constructor(app: any, events: any); /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/View.html * * View class inheriting from ViewBase adding templating & globalization capabilities. * * @param params view parameters, include:app: the appid: view idname: view nametemplate: view template identifier. If templateString is not empty, this parameter is ignored.templateString: view template stringcontroller: view controller module identifierparent: parent viewchildren: children viewsnls: nls definition module identifier */ class View extends dijit._TemplatedMixin implements dijit._WidgetsInTemplateMixin, dijit.Destroyable, dojox.app.ViewBase { constructor(params: any); /** * Object to which attach points and events will be scoped. Defaults * to 'this'. * */ "attachScope": Object; /** * Used to provide a context require to the dojo/parser in order to be * able to use relative MIDs (e.g. ./Widget) in the widget's template. * */ "contextRequire": Function; /** * */ "searchContainerNode": boolean; /** * Path to template (HTML file) for this widget relative to dojo.baseUrl. * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead * */ "templatePath": string; /** * A string that represents the widget template. * Use in conjunction with dojo.cache() to load from a file. * */ "templateString": string; /** * Should we parse the template to find widgets that might be * declared in markup inside it? (Remove for 2.0 and assume true) * */ "widgetsInTemplate": boolean; /** * view life cycle afterActivate() * */ afterActivate(): void; /** * view life cycle afterDeactivate() * */ afterDeactivate(): void; /** * view life cycle beforeActivate() * */ beforeActivate(): void; /** * view life cycle beforeDeactivate() * */ beforeDeactivate(): void; /** * Construct the UI for this widget from a template, setting this.domNode. * */ buildRendering(): void; /** * * @param obj * @param event * @param method */ connect(obj: any, event: any, method: any): any; /** * Destroy this class, releasing any resources registered via own(). * * @param preserveDom */ destroy(preserveDom?: boolean): void; /** * */ destroyRendering(): void; /** * view life cycle init() * */ init(): void; /** * */ load(): any; /** * Track specified handles and remove/destroy them when this instance is destroyed, unless they were * already removed/destroyed manually. * */ own(): any; /** * start view object. * load view template, view controller implement and startup all widgets in view template. * */ start(): any; /** * */ startup(): void; /** * Static method to get a template based on the templatePath or * templateString key */ getCachedTemplate(): any; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/ViewBase.html * * View base class with model & controller capabilities. Subclass must implement rendering capabilities. * * @param params view parameters, include:app: the appid: view idname: view nameparent: parent viewcontroller: view controller module identifierchildren: children views */ class ViewBase { constructor(params: any); /** * view life cycle afterActivate() * */ afterActivate(): void; /** * view life cycle afterDeactivate() * */ afterDeactivate(): void; /** * view life cycle beforeActivate() * */ beforeActivate(): void; /** * view life cycle beforeDeactivate() * */ beforeDeactivate(): void; /** * view life cycle destroy() * */ destroy(): void; /** * view life cycle init() * */ init(): void; /** * */ load(): any; /** * start view object. * load view template, view controller implement and startup all widgets in view template. * */ start(): any; } namespace controllers { /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/History.html * * */ class History extends dojox.app.Controller { constructor(); /** * Current state * */ "currentState": Object; /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; /** * * @param evt */ onDomNodeChange(evt: any): void; /** * Response to dojox/app "popstate" event. * * @param evt Transition options parameter */ onPopState(evt: Object): void; /** * Response to dojox/app "startTransition" event. * * @param evt Transition options parameter */ onStartTransition(evt: Object): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/HistoryHash.html * * * @param app dojox/app application instance. */ class HistoryHash extends dojox.app.Controller { constructor(app: any); /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; /** * * @param evt */ onDomNodeChange(evt: any): void; /** * Response to dojox/app "startTransition" event. * * @param evt transition options parameter */ onStartTransition(evt: Object): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/BorderLayout.html * * * @param app dojox/app application instance. * @param events {event : handler} */ class BorderLayout extends dojox.app.controllers.LayoutBase { constructor(app: any, events: any); /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * * @param view */ hideView(view: any): void; /** * Response to dojox/app "app-initLayout" event which is setup in LayoutBase. * The initLayout event is called once when the View is being created the first time. * * @param event {"view": view, "callback": function(){}}; */ initLayout(event: Object): void; /** * Response to dojox/app "app-layoutView" event. * * @param event {"parent":parent, "view":view, "removeView": boolean} */ layoutView(event: Object): void; /** * * @param view */ showView(view: any): void; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; /** * */ onResize(): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/LayoutBase.html * * * @param app dojox/app application instance. * @param events {event : handler} */ class LayoutBase extends dojox.app.Controller { constructor(app: any, events: any); /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * * @param view */ hideView(view: any): void; /** * Response to dojox/app "app-initLayout" event. * * @param event {"view": view, "callback": function(){}}; */ initLayout(event: Object): void; /** * Response to dojox/app "app-layoutView" event. * * @param event {"parent":parent, "view":view, "removeView": boolean} */ layoutView(event: Object): void; /** * * @param view */ showView(view: any): void; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; /** * */ onResize(): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/Load.html * * * @param app dojox/app application instance. * @param events {event : handler} */ class Load extends dojox.app.Controller { constructor(app: any, events: any); /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * Create a view instance if not already loaded by calling createView. This is typically a * dojox/app/View. * * @param parent parent of the view. * @param childId view id need to be loaded. * @param subIds sub views' id of this view. * @param params */ createChild(parent: Object, childId: String, subIds: String, params: any): any; /** * Create a dojox/app/View instance. Can be overridden to create different type of views. * * @param parent parent of this view. * @param id view id. * @param name view name. * @param mixin additional property to be mixed into the view (templateString, controller...) * @param params params of this view. * @param type the MID of the View. If not provided "dojox/app/View". */ createView(parent: Object, id: String, name: String, mixin: String, params: Object, type: String): any; /** * * @param event */ init(event: any): void; /** * Response to dojox/app "loadArray" event. * * @param event LoadArray event parameter. It should be like this: {"parent":parent, "viewId":viewId, "viewArray":viewArray, "callback":function(){...}} */ load(event: Object): any; /** * Load child and sub children views recursively. * * @param parent parent of this view. * @param childId view id need to be loaded. * @param subIds sub views' id of this view. * @param params params of this view. * @param loadEvent the event passed for the load of this view. */ loadChild(parent: Object, childId: String, subIds: String, params: Object, loadEvent: Object): any; /** * Response to dojox/app "app-load" event. * * @param loadEvent Load event parameter. It should be like this: {"parent":parent, "viewId":viewId, "callback":function(){...}} */ loadView(loadEvent: Object): any; /** * Proceed load queue by FIFO by default. * If load is in proceeding, add the next load to waiting queue. * * @param loadEvt LoadArray event parameter. It should be like this: {"parent":parent, "viewId":viewId, "viewArray":viewArray, "callback":function(){...}} */ proceedLoadView(loadEvt: Object): void; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/Layout.html * * * @param app dojox/app application instance. * @param events {event : handler} */ class Layout extends dojox.app.controllers.LayoutBase { constructor(app: any, events: any); /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * * @param view */ hideView(view: any): void; /** * Response to dojox/app "app-initLayout" event. * * @param event {"view": view, "callback": function(){}}; */ initLayout(event: Object): void; /** * Response to dojox/app "app-layoutView" event. * * @param event {"parent":parent, "view":view, "removeView": boolean} */ layoutView(event: Object): void; /** * * @param w */ resizeSelectedChildren(w: any): void; /** * * @param view */ showView(view: any): void; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; /** * */ onResize(): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/controllers/Transition.html * * * @param app dojox/app application instance. * @param events {event : handler} */ class Transition extends dojox.app.Controller { constructor(app: any, events: any); /** * */ "proceeding": boolean; /** * */ "waitingQueue": any[]; /** * Bind event on dojo/Evented instance, document, domNode or window. * Save event signal in controller instance. If no parameter is provided * automatically bind all events registered in controller events property. * * @param evented dojo/Evented instance, document, domNode or window * @param event event * @param handler event handler */ bind(evented: Object, event: String, handler: Function): Function; /** * Proceed transition queue by FIFO by default. * If transition is in proceeding, add the next transition to waiting queue. * * @param transitionEvt "app-transition" event parameter. It should be like: {"viewId":viewId, "opts":opts} */ proceedTransition(transitionEvt: Object): void; /** * Response to dojox/app "app-transition" event. * * @param event "app-transition" event parameter. It should be like: {"viewId": viewId, "opts": opts} */ transition(event: Object): void; /** * remove a binded event signal. * * @param evented dojo/Evented instance, document, domNode or window * @param event event */ unbind(evented: Object, event: String): Function; /** * * @param evt */ onDomNodeChange(evt: any): void; /** * Response to dojox/app "startTransition" event. * * @param evt transition options parameter */ onStartTransition(evt: Object): void; } } namespace module { /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/module/env.html * * */ class env { constructor(); /** * */ "mode": string; /** * */ init(): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/module/lifecycle.html * * */ class lifecycle { constructor(); /** * */ "lifecycle": Object; /** * */ getStatus(): any; /** * * @param newStatus */ setStatus(newStatus: any): void; } } namespace utils { /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/mvcModel.html * * mvcModel is called for each mvc model, to create the mvc model based upon the type and params. * It will also load models and return the either the loadedModels or a promise. * Called for each model with a modelLoader of "dojox/app/utils/mvcModel", it will * create the model based upon the type and the params set for the model in the config. * * @param config The models section of the config for this view or for the app. * @param params The params set into the config for this model. * @param item The String with the name of this model */ interface mvcModel{(config: Object, params: Object, item: String): void} /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/nls.html * * nsl is called to create to load the nls all for the app, or for a view. * * @param config The section of the config for this view or for the app. * @param parent The parent of this view or the app itself, so that models from the parent will beavailable to the view. */ interface nls{(config: Object, parent: Object): void} /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/model.html * * model is called to create all of the models for the app, and all models for a view, it will * create and call the appropriate model utility based upon the modelLoader set in the model in the config * Called for each view or for the app. For each model in the config, it willcreate the model utility based upon the modelLoader and call it to create and load the model. * * @param config The models section of the config for this view or for the app. * @param parent The parent of this view or the app itself, so that models from the parent will be available to the view. * @param app */ interface model{(config: Object, parent: Object, app: Object): void} /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/simpleModel.html * * simpleModel is called for each simple model, to create the simple model from the DataStore * based upon the store and query params. * It will also load models and return the either the loadedModels or a promise. * Called for each model with a modelLoader of "dojox/app/utils/simpleModel", it will * create the model based upon the store and query params set for the model in the config. * * @param config The models section of the config for this view or for the app. * @param params The params set into the config for this model. * @param item The String with the name of this model */ interface simpleModel{(config: Object, params: Object, item: String): void} /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/constraints.html * * */ interface constraints { /** * get current all selected children for this view and it's selected subviews * * @param view the View to get the child from * @param selChildren the Array of the subChildren found */ getAllSelectedChildren(view: dojox.app.View, selChildren: any[]): any; /** * get current selected child according to the constraint * * @param view the View to get the child from * @param constraint tbe constraint object */ getSelectedChild(view: dojox.app.View, constraint: Object): any; /** * * @param constraint */ register(constraint: any): void; /** * set current selected child according to the constraint * * @param view the View to set the selected child to * @param constraint tbe constraint object * @param child the child to select */ setSelectedChild(view: dojox.app.View, constraint: Object, child: dojox.app.View): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/config.html * * This module contains the config * */ interface config { /** * does a deep copy of the source into the target to merge the config from the source into the target * configMerge will merge the source config into the target config with a deep copy. * anything starting with __ will be skipped and if the target is an array the source items will be pushed into the target. * * @param target an object representing the config which will be updated by merging in the source. * @param source an object representing the config to be merged into the target. */ configMerge(target: Object, source: Object): any; /** * scan the source config for has checks and call configMerge to merge has sections, and remove the has sections from the source. * configProcessHas will scan the source config for has checks. * For each has section the items inside the has section will be tested with has (sniff) * If the has test is true it will call configMerge to merge has sections back into the source config. * It will always remove the has section from the source after processing it. * The names in the has section can be separated by a comma, indicating that any of those being true will satisfy the test. * * @param source an object representing the config to be processed. */ configProcessHas(source: Object): any; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/layout.html * * */ interface layout { /** * Layout a bunch of child dom nodes within a parent dom node * * @param container parent node * @param dim {l, t, w, h} object specifying dimensions of container into which to place children * @param children a list of children * @param changedRegionId OptionalIf specified, the slider for the region with the specified id has been dragged, and thusthe region's height or width should be adjusted according to changedRegionSize * @param changedRegionSize OptionalSee changedRegionId. */ layoutChildren(container: HTMLElement, dim: Object, children: any[], changedRegionId: String, changedRegionSize: number): void; /** * Given the margin-box size of a node, return its content box size. * Functions like domGeometry.contentBox() but is more reliable since it doesn't have * to wait for the browser to compute sizes. * * @param node * @param mb */ marginBox2contentBox(node: HTMLElement, mb: Object): Object; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/utils/hash.html * * This module contains the hash * */ interface hash { /** * add the view specific params to the hash for example (view1&param1=value1) * * @param hash the url hash * @param view the view name * @param params the params for this view */ addViewParams(hash: String, view: String, params: Object): any; /** * build up the url hash adding the params * * @param hash the url hash * @param params the params object */ buildWithParams(hash: String, params: Object): any; /** * called to handle a view specific params object * * @param params the view specific params object * @param viewPart the part of the view with the params for the view */ getParamObj(params: Object, viewPart: String): any; /** * get the params from the hash * * @param hash the url hash */ getParams(hash: String): any; /** * return the param string * * @param params the params object */ getParamString(params: Object): any; /** * return the target string * * @param hash the hash string * @param defaultView Optionalthe optional defaultView string */ getTarget(hash: String, defaultView: String): any; } } namespace widgets { /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/widgets/_ScrollableMixin.html * * Mixin for widgets to have a touch scrolling capability. * Actual implementation is in dojox/mobile/scrollable.js. * scrollable.js is not a dojo class, but just a collection * of functions. This module makes scrollable.js a dojo class. * */ class _ScrollableMixin extends dojox.mobile.scrollable { constructor(); /** * e.g. Allow ScrollableView in a SwapView. * */ "allowNestedScrolls": boolean; /** * Enables the search for application-specific bars (header or footer). * */ "appBars": boolean; /** * bounce back to the content area * */ "constraint": boolean; /** * disable the move handler if scroll starts in the unexpected direction * */ "dirLock": boolean; /** * */ "disableFlashScrollBar": boolean; /** * */ "fadeScrollBar": boolean; /** * height of a fixed footer * */ "fixedFooterHeight": number; /** * height of a fixed header * */ "fixedHeaderHeight": number; /** * explicitly specified height of this widget (ex. "300px") * */ "height": string; /** * footer is view-local (as opposed to application-wide) * */ "isLocalFooter": boolean; /** * let touchstart event propagate up * */ "propagatable": boolean; /** * Parameters for dojox/mobile/scrollable.init(). * */ "scrollableParams": Object; /** * show scroll bar or not * */ "scrollBar": boolean; /** * v: vertical, h: horizontal, vh: both, f: flip * */ "scrollDir": string; /** * * 1: use (-webkit-)transform:translate3d(x,y,z) style, use (-webkit-)animation for slide animation * 2: use top/left style, * 3: use (-webkit-)transform:translate3d(x,y,z) style, use (-webkit-)transition for slide animation * 0: use default value (3 for Android, iOS6+, and BlackBerry; otherwise 1) * */ "scrollType": number; /** * drag threshold value in pixels * */ "threshold": number; /** * a node that will have touch event handlers * */ "touchNode": HTMLElement; /** * frictional drag * */ "weight": number; /** * Aborts scrolling. * This function stops the scrolling animation that is currently * running. It is called when the user touches the screen while * scrolling. * */ abort(): void; /** * Adds the transparent DIV cover. * The cover is to prevent DOM events from affecting the child * widgets such as a list widget. Without the cover, for example, * child widgets may receive a click event and respond to it * unexpectedly when the user flicks the screen to scroll. * Note that only the desktop browsers need the cover. * */ addCover(): void; /** * A stub function to be overridden by subclasses. * This function is called from onTouchEnd(). The purpose is to give its * subclasses a chance to adjust the destination position. If this * function returns false, onTouchEnd() returns immediately without * performing scroll. * * @param to The destination position. An object with x and y. * @param pos The current position. An object with x and y. * @param dim Dimension information returned by getDim(). */ adjustDestination(to: Object, pos: Object, dim: Object): boolean; /** * */ buildRendering(): void; /** * Calculates the scroll bar position. * Given the scroll destination position, calculates the top and/or * the left of the scroll bar(s). Returns an object with x and y. * * @param to The scroll destination position. An object with x and y.ex. {x:0, y:-5} */ calcScrollBarPos(to: Object): Object; /** * Calculate the speed given the distance and time. * * @param distance * @param time */ calcSpeed(distance: number, time: number): number; /** * Checks if the given node is a fixed bar or not. * * @param node * @param local */ checkFixedBar(node: HTMLElement, local: boolean): any; /** * Uninitialize the module. * */ cleanup(): void; /** * Creates a mask for a scroll bar edge. * This function creates a mask that hides corners of one scroll * bar edge to make it round edge. The other side of the edge is * always visible and round shaped with the border-radius style. * */ createMask(): void; /** * */ destroy(): void; /** * Search for application-specific header or footer. * */ findAppBars(): void; /** * Finds the currently displayed view node from my sibling nodes. * * @param node */ findDisp(node: HTMLElement): any; /** * Shows the scroll bar instantly. * This function shows the scroll bar, and then hides it 300ms * later. This is used to show the scroll bar to the user for a * short period of time when a hidden view is revealed. * */ flashScrollBar(): void; /** * Returns various internal dimensional information needed for calculation. * */ getDim(): Object; /** * Gets the top position in the midst of animation. * */ getPos(): Object; /** * Returns the dimensions of the browser window. * */ getScreenSize(): Object; /** * Returns an object that indicates the scrolling speed. * From the position and elapsed time information, calculates the * scrolling speed, and returns an object with x and y. * */ getSpeed(): Object; /** * Hides the scroll bar. * If the fadeScrollBar property is true, hides the scroll bar with * the fade animation. * */ hideScrollBar(): void; /** * Initialize according to the given params. * Mixes in the given params into this instance. At least domNode * and containerNode have to be given. * Starts listening to the touchstart events. * Calls resize(), if this widget is a top level widget. * * @param params Optional */ init(params: Object): void; /** * Returns true if the given node is a form control. * * @param node */ isFormElement(node: HTMLElement): boolean; /** * Returns true if this is a top-level widget. * Subclass may want to override. * */ isTopLevel(): boolean; /** * Constructs a string value that is passed to the -webkit-transform property. * Return value example: "translate3d(0px,-8px,0px)" * * @param to The destination position. An object with x and/or y. */ makeTranslateStr(to: Object): String; /** * Removes the transparent DIV cover. * */ removeCover(): void; /** * Moves all the children to containerNode. * */ reparent(): void; /** * Resets the scroll bar length, position, etc. * */ resetScrollBar(): void; /** * Calls resize() of each child widget. * */ resize(): void; /** * Scrolls the pane until the searching node is in the view. * Just like the scrollIntoView method of DOM elements, this * function causes the given node to scroll into view, aligning it * either at the top or bottom of the pane. * * @param node A DOM node to be searched for view. * @param alignWithTop OptionalIf true, aligns the node at the top of the pane.If false, aligns the node at the bottom of the pane. * @param duration OptionalDuration of scrolling in seconds. (ex. 0.3)If not specified, scrolls without animation. */ scrollIntoView(node: HTMLElement, alignWithTop: boolean, duration: number): void; /** * Moves the scroll bar(s) to the given position without animation. * * @param to The destination position. An object with x and/or y.ex. {x:2, y:5}, {y:20}, etc. */ scrollScrollBarTo(to: Object): void; /** * Scrolls to the given position immediately without animation. * * @param to The destination position. An object with x and y.ex. {x:0, y:-5} * @param doNotMoveScrollBar OptionalIf true, the scroll bar will not be updated. If not specified,it will be updated. * @param node OptionalA DOM node to scroll. If not specified, defaults tothis.containerNode. */ scrollTo(to: Object, doNotMoveScrollBar: boolean, node: HTMLElement): void; /** * Programmatically sets key frames for the scroll animation. * * @param from * @param to * @param idx */ setKeyframes(from: Object, to: Object, idx: number): void; /** * Sets the given node as selectable or unselectable. * * @param node * @param selectable */ setSelectable(node: HTMLElement, selectable: boolean): void; /** * Shows the scroll bar. * This function creates the scroll bar instance if it does not * exist yet, and calls resetScrollBar() to reset its length and * position. * */ showScrollBar(): void; /** * Moves the scroll bar(s) to the given position with the slide animation. * * @param to The destination position. An object with x and y.ex. {x:0, y:-5} * @param duration Duration of the animation in seconds. (ex. 0.3) * @param easing The name of easing effect which webkit supports."ease", "linear", "ease-in", "ease-out", etc. */ slideScrollBarTo(to: Object, duration: number, easing: String): void; /** * Scrolls to the given position with the slide animation. * * @param to The scroll destination position. An object with x and/or y.ex. {x:0, y:-5}, {y:-29}, etc. * @param duration Duration of scrolling in seconds. (ex. 0.3) * @param easing The name of easing effect which webkit supports."ease", "linear", "ease-in", "ease-out", etc. */ slideTo(to: Object, duration: number, easing: String): void; /** * */ startup(): void; /** * Stops the currently running animation. * */ stopAnimation(): void; /** * called after a scroll has been performed. * * @param e the scroll event, that contains the following attributes:x (x coordinate of the scroll destination),y (y coordinate of the scroll destination),beforeTop (a boolean that is true if the scroll detination is before the top of the scrollable),beforeTopHeight (the number of pixels before the top of the scrollable for the scroll destination),afterBottom (a boolean that is true if the scroll destination is after the bottom of the scrollable),afterBottomHeight (the number of pixels after the bottom of the scrollable for the scroll destination) */ onAfterScroll(e: Event): void; /** * called before a scroll is initiated. If this method returns false, * the scroll is canceled. * * @param e the scroll event, that contains the following attributes:x (x coordinate of the scroll destination),y (y coordinate of the scroll destination),beforeTop (a boolean that is true if the scroll detination is before the top of the scrollable),beforeTopHeight (the number of pixels before the top of the scrollable for the scroll destination),afterBottom (a boolean that is true if the scroll destination is after the bottom of the scrollable),afterBottomHeight (the number of pixels after the bottom of the scrollable for the scroll destination) */ onBeforeScroll(e: Event): boolean; /** * * @param e */ onFlickAnimationEnd(e: any): void; /** * * @param e */ onFlickAnimationStart(e: any): void; /** * User-defined function to handle touchEnd events. * * @param e */ onTouchEnd(e: Event): void; /** * User-defined function to handle touchMove events. * * @param e */ onTouchMove(e: any): void; /** * User-defined function to handle touchStart events. * * @param e */ onTouchStart(e: any): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/app/widgets/Container.html * * * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree */ class Container extends dijit._WidgetBase implements dijit._Container, dijit._Contained, dojox.app.widgets._ScrollableMixin { constructor(params?: Object, srcNodeRef?: HTMLElement); /** * e.g. Allow ScrollableView in a SwapView. * */ "allowNestedScrolls": boolean; set(property:"allowNestedScrolls", value: boolean): void; get(property:"allowNestedScrolls"): boolean; watch(property:"allowNestedScrolls", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * Enables the search for application-specific bars (header or footer). * */ "appBars": boolean; set(property:"appBars", value: boolean): void; get(property:"appBars"): boolean; watch(property:"appBars", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute * for each XXX attribute to be mapped to the DOM. * * attributeMap sets up a "binding" between attributes (aka properties) * of the widget and the widget's DOM. * Changes to widget attributes listed in attributeMap will be * reflected into the DOM. * * For example, calling set('title', 'hello') * on a TitlePane will automatically cause the TitlePane's DOM to update * with the new title. * * attributeMap is a hash where the key is an attribute of the widget, * and the value reflects a binding to a: * * DOM node attribute * focus: {node: "focusNode", type: "attribute"} * Maps this.focus to this.focusNode.focus * * DOM node innerHTML * title: { node: "titleNode", type: "innerHTML" } * Maps this.title to this.titleNode.innerHTML * * DOM node innerText * title: { node: "titleNode", type: "innerText" } * Maps this.title to this.titleNode.innerText * * DOM node CSS class * myClass: { node: "domNode", type: "class" } * Maps this.myClass to this.domNode.className * * If the value is an array, then each element in the array matches one of the * formats of the above list. * * There are also some shorthands for backwards compatibility: * * string --> { node: string, type: "attribute" }, for example: * "focusNode" ---> { node: "focusNode", type: "attribute" } * "" --> { node: "domNode", type: "attribute" } * */ "attributeMap": Object; set(property:"attributeMap", value: Object): void; get(property:"attributeMap"): Object; watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate * widget state. * */ "baseClass": string; set(property:"baseClass", value: string): void; get(property:"baseClass"): string; watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * */ "class": string; set(property:"class", value: string): void; get(property:"class"): string; watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * bounce back to the content area * */ "constraint": boolean; set(property:"constraint", value: boolean): void; get(property:"constraint"): boolean; watch(property:"constraint", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * Designates where children of the source DOM node will be placed. * "Children" in this case refers to both DOM nodes and widgets. * For example, for myWidget: * * <div data-dojo-type=myWidget> * <b> here's a plain DOM node * <span data-dojo-type=subWidget>and a widget</span> * <i> and another plain DOM node </i> * </div> * containerNode would point to: * * <b> here's a plain DOM node * <span data-dojo-type=subWidget>and a widget</span> * <i> and another plain DOM node </i> * In templated widgets, "containerNode" is set via a * data-dojo-attach-point assignment. * * containerNode must be defined for any widget that accepts innerHTML * (like ContentPane or BorderContainer or even Button), and conversely * is null for widgets that don't, like TextBox. * */ "containerNode": HTMLElement; set(property:"containerNode", value: HTMLElement): void; get(property:"containerNode"): HTMLElement; watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} /** * Bi-directional support, as defined by the HTML DIR * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's * default direction. * */ "dir": string; set(property:"dir", value: string): void; get(property:"dir"): string; watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * disable the move handler if scroll starts in the unexpected direction * */ "dirLock": boolean; set(property:"dirLock", value: boolean): void; get(property:"dirLock"): boolean; watch(property:"dirLock", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * */ "disableFlashScrollBar": boolean; set(property:"disableFlashScrollBar", value: boolean): void; get(property:"disableFlashScrollBar"): boolean; watch(property:"disableFlashScrollBar", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * This is our visible representation of the widget! Other DOM * Nodes may by assigned to other properties, usually through the * template system's data-dojo-attach-point syntax, but the domNode * property is the canonical "top level" node in widget UI. * */ "domNode": HTMLElement; set(property:"domNode", value: HTMLElement): void; get(property:"domNode"): HTMLElement; watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} /** * */ "fadeScrollBar": boolean; set(property:"fadeScrollBar", value: boolean): void; get(property:"fadeScrollBar"): boolean; watch(property:"fadeScrollBar", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * */ "fixedFooter": string; set(property:"fixedFooter", value: string): void; get(property:"fixedFooter"): string; watch(property:"fixedFooter", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * height of a fixed footer * */ "fixedFooterHeight": number; set(property:"fixedFooterHeight", value: number): void; get(property:"fixedFooterHeight"): number; watch(property:"fixedFooterHeight", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} /** * */ "fixedHeader": string; set(property:"fixedHeader", value: string): void; get(property:"fixedHeader"): string; watch(property:"fixedHeader", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * height of a fixed header * */ "fixedHeaderHeight": number; set(property:"fixedHeaderHeight", value: number): void; get(property:"fixedHeaderHeight"): number; watch(property:"fixedHeaderHeight", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} /** * This widget or a widget it contains has focus, or is "active" because * it was recently clicked. * */ "focused": boolean; set(property:"focused", value: boolean): void; get(property:"focused"): boolean; watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * explicitly specified height of this widget (ex. "300px") * */ "height": string; set(property:"height", value: string): void; get(property:"height"): string; watch(property:"height", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * A unique, opaque ID string that can be assigned by users or by the * system. If the developer passes an ID which is known not to be * unique, the specified ID is ignored and the system-generated ID is * used instead. * */ "id": string; set(property:"id", value: string): void; get(property:"id"): string; watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * footer is view-local (as opposed to application-wide) * */ "isLocalFooter": boolean; set(property:"isLocalFooter", value: boolean): void; get(property:"isLocalFooter"): boolean; watch(property:"isLocalFooter", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * Rarely used. Overrides the default Dojo locale used to render this widget, * as defined by the HTML LANG attribute. * Value must be among the list of locales specified during by the Dojo bootstrap, * formatted according to RFC 3066 (like en-us). * */ "lang": string; set(property:"lang", value: string): void; get(property:"lang"): string; watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * The document this widget belongs to. If not specified to constructor, will default to * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global * */ "ownerDocument": Object; set(property:"ownerDocument", value: Object): void; get(property:"ownerDocument"): Object; watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** * let touchstart event propagate up * */ "propagatable": boolean; set(property:"propagatable", value: boolean): void; get(property:"propagatable"): boolean; watch(property:"propagatable", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * */ "scrollable": boolean; set(property:"scrollable", value: boolean): void; get(property:"scrollable"): boolean; watch(property:"scrollable", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * Parameters for dojox/mobile/scrollable.init(). * */ "scrollableParams": Object; set(property:"scrollableParams", value: Object): void; get(property:"scrollableParams"): Object; watch(property:"scrollableParams", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** * show scroll bar or not * */ "scrollBar": boolean; set(property:"scrollBar", value: boolean): void; get(property:"scrollBar"): boolean; watch(property:"scrollBar", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** * v: vertical, h: horizontal, vh: both, f: flip * */ "scrollDir": string; set(property:"scrollDir", value: string): void; get(property:"scrollDir"): string; watch(property:"scrollDir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * * 1: use (-webkit-)transform:translate3d(x,y,z) style, use (-webkit-)animation for slide animation * 2: use top/left style, * 3: use (-webkit-)transform:translate3d(x,y,z) style, use (-webkit-)transition for slide animation * 0: use default value (3 for Android, iOS6+, and BlackBerry; otherwise 1) * */ "scrollType": number; set(property:"scrollType", value: number): void; get(property:"scrollType"): number; watch(property:"scrollType", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} /** * pointer to original DOM node * */ "srcNodeRef": HTMLElement; set(property:"srcNodeRef", value: HTMLElement): void; get(property:"srcNodeRef"): HTMLElement; watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} /** * HTML style attributes as cssText string or name/value hash * */ "style": string; set(property:"style", value: string): void; get(property:"style"): string; watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * drag threshold value in pixels * */ "threshold": number; set(property:"threshold", value: number): void; get(property:"threshold"): number; watch(property:"threshold", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} /** * HTML title attribute. * * For form widgets this specifies a tooltip to display when hovering over * the widget (just like the native HTML title attribute). * * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's * interpreted as HTML. * */ "title": string; set(property:"title", value: string): void; get(property:"title"): string; watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * When this widget's title attribute is used to for a tab label, accordion pane title, etc., * this specifies the tooltip to appear when the mouse is hovered over that text. * */ "tooltip": string; set(property:"tooltip", value: string): void; get(property:"tooltip"): string; watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} /** * a node that will have touch event handlers * */ "touchNode": HTMLElement; set(property:"touchNode", value: HTMLElement): void; get(property:"touchNode"): HTMLElement; watch(property:"touchNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} /** * frictional drag * */ "weight": number; set(property:"weight", value: number): void; get(property:"weight"): number; watch(property:"weight", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} /** * Aborts scrolling. * This function stops the scrolling animation that is currently * running. It is called when the user touches the screen while * scrolling. * */ abort(): void; /** * Makes the given widget a child of this widget. * Inserts specified child widget's dom node as a child of this widget's * container node, and possibly does other processing (such as layout). * * @param widget * @param insertIndex Optional */ addChild(widget: dijit._WidgetBase, insertIndex: number): void; /** * Adds the transparent DIV cover. * The cover is to prevent DOM events from affecting the child * widgets such as a list widget. Without the cover, for example, * child widgets may receive a click event and respond to it * unexpectedly when the user flicks the screen to scroll. * Note that only the desktop browsers need the cover. * */ addCover(): void; /** * A stub function to be overridden by subclasses. * This function is called from onTouchEnd(). The purpose is to give its * subclasses a chance to adjust the destination position. If this * function returns false, onTouchEnd() returns immediately without * performing scroll. * * @param to The destination position. An object with x and y. * @param pos The current position. An object with x and y. * @param dim Dimension information returned by getDim(). */ adjustDestination(to: Object, pos: Object, dim: Object): boolean; /** * */ buildRendering(): void; /** * Calculates the scroll bar position. * Given the scroll destination position, calculates the top and/or * the left of the scroll bar(s). Returns an object with x and y. * * @param to The scroll destination position. An object with x and y.ex. {x:0, y:-5} */ calcScrollBarPos(to: Object): Object; /** * Calculate the speed given the distance and time. * * @param distance * @param time */ calcSpeed(distance: number, time: number): number; /** * Checks if the given node is a fixed bar or not. * * @param node * @param local */ checkFixedBar(node: HTMLElement, local: boolean): any; /** * Uninitialize the module. * */ cleanup(): void; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: Object, event: String, method: String): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: any, event: String, method: String): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: Object, event: Function, method: String): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: any, event: Function, method: String): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: Object, event: String, method: Function): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: any, event: String, method: Function): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: Object, event: Function, method: Function): any; /** * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. * * Connects specified obj/event to specified method of this object * and registers for disconnect() on widget destroy. * * Provide widget-specific analog to dojo.connect, except with the * implicit use of this widget as the target object. * Events connected with this.connect are disconnected upon * destruction. * * @param obj * @param event * @param method */ connect(obj: any, event: Function, method: Function): any; /** * Creates a mask for a scroll bar edge. * This function creates a mask that hides corners of one scroll * bar edge to make it round edge. The other side of the edge is * always visible and round shaped with the border-radius style. * */ createMask(): void; /** * Wrapper to setTimeout to avoid deferred functions executing * after the originating widget has been destroyed. * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). * * @param fcn Function reference. * @param delay OptionalDelay, defaults to 0. */ defer(fcn: Function, delay: number): Object; /** * Destroy this widget, but not its descendants. Descendants means widgets inside of * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). * * This method will also destroy internal widgets such as those created from a template, * assuming those widgets exist inside of this.domNode but outside of this.containerNode. * * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not * depend on the current ability to destroy a widget without destroying its descendants. Generally * they should use destroyRecursive() for widgets with children. * * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets */ destroy(preserveDom?: boolean): void; /** * Recursively destroy the children of this widget and their * descendants. * * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. */ destroyDescendants(preserveDom: boolean): void; /** * Destroy this widget and its descendants * This is the generic "destructor" function that all widget users * should call to cleanly discard with a widget. Once a widget is * destroyed, it is removed from the manager object. * * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. */ destroyRecursive(preserveDom: boolean): void; /** * Destroys the DOM nodes associated with this widget. * * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. */ destroyRendering(preserveDom?: boolean): void; /** * Deprecated, will be removed in 2.0, use handle.remove() instead. * * Disconnects handle created by connect. * * @param handle */ disconnect(handle: any): void; /** * Used by widgets to signal that a synthetic event occurred, ex: * * myWidget.emit("attrmodified-selectedChildWidget", {}). * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. * Also calls onType() method, if present, and returns value from that method. * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). * * @param type * @param eventObj Optional * @param callbackArgs Optional */ emit(type: String, eventObj: Object, callbackArgs: any[]): any; /** * Search for application-specific header or footer. * */ findAppBars(): void; /** * Finds the currently displayed view node from my sibling nodes. * * @param node */ findDisp(node: HTMLElement): any; /** * Shows the scroll bar instantly. * This function shows the scroll bar, and then hides it 300ms * later. This is used to show the scroll bar to the user for a * short period of time when a hidden view is revealed. * */ flashScrollBar(): void; /** * Get a property from a widget. * Get a named property from a widget. The property may * potentially be retrieved via a getter method. If no getter is defined, this * just retrieves the object's property. * * For example, if the widget has properties foo and bar * and a method named _getFooAttr(), calling: * myWidget.get("foo") would be equivalent to calling * widget._getFooAttr() and myWidget.get("bar") * would be equivalent to the expression * widget.bar2 * * @param name The property to get. */ get(name: any): any; /** * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent * is this widget. Note that it does not return all descendants, but rather just direct children. * Analogous to Node.childNodes, * except containing widgets rather than DOMNodes. * * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) * outside of this.containerNode. * * Note that the array returned is a simple array. Application code should not assume * existence of methods like forEach(). * */ getChildren(): any[]; /** * Returns various internal dimensional information needed for calculation. * */ getDim(): Object; /** * Returns the index of this widget within its container parent. * It returns -1 if the parent does not exist, or if the parent * is not a dijit/_Container * */ getIndexInParent(): any; /** * Gets the index of the child in this container or -1 if not found * * @param child */ getIndexOfChild(child: dijit._WidgetBase): any; /** * Returns null if this is the last child of the parent, * otherwise returns the next element sibling to the "right". * */ getNextSibling(): any; /** * Returns the parent widget of this widget. * */ getParent(): any; /** * Gets the top position in the midst of animation. * */ getPos(): Object; /** * Returns null if this is the first child of the parent, * otherwise returns the next element sibling to the "left". * */ getPreviousSibling(): any; /** * Returns the dimensions of the browser window. * */ getScreenSize(): Object; /** * Returns an object that indicates the scrolling speed. * From the position and elapsed time information, calculates the * scrolling speed, and returns an object with x and y. * */ getSpeed(): Object; /** * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. * */ hasChildren(): boolean; /** * Hides the scroll bar. * If the fadeScrollBar property is true, hides the scroll bar with * the fade animation. * */ hideScrollBar(): void; /** * Initialize according to the given params. * Mixes in the given params into this instance. At least domNode * and containerNode have to be given. * Starts listening to the touchstart events. * Calls resize(), if this widget is a top level widget. * * @param params Optional */ init(params: Object): void; /** * Return true if this widget can currently be focused * and false if not * */ isFocusable(): any; /** * Returns true if the given node is a form control. * * @param node */ isFormElement(node: HTMLElement): boolean; /** * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) * */ isLeftToRight(): any; /** * Returns true if this is a top-level widget. * Subclass may want to override. * */ isTopLevel(): boolean; /** * layout container * */ layout(): void; /** * Constructs a string value that is passed to the -webkit-transform property. * Return value example: "translate3d(0px,-8px,0px)" * * @param to The destination position. An object with x and/or y. */ makeTranslateStr(to: Object): String; /** * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). * Note that the function is not run in any particular scope, so if (for example) you want it to run in the * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). * * @param type Name of event (ex: "click") or extension event like touch.press. * @param func */ on(type: String, func: Function): any; /** * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). * Note that the function is not run in any particular scope, so if (for example) you want it to run in the * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). * * @param type Name of event (ex: "click") or extension event like touch.press. * @param func */ on(type: Function, func: Function): any; /** * Track specified handles and remove/destroy them when this instance is destroyed, unless they were * already removed/destroyed manually. * */ own(): any; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. * A convenience function provided in all _Widgets, providing a simple * shorthand mechanism to put an existing (or newly created) Widget * somewhere in the dom, and allow chaining. * * @param reference Widget, DOMNode, or id of widget or DOMNode * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). */ placeAt(reference: String, position: String): any; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. * A convenience function provided in all _Widgets, providing a simple * shorthand mechanism to put an existing (or newly created) Widget * somewhere in the dom, and allow chaining. * * @param reference Widget, DOMNode, or id of widget or DOMNode * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). */ placeAt(reference: HTMLElement, position: String): any; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. * A convenience function provided in all _Widgets, providing a simple * shorthand mechanism to put an existing (or newly created) Widget * somewhere in the dom, and allow chaining. * * @param reference Widget, DOMNode, or id of widget or DOMNode * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). */ placeAt(reference: dijit._WidgetBase, position: String): any; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. * A convenience function provided in all _Widgets, providing a simple * shorthand mechanism to put an existing (or newly created) Widget * somewhere in the dom, and allow chaining. * * @param reference Widget, DOMNode, or id of widget or DOMNode * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). */ placeAt(reference: String, position: number): any; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. * A convenience function provided in all _Widgets, providing a simple * shorthand mechanism to put an existing (or newly created) Widget * somewhere in the dom, and allow chaining. * * @param reference Widget, DOMNode, or id of widget or DOMNode * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). */ placeAt(reference: HTMLElement, position: number): any; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. * A convenience function provided in all _Widgets, providing a simple * shorthand mechanism to put an existing (or newly created) Widget * somewhere in the dom, and allow chaining. * * @param reference Widget, DOMNode, or id of widget or DOMNode * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). */ placeAt(reference: dijit._WidgetBase, position: number): any; /** * Processing after the DOM fragment is created * Called after the DOM fragment has been created, but not necessarily * added to the document. Do not include any operations which rely on * node dimensions or placement. * */ postCreate(): void; /** * Called after the parameters to the widget have been read-in, * but before the widget template is instantiated. Especially * useful to set properties that are referenced in the widget * template. * */ postMixInProperties(): void; /** * Removes the passed widget instance from this widget but does * not destroy it. You can also pass in an integer indicating * the index within the container to remove (ie, removeChild(5) removes the sixth widget). * * @param widget */ removeChild(widget: dijit._WidgetBase): void; /** * Removes the passed widget instance from this widget but does * not destroy it. You can also pass in an integer indicating * the index within the container to remove (ie, removeChild(5) removes the sixth widget). * * @param widget */ removeChild(widget: number): void; /** * Removes the transparent DIV cover. * */ removeCover(): void; /** * Moves all the children to containerNode. * */ reparent(): void; /** * Resets the scroll bar length, position, etc. * */ resetScrollBar(): void; /** * Call this to resize a widget, or after its size has changed. * Change size mode * When changeSize is specified, changes the marginBox of this widget * and forces it to re-layout its contents accordingly. * changeSize may specify height, width, or both. * * If resultSize is specified it indicates the size the widget will * become after changeSize has been applied. * * Notification mode * When changeSize is null, indicates that the caller has already changed * the size of the widget, or perhaps it changed because the browser * window was resized. Tells widget to re-layout its contents accordingly. * * If resultSize is also specified it indicates the size the widget has * become. * * In either mode, this method also: * * Sets this._borderBox and this._contentBox to the new size of * the widget. Queries the current domNode size if necessary. * Calls layout() to resize contents (and maybe adjust child widgets). * * @param changeSize OptionalSets the widget to this margin-box size and position.May include any/all of the following properties:{w: int, h: int, l: int, t: int} * @param resultSize OptionalThe margin-box size of this widget after applying changeSize (ifchangeSize is specified). If caller knows this size andpasses it in, we don't need to query the browser to get the size.{w: int, h: int} */ resize(changeSize?: Object, resultSize?: Object): void; /** * Scrolls the pane until the searching node is in the view. * Just like the scrollIntoView method of DOM elements, this * function causes the given node to scroll into view, aligning it * either at the top or bottom of the pane. * * @param node A DOM node to be searched for view. * @param alignWithTop OptionalIf true, aligns the node at the top of the pane.If false, aligns the node at the bottom of the pane. * @param duration OptionalDuration of scrolling in seconds. (ex. 0.3)If not specified, scrolls without animation. */ scrollIntoView(node: HTMLElement, alignWithTop: boolean, duration: number): void; /** * Moves the scroll bar(s) to the given position without animation. * * @param to The destination position. An object with x and/or y.ex. {x:2, y:5}, {y:20}, etc. */ scrollScrollBarTo(to: Object): void; /** * Scrolls to the given position immediately without animation. * * @param to The destination position. An object with x and y.ex. {x:0, y:-5} * @param doNotMoveScrollBar OptionalIf true, the scroll bar will not be updated. If not specified,it will be updated. * @param node OptionalA DOM node to scroll. If not specified, defaults tothis.containerNode. */ scrollTo(to: Object, doNotMoveScrollBar: boolean, node: HTMLElement): void; /** * Set a property on a widget * Sets named properties on a widget which may potentially be handled by a * setter in the widget. * * For example, if the widget has properties foo and bar * and a method named _setFooAttr(), calling * myWidget.set("foo", "Howdy!") would be equivalent to calling * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) * would be equivalent to the statement widget.bar = 3; * * set() may also be called with a hash of name/value pairs, ex: * * myWidget.set({ * foo: "Howdy", * bar: 3 * }); * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) * * @param name The property to set. * @param value The value to set in the property. */ set(name: any, value: any): any; /** * Programmatically sets key frames for the scroll animation. * * @param from * @param to * @param idx */ setKeyframes(from: Object, to: Object, idx: number): void; /** * Sets the given node as selectable or unselectable. * * @param node * @param selectable */ setSelectable(node: HTMLElement, selectable: boolean): void; /** * Shows the scroll bar. * This function creates the scroll bar instance if it does not * exist yet, and calls resetScrollBar() to reset its length and * position. * */ showScrollBar(): void; /** * Moves the scroll bar(s) to the given position with the slide animation. * * @param to The destination position. An object with x and y.ex. {x:0, y:-5} * @param duration Duration of the animation in seconds. (ex. 0.3) * @param easing The name of easing effect which webkit supports."ease", "linear", "ease-in", "ease-out", etc. */ slideScrollBarTo(to: Object, duration: number, easing: String): void; /** * Scrolls to the given position with the slide animation. * * @param to The scroll destination position. An object with x and/or y.ex. {x:0, y:-5}, {y:-29}, etc. * @param duration Duration of scrolling in seconds. (ex. 0.3) * @param easing The name of easing effect which webkit supports."ease", "linear", "ease-in", "ease-out", etc. */ slideTo(to: Object, duration: number, easing: String): void; /** * */ startup(): void; /** * Stops the currently running animation. * */ stopAnimation(): void; /** * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. * * Subscribes to the specified topic and calls the specified method * of this object and registers for unsubscribe() on widget destroy. * * Provide widget-specific analog to dojo.subscribe, except with the * implicit use of this widget as the target object. * * @param t The topic * @param method The callback */ subscribe(t: String, method: Function): any; /** * Returns a string that represents the widget. * When a widget is cast to a string, this method will be used to generate the * output. Currently, it does not implement any sort of reversible * serialization. * */ toString(): string; /** * Deprecated. Override destroy() instead to implement custom widget tear-down * behavior. * */ uninitialize(): boolean; /** * Deprecated, will be removed in 2.0, use handle.remove() instead. * * Unsubscribes handle created by this.subscribe. * Also removes handle from this widget's list of subscriptions * * @param handle */ unsubscribe(handle: Object): void; /** * Watches a property for changes * * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. */ watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; /** * called after a scroll has been performed. * * @param e the scroll event, that contains the following attributes:x (x coordinate of the scroll destination),y (y coordinate of the scroll destination),beforeTop (a boolean that is true if the scroll detination is before the top of the scrollable),beforeTopHeight (the number of pixels before the top of the scrollable for the scroll destination),afterBottom (a boolean that is true if the scroll destination is after the bottom of the scrollable),afterBottomHeight (the number of pixels after the bottom of the scrollable for the scroll destination) */ onAfterScroll(e: Event): void; /** * called before a scroll is initiated. If this method returns false, * the scroll is canceled. * * @param e the scroll event, that contains the following attributes:x (x coordinate of the scroll destination),y (y coordinate of the scroll destination),beforeTop (a boolean that is true if the scroll detination is before the top of the scrollable),beforeTopHeight (the number of pixels before the top of the scrollable for the scroll destination),afterBottom (a boolean that is true if the scroll destination is after the bottom of the scrollable),afterBottomHeight (the number of pixels after the bottom of the scrollable for the scroll destination) */ onBeforeScroll(e: Event): boolean; /** * Called when the widget stops being "active" because * focus moved to something outside of it, or the user * clicked somewhere outside of it, or the widget was * hidden. * */ onBlur(): void; /** * * @param e */ onFlickAnimationEnd(e: any): void; /** * * @param e */ onFlickAnimationStart(e: any): void; /** * Called when the widget becomes "active" because * it or a widget inside of it either has focus, or has recently * been clicked. * */ onFocus(): void; /** * User-defined function to handle touchEnd events. * * @param e */ onTouchEnd(e: Event): void; /** * User-defined function to handle touchMove events. * * @param e */ onTouchMove(e: any): void; /** * User-defined function to handle touchStart events. * * @param e */ onTouchStart(e: any): void; } } } } declare module "dojox/app/main" { var exp: dojox.app.main export=exp; } declare module "dojox/app/Controller" { var exp: dojox.app.Controller export=exp; } declare module "dojox/app/ViewBase" { var exp: dojox.app.ViewBase export=exp; } declare module "dojox/app/View" { var exp: dojox.app.View export=exp; } declare module "dojox/app/controllers/BorderLayout" { var exp: dojox.app.controllers.BorderLayout export=exp; } declare module "dojox/app/controllers/History" { var exp: dojox.app.controllers.History export=exp; } declare module "dojox/app/controllers/HistoryHash" { var exp: dojox.app.controllers.HistoryHash export=exp; } declare module "dojox/app/controllers/Layout" { var exp: dojox.app.controllers.Layout export=exp; } declare module "dojox/app/controllers/LayoutBase" { var exp: dojox.app.controllers.LayoutBase export=exp; } declare module "dojox/app/controllers/Load" { var exp: dojox.app.controllers.Load export=exp; } declare module "dojox/app/controllers/Transition" { var exp: dojox.app.controllers.Transition export=exp; } declare module "dojox/app/module/env" { var exp: dojox.app.module.env export=exp; } declare module "dojox/app/module/lifecycle" { var exp: dojox.app.module.lifecycle export=exp; } declare module "dojox/app/utils/mvcModel" { var exp: dojox.app.utils.mvcModel export=exp; } declare module "dojox/app/utils/nls" { var exp: dojox.app.utils.nls export=exp; } declare module "dojox/app/utils/model" { var exp: dojox.app.utils.model export=exp; } declare module "dojox/app/utils/simpleModel" { var exp: dojox.app.utils.simpleModel export=exp; } declare module "dojox/app/utils/config" { var exp: dojox.app.utils.config export=exp; } declare module "dojox/app/utils/constraints" { var exp: dojox.app.utils.constraints export=exp; } declare module "dojox/app/utils/layout" { var exp: dojox.app.utils.layout export=exp; } declare module "dojox/app/utils/hash" { var exp: dojox.app.utils.hash export=exp; } declare module "dojox/app/widgets/_ScrollableMixin" { var exp: dojox.app.widgets._ScrollableMixin export=exp; } declare module "dojox/app/widgets/Container" { var exp: dojox.app.widgets.Container export=exp; }
the_stack
import { mock, instance, spy, verify, anyOfClass, anything, objectContaining } from 'ts-mockito'; import Entity from '../Entity'; import { EntityCompanionDefinition } from '../EntityCompanionProvider'; import EntityConfiguration from '../EntityConfiguration'; import { UUIDField } from '../EntityFields'; import EntityPrivacyPolicy, { EntityPrivacyPolicyEvaluator, EntityAuthorizationAction, EntityPrivacyPolicyEvaluationMode, } from '../EntityPrivacyPolicy'; import { EntityQueryContext } from '../EntityQueryContext'; import ViewerContext from '../ViewerContext'; import EntityNotAuthorizedError from '../errors/EntityNotAuthorizedError'; import IEntityMetricsAdapter, { EntityMetricsAuthorizationResult, } from '../metrics/IEntityMetricsAdapter'; import AlwaysAllowPrivacyPolicyRule from '../rules/AlwaysAllowPrivacyPolicyRule'; import AlwaysDenyPrivacyPolicyRule from '../rules/AlwaysDenyPrivacyPolicyRule'; import AlwaysSkipPrivacyPolicyRule from '../rules/AlwaysSkipPrivacyPolicyRule'; import PrivacyPolicyRule, { RuleEvaluationResult } from '../rules/PrivacyPolicyRule'; type BlahFields = { id: string; }; class BlahEntity extends Entity<BlahFields, string, ViewerContext> { static getCompanionDefinition(): EntityCompanionDefinition< BlahFields, string, ViewerContext, BlahEntity, any > { return blahEntityCompanionDefinition; } } class AlwaysDenyPolicy extends EntityPrivacyPolicy<BlahFields, string, ViewerContext, BlahEntity> { protected override readonly createRules = [ new AlwaysDenyPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly readRules = [ new AlwaysDenyPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly updateRules = [ new AlwaysDenyPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly deleteRules = [ new AlwaysDenyPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; } class DryRunAlwaysDenyPolicy extends AlwaysDenyPolicy { // public method for test spying public denyHandler( _error: EntityNotAuthorizedError<BlahFields, string, ViewerContext, BlahEntity> ): void {} protected override getPrivacyPolicyEvaluator(): EntityPrivacyPolicyEvaluator< BlahFields, string, ViewerContext, BlahEntity > { return { mode: EntityPrivacyPolicyEvaluationMode.DRY_RUN, denyHandler: this.denyHandler, }; } } class LoggingEnforceAlwaysDenyPolicy extends AlwaysDenyPolicy { // public method for test spying public denyHandler( _error: EntityNotAuthorizedError<BlahFields, string, ViewerContext, BlahEntity> ): void {} protected override getPrivacyPolicyEvaluator(): EntityPrivacyPolicyEvaluator< BlahFields, string, ViewerContext, BlahEntity > { return { mode: EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG, denyHandler: this.denyHandler, }; } } class AlwaysAllowPolicy extends EntityPrivacyPolicy<BlahFields, string, ViewerContext, BlahEntity> { protected override readonly createRules = [ new AlwaysAllowPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly readRules = [ new AlwaysAllowPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly updateRules = [ new AlwaysAllowPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly deleteRules = [ new AlwaysAllowPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; } class DryRunAlwaysAllowPolicy extends AlwaysAllowPolicy { // public method for test spying public denyHandler( _error: EntityNotAuthorizedError<BlahFields, string, ViewerContext, BlahEntity> ): void {} protected override getPrivacyPolicyEvaluator(): EntityPrivacyPolicyEvaluator< BlahFields, string, ViewerContext, BlahEntity > { return { mode: EntityPrivacyPolicyEvaluationMode.DRY_RUN, denyHandler: this.denyHandler, }; } } class LoggingEnforceAlwaysAllowPolicy extends AlwaysAllowPolicy { // public method for test spying public denyHandler( _error: EntityNotAuthorizedError<BlahFields, string, ViewerContext, BlahEntity> ): void {} protected override getPrivacyPolicyEvaluator(): EntityPrivacyPolicyEvaluator< BlahFields, string, ViewerContext, BlahEntity > { return { mode: EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG, denyHandler: this.denyHandler, }; } } class SkipAllPolicy extends EntityPrivacyPolicy<BlahFields, string, ViewerContext, BlahEntity> { protected override readonly createRules = [ new AlwaysSkipPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly readRules = [ new AlwaysSkipPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly updateRules = [ new AlwaysSkipPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; protected override readonly deleteRules = [ new AlwaysSkipPrivacyPolicyRule<BlahFields, string, ViewerContext, BlahEntity>(), ]; } class AlwaysThrowPrivacyPolicyRule extends PrivacyPolicyRule< BlahFields, string, ViewerContext, BlahEntity > { evaluateAsync( _viewerContext: ViewerContext, _queryContext: EntityQueryContext, _entity: BlahEntity ): Promise<RuleEvaluationResult> { throw new Error('WooHoo!'); } } class ThrowAllPolicy extends EntityPrivacyPolicy<BlahFields, string, ViewerContext, BlahEntity> { protected override readonly createRules = [new AlwaysThrowPrivacyPolicyRule()]; protected override readonly readRules = [new AlwaysThrowPrivacyPolicyRule()]; protected override readonly updateRules = [new AlwaysThrowPrivacyPolicyRule()]; protected override readonly deleteRules = [new AlwaysThrowPrivacyPolicyRule()]; } class DryRunThrowAllPolicy extends ThrowAllPolicy { // public method for test spying public denyHandler( _error: EntityNotAuthorizedError<BlahFields, string, ViewerContext, BlahEntity> ): void {} protected override getPrivacyPolicyEvaluator(): EntityPrivacyPolicyEvaluator< BlahFields, string, ViewerContext, BlahEntity > { return { mode: EntityPrivacyPolicyEvaluationMode.DRY_RUN, denyHandler: this.denyHandler, }; } } class LoggingEnforceThrowAllPolicy extends ThrowAllPolicy { // public method for test spying public denyHandler( _error: EntityNotAuthorizedError<BlahFields, string, ViewerContext, BlahEntity> ): void {} protected override getPrivacyPolicyEvaluator(): EntityPrivacyPolicyEvaluator< BlahFields, string, ViewerContext, BlahEntity > { return { mode: EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG, denyHandler: this.denyHandler, }; } } class EmptyPolicy extends EntityPrivacyPolicy<BlahFields, string, ViewerContext, BlahEntity> { protected override readonly createRules = []; protected override readonly readRules = []; protected override readonly updateRules = []; protected override readonly deleteRules = []; } const blahEntityCompanionDefinition = new EntityCompanionDefinition({ entityClass: BlahEntity, entityConfiguration: new EntityConfiguration<BlahFields>({ idField: 'id', tableName: 'blah_table', schema: { id: new UUIDField({ columnName: 'id', }), }, databaseAdapterFlavor: 'postgres', cacheAdapterFlavor: 'redis', }), privacyPolicyClass: AlwaysDenyPolicy, }); describe(EntityPrivacyPolicy, () => { describe(EntityPrivacyPolicyEvaluationMode.ENFORCE.toString(), () => { it('throws EntityNotAuthorizedError when deny', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new AlwaysDenyPolicy(); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toBeInstanceOf(EntityNotAuthorizedError); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.DENY, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.ENFORCE, }) ) ).once(); }); it('returns entity when allowed', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new AlwaysAllowPolicy(); const approvedEntity = await policy.authorizeCreateAsync( viewerContext, queryContext, entity, metricsAdapter ); expect(approvedEntity).toEqual(entity); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.ALLOW, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.ENFORCE, }) ) ).once(); }); it('throws EntityNotAuthorizedError when all skipped', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new SkipAllPolicy(); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toBeInstanceOf(EntityNotAuthorizedError); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.DENY, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.ENFORCE, }) ) ).once(); }); it('throws EntityNotAuthorizedError when empty policy', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new EmptyPolicy(); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toBeInstanceOf(EntityNotAuthorizedError); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.DENY, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.ENFORCE, }) ) ).once(); }); it('throws when rule throws', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new ThrowAllPolicy(); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toThrowError('WooHoo!'); verify(metricsAdapterMock.logAuthorizationEvent(anything())).never(); }); }); describe(EntityPrivacyPolicyEvaluationMode.DRY_RUN.toString(), () => { it('returns entity when denied but calls denialHandler', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new DryRunAlwaysDenyPolicy(); const policySpy = spy(policy); const approvedEntity = await policy.authorizeCreateAsync( viewerContext, queryContext, entity, metricsAdapter ); expect(approvedEntity).toEqual(entity); verify(policySpy.denyHandler(anyOfClass(EntityNotAuthorizedError))).once(); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.DENY, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.DRY_RUN, }) ) ).once(); }); it('does not log when not denied', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new DryRunAlwaysAllowPolicy(); const policySpy = spy(policy); const approvedEntity = await policy.authorizeCreateAsync( viewerContext, queryContext, entity, metricsAdapter ); expect(approvedEntity).toEqual(entity); verify(policySpy.denyHandler(anyOfClass(EntityNotAuthorizedError))).never(); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.ALLOW, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.DRY_RUN, }) ) ).once(); }); it('passes through other errors', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new DryRunThrowAllPolicy(); const policySpy = spy(policy); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toThrowError('WooHoo!'); verify(policySpy.denyHandler(anyOfClass(EntityNotAuthorizedError))).never(); verify(metricsAdapterMock.logAuthorizationEvent(anything())).never(); }); }); describe(EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG.toString(), () => { it('denies when denied but calls denialHandler', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new LoggingEnforceAlwaysDenyPolicy(); const policySpy = spy(policy); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toBeInstanceOf(EntityNotAuthorizedError); verify(policySpy.denyHandler(anyOfClass(EntityNotAuthorizedError))).once(); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.DENY, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG, }) ) ).once(); }); it('does not log when not denied', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new LoggingEnforceAlwaysAllowPolicy(); const policySpy = spy(policy); const approvedEntity = await policy.authorizeCreateAsync( viewerContext, queryContext, entity, metricsAdapter ); expect(approvedEntity).toEqual(entity); verify(policySpy.denyHandler(anyOfClass(EntityNotAuthorizedError))).never(); verify( metricsAdapterMock.logAuthorizationEvent( objectContaining({ entityClassName: entity.constructor.name, action: EntityAuthorizationAction.CREATE, evaluationResult: EntityMetricsAuthorizationResult.ALLOW, privacyPolicyEvaluationMode: EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG, }) ) ).once(); }); it('passes through other errors', async () => { const viewerContext = instance(mock(ViewerContext)); const queryContext = instance(mock(EntityQueryContext)); const metricsAdapterMock = mock<IEntityMetricsAdapter>(); const metricsAdapter = instance(metricsAdapterMock); const entity = new BlahEntity(viewerContext, { id: '1' }); const policy = new LoggingEnforceThrowAllPolicy(); const policySpy = spy(policy); await expect( policy.authorizeCreateAsync(viewerContext, queryContext, entity, metricsAdapter) ).rejects.toThrowError('WooHoo!'); verify(policySpy.denyHandler(anyOfClass(EntityNotAuthorizedError))).never(); verify(metricsAdapterMock.logAuthorizationEvent(anything())).never(); }); }); });
the_stack
import { OfficeExtension } from "../api-extractor-inputs-office/office" import { Office as Outlook} from "../api-extractor-inputs-outlook/outlook" //////////////////////////////////////////////////////////////// /////////////////////// Begin Visio APIs /////////////////////// //////////////////////////////////////////////////////////////// export declare namespace Visio { /** * * Provides information about the shape that raised the ShapeMouseEnter event. * * [Api set: 1.1] */ export interface ShapeMouseEnterEventArgs { /** * * Gets the name of the page which has the shape object that raised the ShapeMouseEnter event. * * [Api set: 1.1] */ pageName: string; /** * * Gets the name of the shape object that raised the ShapeMouseEnter event. * * [Api set: 1.1] */ shapeName: string; } /** * * Provides information about the shape that raised the ShapeMouseLeave event. * * [Api set: 1.1] */ export interface ShapeMouseLeaveEventArgs { /** * * Gets the name of the page which has the shape object that raised the ShapeMouseLeave event. * * [Api set: 1.1] */ pageName: string; /** * * Gets the name of the shape object that raised the ShapeMouseLeave event. * * [Api set: 1.1] */ shapeName: string; } /** * * Provides information about the page that raised the PageLoadComplete event. * * [Api set: 1.1] */ export interface PageLoadCompleteEventArgs { /** * * Gets the name of the page that raised the PageLoad event. * * [Api set: 1.1] */ pageName: string; /** * * Gets the success or failure of the PageLoadComplete event. * * [Api set: 1.1] */ success: boolean; } /** * * Provides information about the document that raised the DataRefreshComplete event. * * [Api set: 1.1] */ export interface DataRefreshCompleteEventArgs { /** * * Gets the document object that raised the DataRefreshComplete event. * * [Api set: 1.1] */ document: Visio.Document; /** * * Gets the success or failure of the DataRefreshComplete event. * * [Api set: 1.1] */ success: boolean; } /** * * Provides information about the shape collection that raised the SelectionChanged event. * * [Api set: 1.1] */ export interface SelectionChangedEventArgs { /** * * Gets the name of the page which has the ShapeCollection object that raised the SelectionChanged event. * * [Api set: 1.1] */ pageName: string; /** * * Gets the array of shape names that raised the SelectionChanged event. * * [Api set: 1.1] */ shapeNames: string[]; } /** * * Provides information about the success or failure of the DocumentLoadComplete event. * * [Api set: 1.1] */ export interface DocumentLoadCompleteEventArgs { /** * * Gets the success or failure of the DocumentLoadComplete event. * * [Api set: 1.1] */ success: boolean; } /** * * Provides information about the page that raised the PageRenderComplete event. * * [Api set: 1.1] */ export interface PageRenderCompleteEventArgs { /** * * Gets the name of the page that raised the PageLoad event. * * [Api set: 1.1] */ pageName: string; /** * * Gets the success/failure of the PageRender event. * * [Api set: 1.1] */ success: boolean; } /** * * Represents the Application. * * [Api set: 1.1] */ export class Application extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Show or hide the iFrame application borders. * * [Api set: 1.1] */ showBorders: boolean; /** * * Show or hide the standard toolbars. * * [Api set: 1.1] */ showToolbars: boolean; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.Application): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ApplicationUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.Application): void; /** * * Sets the visibility of a specific toolbar in the application. * * [Api set: 1.1] * * @param id - The type of the Toolbar * @param show - Whether the toolbar is visibile or not. */ showToolbar(id: Visio.ToolBarType, show: boolean): void; /** * * Sets the visibility of a specific toolbar in the application. * * [Api set: 1.1] * * @param idString - The type of the Toolbar * @param show - Whether the toolbar is visibile or not. */ showToolbar(idString: "CommandBar" | "PageNavigationBar" | "StatusBar", show: boolean): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.ApplicationLoadOptions): Visio.Application; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Application; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Application; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Application object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.ApplicationData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.ApplicationData; } /** * * Represents the Document class. * * [Api set: 1.1] */ export class Document extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Represents a Visio application instance that contains this document. Read-only. * * [Api set: 1.1] */ readonly application: Visio.Application; /** * * Represents a collection of pages associated with the document. Read-only. * * [Api set: 1.1] */ readonly pages: Visio.PageCollection; /** * * Returns the DocumentView object. Read-only. * * [Api set: 1.1] */ readonly view: Visio.DocumentView; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.Document): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.DocumentUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.Document): void; /** * * Returns the Active Page of the document. * * [Api set: 1.1] */ getActivePage(): Visio.Page; /** * * Set the Active Page of the document. * * [Api set: 1.1] * * @param PageName - Name of the page */ setActivePage(PageName: string): void; /** * * Triggers the refresh of the data in the Diagram, for all pages. * * [Api set: 1.1] */ startDataRefresh(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Document` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Document` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Document` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.DocumentLoadOptions): Visio.Document; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Document; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Document; /** * * Occurs when the data is refreshed in the diagram. * * [Api set: 1.1] * * @eventproperty */ readonly onDataRefreshComplete: OfficeExtension.EventHandlers<Visio.DataRefreshCompleteEventArgs>; /** * * Occurs when the Document is loaded, refreshed, or changed. * * [Api set: 1.1] * * @eventproperty */ readonly onDocumentLoadComplete: OfficeExtension.EventHandlers<Visio.DocumentLoadCompleteEventArgs>; /** * * Occurs when the page is finished loading. * * [Api set: 1.1] * * @eventproperty */ readonly onPageLoadComplete: OfficeExtension.EventHandlers<Visio.PageLoadCompleteEventArgs>; /** * * Occurs when the current selection of shapes changes. * * [Api set: 1.1] * * @eventproperty */ readonly onSelectionChanged: OfficeExtension.EventHandlers<Visio.SelectionChangedEventArgs>; /** * * Occurs when the user moves the mouse pointer into the bounding box of a shape. * * [Api set: 1.1] * * @eventproperty */ readonly onShapeMouseEnter: OfficeExtension.EventHandlers<Visio.ShapeMouseEnterEventArgs>; /** * * Occurs when the user moves the mouse out of the bounding box of a shape. * * [Api set: 1.1] * * @eventproperty */ readonly onShapeMouseLeave: OfficeExtension.EventHandlers<Visio.ShapeMouseLeaveEventArgs>; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Document object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.DocumentData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.DocumentData; } /** * * Represents the DocumentView class. * * [Api set: 1.1] */ export class DocumentView extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Disable Hyperlinks. * * [Api set: 1.1] */ disableHyperlinks: boolean; /** * * Disable Pan. * * [Api set: 1.1] */ disablePan: boolean; /** * * Disable PanZoomWindow. * * [Api set: 1.1] */ disablePanZoomWindow: boolean; /** * * Disable Zoom. * * [Api set: 1.1] */ disableZoom: boolean; /** * * Hide Diagram Boundary. * * [Api set: 1.1] */ hideDiagramBoundary: boolean; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.DocumentView): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.DocumentViewUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.DocumentView): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.DocumentView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.DocumentView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.DocumentView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.DocumentViewLoadOptions): Visio.DocumentView; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.DocumentView; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.DocumentView; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.DocumentView object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.DocumentViewData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.DocumentViewData; } /** * * Represents the Page class. * * [Api set: 1.1] */ export class Page extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * All shapes in the Page, including subshapes. Read-only. * * [Api set: 1.1] */ readonly allShapes: Visio.ShapeCollection; /** * * Returns the Comments Collection. Read-only. * * [Api set: 1.1] */ readonly comments: Visio.CommentCollection; /** * * All top-level shapes in the Page.Read-only. * * [Api set: 1.1] */ readonly shapes: Visio.ShapeCollection; /** * * Returns the view of the page. Read-only. * * [Api set: 1.1] */ readonly view: Visio.PageView; /** * * Returns the height of the page. Read-only. * * [Api set: 1.1] */ readonly height: number; /** * * Index of the Page. Read-only. * * [Api set: 1.1] */ readonly index: number; /** * * Whether the page is a background page or not. Read-only. * * [Api set: 1.1] */ readonly isBackground: boolean; /** * * Page name. Read-only. * * [Api set: 1.1] */ readonly name: string; /** * * Returns the width of the page. Read-only. * * [Api set: 1.1] */ readonly width: number; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.Page): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.PageUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.Page): void; /** * * Set the page as Active Page of the document. * * [Api set: 1.1] */ activate(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Page` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Page` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Page` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.PageLoadOptions): Visio.Page; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Page; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Page; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Page object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.PageData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.PageData; } /** * * Represents the PageView class. * * [Api set: 1.1] */ export class PageView extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Get and set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. * * [Api set: 1.1] */ zoom: number; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.PageView): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.PageViewUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.PageView): void; /** * * Pans the Visio drawing to place the specified shape in the center of the view. * * [Api set: 1.1] * * @param ShapeId - ShapeId to be seen in the center. */ centerViewportOnShape(ShapeId: number): void; /** * * Fit Page to current window. * * [Api set: 1.1] */ fitToWindow(): void; /** * * Returns the position object that specifies the position of the page in the view. * * [Api set: 1.1] */ getPosition(): OfficeExtension.ClientResult<Visio.Position>; /** * * Represents the Selection in the page. * * [Api set: 1.1] */ getSelection(): Visio.Selection; /** * * To check if the shape is in view of the page or not. * * [Api set: 1.1] * * @param Shape - Shape to be checked. */ isShapeInViewport(Shape: Visio.Shape): OfficeExtension.ClientResult<boolean>; /** * * Sets the position of the page in the view. * * [Api set: 1.1] * * @param Position - Position object that specifies the new position of the page in the view. */ setPosition(Position: Visio.Position): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.PageView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.PageView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.PageView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.PageViewLoadOptions): Visio.PageView; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.PageView; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.PageView; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.PageView object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.PageViewData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.PageViewData; } /** * * Represents a collection of Page objects that are part of the document. * * [Api set: 1.1] */ export class PageCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Visio.Page[]; /** * * Gets the number of pages in the collection. * * [Api set: 1.1] */ getCount(): OfficeExtension.ClientResult<number>; /** * * Gets a page using its key (name or Id). * * [Api set: 1.1] * * @param key - Key is the name or Id of the page to be retrieved. */ getItem(key: number | string): Visio.Page; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.PageCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.PageCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.PageCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.PageCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.PageCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.PageCollection; load(option?: OfficeExtension.LoadOption): Visio.PageCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Visio.PageCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.PageCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Visio.Interfaces.PageCollectionData; } /** * * Represents the Shape Collection. * * [Api set: 1.1] */ export class ShapeCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Visio.Shape[]; /** * * Gets the number of Shapes in the collection. * * [Api set: 1.1] */ getCount(): OfficeExtension.ClientResult<number>; /** * * Gets a Shape using its key (name or Index). * * [Api set: 1.1] * * @param key - Key is the Name or Index of the shape to be retrieved. */ getItem(key: number | string): Visio.Shape; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.ShapeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.ShapeCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.ShapeCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.ShapeCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.ShapeCollection; load(option?: OfficeExtension.LoadOption): Visio.ShapeCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Visio.ShapeCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.ShapeCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Visio.Interfaces.ShapeCollectionData; } /** * * Represents the Shape class. * * [Api set: 1.1] */ export class Shape extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Returns the Comments Collection. Read-only. * * [Api set: 1.1] */ readonly comments: Visio.CommentCollection; /** * * Returns the Hyperlinks collection for a Shape object. Read-only. * * [Api set: 1.1] */ readonly hyperlinks: Visio.HyperlinkCollection; /** * * Returns the Shape's Data Section. Read-only. * * [Api set: 1.1] */ readonly shapeDataItems: Visio.ShapeDataItemCollection; /** * * Gets SubShape Collection. Read-only. * * [Api set: 1.1] */ readonly subShapes: Visio.ShapeCollection; /** * * Returns the view of the shape. Read-only. * * [Api set: 1.1] */ readonly view: Visio.ShapeView; /** * * Shape's identifier. Read-only. * * [Api set: 1.1] */ readonly id: number; /** * * Shape's name. Read-only. * * [Api set: 1.1] */ readonly name: string; /** * * Returns true, if shape is selected. User can set true to select the shape explicitly. * * [Api set: 1.1] */ select: boolean; /** * * Shape's text. Read-only. * * [Api set: 1.1] */ readonly text: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.Shape): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ShapeUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.Shape): void; /** * * Returns the BoundingBox object that specifies bounding box of the shape. * * [Api set: 1.1] */ getBounds(): OfficeExtension.ClientResult<Visio.BoundingBox>; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Shape` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Shape` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Shape` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.ShapeLoadOptions): Visio.Shape; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Shape; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Shape; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Shape object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.ShapeData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.ShapeData; } /** * * Represents the ShapeView class. * * [Api set: 1.1] */ export class ShapeView extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Represents the highlight around the shape. * * [Api set: 1.1] */ highlight: Visio.Highlight; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.ShapeView): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ShapeViewUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.ShapeView): void; /** * * Adds an overlay on top of the shape. * * [Api set: 1.1] * * @param OverlayType - An Overlay Type. Can be 'Text' or 'Image'. * @param Content - Content of Overlay. * @param OverlayHorizontalAlignment - Horizontal Alignment of Overlay. Can be 'Left', 'Center', or 'Right'. * @param OverlayVerticalAlignment - Vertical Alignment of Overlay. Can be 'Top', 'Middle', 'Bottom'. * @param Width - Overlay Width. * @param Height - Overlay Height. */ addOverlay(OverlayType: Visio.OverlayType, Content: string, OverlayHorizontalAlignment: Visio.OverlayHorizontalAlignment, OverlayVerticalAlignment: Visio.OverlayVerticalAlignment, Width: number, Height: number): OfficeExtension.ClientResult<number>; /** * * Adds an overlay on top of the shape. * * [Api set: 1.1] * * @param OverlayTypeString - An Overlay Type. Can be 'Text' or 'Image'. * @param Content - Content of Overlay. * @param OverlayHorizontalAlignment - Horizontal Alignment of Overlay. Can be 'Left', 'Center', or 'Right'. * @param OverlayVerticalAlignment - Vertical Alignment of Overlay. Can be 'Top', 'Middle', 'Bottom'. * @param Width - Overlay Width. * @param Height - Overlay Height. */ addOverlay(OverlayTypeString: "Text" | "Image" | "Html", Content: string, OverlayHorizontalAlignment: "Left" | "Center" | "Right", OverlayVerticalAlignment: "Top" | "Middle" | "Bottom", Width: number, Height: number): OfficeExtension.ClientResult<number>; /** * * Removes particular overlay or all overlays on the Shape. * * [Api set: 1.1] * * @param OverlayId - An Overlay Id. Removes the specific overlay id from the shape. */ removeOverlay(OverlayId: number): void; /** * * Shows particular overlay on the Shape. * * [Api set: 1.1] * * @param overlayId - overlay id in context * @param show - to show or hide */ showOverlay(overlayId: number, show: boolean): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.ShapeView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.ShapeView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.ShapeViewLoadOptions): Visio.ShapeView; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.ShapeView; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.ShapeView; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.ShapeView object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.ShapeViewData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.ShapeViewData; } /** * * Represents the Position of the object in the view. * * [Api set: 1.1] */ export interface Position { /** * * An integer that specifies the x-coordinate of the object, which is the signed value of the distance in pixels from the viewport's center to the left boundary of the page. * * [Api set: 1.1] */ x: number; /** * * An integer that specifies the y-coordinate of the object, which is the signed value of the distance in pixels from the viewport's center to the top boundary of the page. * * [Api set: 1.1] */ y: number; } /** * * Represents the BoundingBox of the shape. * * [Api set: 1.1] */ export interface BoundingBox { /** * * The distance between the top and bottom edges of the bounding box of the shape, excluding any data graphics associated with the shape. * * [Api set: 1.1] */ height: number; /** * * The distance between the left and right edges of the bounding box of the shape, excluding any data graphics associated with the shape. * * [Api set: 1.1] */ width: number; /** * * An integer that specifies the x-coordinate of the bounding box. * * [Api set: 1.1] */ x: number; /** * * An integer that specifies the y-coordinate of the bounding box. * * [Api set: 1.1] */ y: number; } /** * * Represents the highlight data added to the shape. * * [Api set: 1.1] */ export interface Highlight { /** * * A string that specifies the color of the highlight. It must have the form "#RRGGBB", where each letter represents a hexadecimal digit between 0 and F, and where RR is the red value between 0 and 0xFF (255), GG the green value between 0 and 0xFF (255), and BB is the blue value between 0 and 0xFF (255). * * [Api set: 1.1] */ color: string; /** * * A positive integer that specifies the width of the highlight's stroke in pixels. * * [Api set: 1.1] */ width: number; } /** * * Represents the ShapeDataItemCollection for a given Shape. * * [Api set: 1.1] */ export class ShapeDataItemCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Visio.ShapeDataItem[]; /** * * Gets the number of Shape Data Items. * * [Api set: 1.1] */ getCount(): OfficeExtension.ClientResult<number>; /** * * Gets the ShapeDataItem using its name. * * [Api set: 1.1] * * @param key - Key is the name of the ShapeDataItem to be retrieved. */ getItem(key: string): Visio.ShapeDataItem; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.ShapeDataItemCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.ShapeDataItemCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeDataItemCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.ShapeDataItemCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.ShapeDataItemCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.ShapeDataItemCollection; load(option?: OfficeExtension.LoadOption): Visio.ShapeDataItemCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Visio.ShapeDataItemCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.ShapeDataItemCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Visio.Interfaces.ShapeDataItemCollectionData; } /** * * Represents the ShapeDataItem. * * [Api set: 1.1] */ export class ShapeDataItem extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * A string that specifies the format of the shape data item. Read-only. * * [Api set: 1.1] */ readonly format: string; /** * * A string that specifies the formatted value of the shape data item. Read-only. * * [Api set: 1.1] */ readonly formattedValue: string; /** * * A string that specifies the label of the shape data item. Read-only. * * [Api set: 1.1] */ readonly label: string; /** * * A string that specifies the value of the shape data item. Read-only. * * [Api set: 1.1] */ readonly value: string; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.ShapeDataItem` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.ShapeDataItem` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeDataItem` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.ShapeDataItemLoadOptions): Visio.ShapeDataItem; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.ShapeDataItem; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.ShapeDataItem; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.ShapeDataItem object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.ShapeDataItemData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.ShapeDataItemData; } /** * * Represents the Hyperlink Collection. * * [Api set: 1.1] */ export class HyperlinkCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Visio.Hyperlink[]; /** * * Gets the number of hyperlinks. * * [Api set: 1.1] */ getCount(): OfficeExtension.ClientResult<number>; /** * * Gets a Hyperlink using its key (name or Id). * * [Api set: 1.1] * * @param Key - Key is the name or index of the Hyperlink to be retrieved. */ getItem(Key: number | string): Visio.Hyperlink; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.HyperlinkCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.HyperlinkCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.HyperlinkCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.HyperlinkCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.HyperlinkCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.HyperlinkCollection; load(option?: OfficeExtension.LoadOption): Visio.HyperlinkCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Visio.HyperlinkCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.HyperlinkCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Visio.Interfaces.HyperlinkCollectionData; } /** * * Represents the Hyperlink. * * [Api set: 1.1] */ export class Hyperlink extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ readonly address: string; /** * * Gets the description of a hyperlink. Read-only. * * [Api set: 1.1] */ readonly description: string; /** * * Gets the extra URL request information used to resolve the hyperlink's URL. Read-only. * * [Api set: 1.1] */ readonly extraInfo: string; /** * * Gets the sub-address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ readonly subAddress: string; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Hyperlink` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Hyperlink` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Hyperlink` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.HyperlinkLoadOptions): Visio.Hyperlink; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Hyperlink; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Hyperlink; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Hyperlink object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.HyperlinkData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.HyperlinkData; } /** * * Represents the CommentCollection for a given Shape. * * [Api set: 1.1] */ export class CommentCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Visio.Comment[]; /** * * Gets the number of Comments. * * [Api set: 1.1] */ getCount(): OfficeExtension.ClientResult<number>; /** * * Gets the Comment using its name. * * [Api set: 1.1] * * @param key - Key is the name of the Comment to be retrieved. */ getItem(key: string): Visio.Comment; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.CommentCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.CommentCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.CommentCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.CommentCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.CommentCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.CommentCollection; load(option?: OfficeExtension.LoadOption): Visio.CommentCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Visio.CommentCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.CommentCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Visio.Interfaces.CommentCollectionData; } /** * * Represents the Comment. * * [Api set: 1.1] */ export class Comment extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * A string that specifies the name of the author of the comment. * * [Api set: 1.1] */ author: string; /** * * A string that specifies the date when the comment was created. * * [Api set: 1.1] */ date: string; /** * * A string that contains the comment text. * * [Api set: 1.1] */ text: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: Visio.Comment): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.CommentUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Visio.Comment): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Comment` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Comment` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Comment` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: Visio.Interfaces.CommentLoadOptions): Visio.Comment; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Comment; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Comment; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Comment object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.CommentData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.CommentData; } /** * * Represents the Selection in the page. * * [Api set: 1.1] */ export class Selection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the Shapes of the Selection. Read-only. * * [Api set: 1.1] */ readonly shapes: Visio.ShapeCollection; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): Visio.Selection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): Visio.Selection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Selection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Visio.Selection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Visio.Selection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Visio.Selection object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Visio.Interfaces.SelectionData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Visio.Interfaces.SelectionData; } /** * * Represents the Horizontal Alignment of the Overlay relative to the shape. * * [Api set: 1.1] */ enum OverlayHorizontalAlignment { /** * * left * */ left = "Left", /** * * center * */ center = "Center", /** * * right * */ right = "Right", } /** * * Represents the Vertical Alignment of the Overlay relative to the shape. * * [Api set: 1.1] */ enum OverlayVerticalAlignment { /** * * top * */ top = "Top", /** * * middle * */ middle = "Middle", /** * * bottom * */ bottom = "Bottom", } /** * * Represents the type of the overlay. * * [Api set: 1.1] */ enum OverlayType { /** * * text * */ text = "Text", /** * * image * */ image = "Image", /** * * html * */ html = "Html", } /** * * Toolbar IDs of the app * * [Api set: 1.1] */ enum ToolBarType { /** * * CommandBar * */ commandBar = "CommandBar", /** * * PageNavigationBar * */ pageNavigationBar = "PageNavigationBar", /** * * StatusBar * */ statusBar = "StatusBar", } enum ErrorCodes { accessDenied = "AccessDenied", generalException = "GeneralException", invalidArgument = "InvalidArgument", itemNotFound = "ItemNotFound", notImplemented = "NotImplemented", unsupportedOperation = "UnsupportedOperation", } export module Interfaces { /** * Provides ways to load properties of only a subset of members of a collection. */ export interface CollectionLoadOptions { /** * Specify the number of items in the queried collection to be included in the result. */ $top?: number; /** * Specify the number of items in the collection that are to be skipped and not included in the result. If top is specified, the selection of result will start after skipping the specified number of items. */ $skip?: number; } /** An interface for updating data on the Application object, for use in "application.set({ ... })". */ export interface ApplicationUpdateData { /** * * Show or hide the iFrame application borders. * * [Api set: 1.1] */ showBorders?: boolean; /** * * Show or hide the standard toolbars. * * [Api set: 1.1] */ showToolbars?: boolean; } /** An interface for updating data on the Document object, for use in "document.set({ ... })". */ export interface DocumentUpdateData { /** * * Represents a Visio application instance that contains this document. * * [Api set: 1.1] */ application?: Visio.Interfaces.ApplicationUpdateData; /** * * Returns the DocumentView object. * * [Api set: 1.1] */ view?: Visio.Interfaces.DocumentViewUpdateData; } /** An interface for updating data on the DocumentView object, for use in "documentView.set({ ... })". */ export interface DocumentViewUpdateData { /** * * Disable Hyperlinks. * * [Api set: 1.1] */ disableHyperlinks?: boolean; /** * * Disable Pan. * * [Api set: 1.1] */ disablePan?: boolean; /** * * Disable PanZoomWindow. * * [Api set: 1.1] */ disablePanZoomWindow?: boolean; /** * * Disable Zoom. * * [Api set: 1.1] */ disableZoom?: boolean; /** * * Hide Diagram Boundary. * * [Api set: 1.1] */ hideDiagramBoundary?: boolean; } /** An interface for updating data on the Page object, for use in "page.set({ ... })". */ export interface PageUpdateData { /** * * Returns the view of the page. * * [Api set: 1.1] */ view?: Visio.Interfaces.PageViewUpdateData; } /** An interface for updating data on the PageView object, for use in "pageView.set({ ... })". */ export interface PageViewUpdateData { /** * * Get and set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. * * [Api set: 1.1] */ zoom?: number; } /** An interface for updating data on the PageCollection object, for use in "pageCollection.set({ ... })". */ export interface PageCollectionUpdateData { items?: Visio.Interfaces.PageData[]; } /** An interface for updating data on the ShapeCollection object, for use in "shapeCollection.set({ ... })". */ export interface ShapeCollectionUpdateData { items?: Visio.Interfaces.ShapeData[]; } /** An interface for updating data on the Shape object, for use in "shape.set({ ... })". */ export interface ShapeUpdateData { /** * * Returns the view of the shape. * * [Api set: 1.1] */ view?: Visio.Interfaces.ShapeViewUpdateData; /** * * Returns true, if shape is selected. User can set true to select the shape explicitly. * * [Api set: 1.1] */ select?: boolean; } /** An interface for updating data on the ShapeView object, for use in "shapeView.set({ ... })". */ export interface ShapeViewUpdateData { /** * * Represents the highlight around the shape. * * [Api set: 1.1] */ highlight?: Visio.Highlight; } /** An interface for updating data on the ShapeDataItemCollection object, for use in "shapeDataItemCollection.set({ ... })". */ export interface ShapeDataItemCollectionUpdateData { items?: Visio.Interfaces.ShapeDataItemData[]; } /** An interface for updating data on the HyperlinkCollection object, for use in "hyperlinkCollection.set({ ... })". */ export interface HyperlinkCollectionUpdateData { items?: Visio.Interfaces.HyperlinkData[]; } /** An interface for updating data on the CommentCollection object, for use in "commentCollection.set({ ... })". */ export interface CommentCollectionUpdateData { items?: Visio.Interfaces.CommentData[]; } /** An interface for updating data on the Comment object, for use in "comment.set({ ... })". */ export interface CommentUpdateData { /** * * A string that specifies the name of the author of the comment. * * [Api set: 1.1] */ author?: string; /** * * A string that specifies the date when the comment was created. * * [Api set: 1.1] */ date?: string; /** * * A string that contains the comment text. * * [Api set: 1.1] */ text?: string; } /** An interface describing the data returned by calling "application.toJSON()". */ export interface ApplicationData { /** * * Show or hide the iFrame application borders. * * [Api set: 1.1] */ showBorders?: boolean; /** * * Show or hide the standard toolbars. * * [Api set: 1.1] */ showToolbars?: boolean; } /** An interface describing the data returned by calling "document.toJSON()". */ export interface DocumentData { /** * * Represents a Visio application instance that contains this document. Read-only. * * [Api set: 1.1] */ application?: Visio.Interfaces.ApplicationData; /** * * Represents a collection of pages associated with the document. Read-only. * * [Api set: 1.1] */ pages?: Visio.Interfaces.PageData[]; /** * * Returns the DocumentView object. Read-only. * * [Api set: 1.1] */ view?: Visio.Interfaces.DocumentViewData; } /** An interface describing the data returned by calling "documentView.toJSON()". */ export interface DocumentViewData { /** * * Disable Hyperlinks. * * [Api set: 1.1] */ disableHyperlinks?: boolean; /** * * Disable Pan. * * [Api set: 1.1] */ disablePan?: boolean; /** * * Disable PanZoomWindow. * * [Api set: 1.1] */ disablePanZoomWindow?: boolean; /** * * Disable Zoom. * * [Api set: 1.1] */ disableZoom?: boolean; /** * * Hide Diagram Boundary. * * [Api set: 1.1] */ hideDiagramBoundary?: boolean; } /** An interface describing the data returned by calling "page.toJSON()". */ export interface PageData { /** * * All shapes in the Page, including subshapes. Read-only. * * [Api set: 1.1] */ allShapes?: Visio.Interfaces.ShapeData[]; /** * * Returns the Comments Collection. Read-only. * * [Api set: 1.1] */ comments?: Visio.Interfaces.CommentData[]; /** * * All top-level shapes in the Page.Read-only. * * [Api set: 1.1] */ shapes?: Visio.Interfaces.ShapeData[]; /** * * Returns the view of the page. Read-only. * * [Api set: 1.1] */ view?: Visio.Interfaces.PageViewData; /** * * Returns the height of the page. Read-only. * * [Api set: 1.1] */ height?: number; /** * * Index of the Page. Read-only. * * [Api set: 1.1] */ index?: number; /** * * Whether the page is a background page or not. Read-only. * * [Api set: 1.1] */ isBackground?: boolean; /** * * Page name. Read-only. * * [Api set: 1.1] */ name?: string; /** * * Returns the width of the page. Read-only. * * [Api set: 1.1] */ width?: number; } /** An interface describing the data returned by calling "pageView.toJSON()". */ export interface PageViewData { /** * * Get and set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. * * [Api set: 1.1] */ zoom?: number; } /** An interface describing the data returned by calling "pageCollection.toJSON()". */ export interface PageCollectionData { items?: Visio.Interfaces.PageData[]; } /** An interface describing the data returned by calling "shapeCollection.toJSON()". */ export interface ShapeCollectionData { items?: Visio.Interfaces.ShapeData[]; } /** An interface describing the data returned by calling "shape.toJSON()". */ export interface ShapeData { /** * * Returns the Comments Collection. Read-only. * * [Api set: 1.1] */ comments?: Visio.Interfaces.CommentData[]; /** * * Returns the Hyperlinks collection for a Shape object. Read-only. * * [Api set: 1.1] */ hyperlinks?: Visio.Interfaces.HyperlinkData[]; /** * * Returns the Shape's Data Section. Read-only. * * [Api set: 1.1] */ shapeDataItems?: Visio.Interfaces.ShapeDataItemData[]; /** * * Gets SubShape Collection. Read-only. * * [Api set: 1.1] */ subShapes?: Visio.Interfaces.ShapeData[]; /** * * Returns the view of the shape. Read-only. * * [Api set: 1.1] */ view?: Visio.Interfaces.ShapeViewData; /** * * Shape's identifier. Read-only. * * [Api set: 1.1] */ id?: number; /** * * Shape's name. Read-only. * * [Api set: 1.1] */ name?: string; /** * * Returns true, if shape is selected. User can set true to select the shape explicitly. * * [Api set: 1.1] */ select?: boolean; /** * * Shape's text. Read-only. * * [Api set: 1.1] */ text?: string; } /** An interface describing the data returned by calling "shapeView.toJSON()". */ export interface ShapeViewData { /** * * Represents the highlight around the shape. * * [Api set: 1.1] */ highlight?: Visio.Highlight; } /** An interface describing the data returned by calling "shapeDataItemCollection.toJSON()". */ export interface ShapeDataItemCollectionData { items?: Visio.Interfaces.ShapeDataItemData[]; } /** An interface describing the data returned by calling "shapeDataItem.toJSON()". */ export interface ShapeDataItemData { /** * * A string that specifies the format of the shape data item. Read-only. * * [Api set: 1.1] */ format?: string; /** * * A string that specifies the formatted value of the shape data item. Read-only. * * [Api set: 1.1] */ formattedValue?: string; /** * * A string that specifies the label of the shape data item. Read-only. * * [Api set: 1.1] */ label?: string; /** * * A string that specifies the value of the shape data item. Read-only. * * [Api set: 1.1] */ value?: string; } /** An interface describing the data returned by calling "hyperlinkCollection.toJSON()". */ export interface HyperlinkCollectionData { items?: Visio.Interfaces.HyperlinkData[]; } /** An interface describing the data returned by calling "hyperlink.toJSON()". */ export interface HyperlinkData { /** * * Gets the address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ address?: string; /** * * Gets the description of a hyperlink. Read-only. * * [Api set: 1.1] */ description?: string; /** * * Gets the extra URL request information used to resolve the hyperlink's URL. Read-only. * * [Api set: 1.1] */ extraInfo?: string; /** * * Gets the sub-address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ subAddress?: string; } /** An interface describing the data returned by calling "commentCollection.toJSON()". */ export interface CommentCollectionData { items?: Visio.Interfaces.CommentData[]; } /** An interface describing the data returned by calling "comment.toJSON()". */ export interface CommentData { /** * * A string that specifies the name of the author of the comment. * * [Api set: 1.1] */ author?: string; /** * * A string that specifies the date when the comment was created. * * [Api set: 1.1] */ date?: string; /** * * A string that contains the comment text. * * [Api set: 1.1] */ text?: string; } /** An interface describing the data returned by calling "selection.toJSON()". */ export interface SelectionData { /** * * Gets the Shapes of the Selection. Read-only. * * [Api set: 1.1] */ shapes?: Visio.Interfaces.ShapeData[]; } /** * * Represents the Application. * * [Api set: 1.1] */ export interface ApplicationLoadOptions { $all?: boolean; /** * * Show or hide the iFrame application borders. * * [Api set: 1.1] */ showBorders?: boolean; /** * * Show or hide the standard toolbars. * * [Api set: 1.1] */ showToolbars?: boolean; } /** * * Represents the Document class. * * [Api set: 1.1] */ export interface DocumentLoadOptions { $all?: boolean; /** * * Represents a Visio application instance that contains this document. * * [Api set: 1.1] */ application?: Visio.Interfaces.ApplicationLoadOptions; /** * * Returns the DocumentView object. * * [Api set: 1.1] */ view?: Visio.Interfaces.DocumentViewLoadOptions; } /** * * Represents the DocumentView class. * * [Api set: 1.1] */ export interface DocumentViewLoadOptions { $all?: boolean; /** * * Disable Hyperlinks. * * [Api set: 1.1] */ disableHyperlinks?: boolean; /** * * Disable Pan. * * [Api set: 1.1] */ disablePan?: boolean; /** * * Disable PanZoomWindow. * * [Api set: 1.1] */ disablePanZoomWindow?: boolean; /** * * Disable Zoom. * * [Api set: 1.1] */ disableZoom?: boolean; /** * * Hide Diagram Boundary. * * [Api set: 1.1] */ hideDiagramBoundary?: boolean; } /** * * Represents the Page class. * * [Api set: 1.1] */ export interface PageLoadOptions { $all?: boolean; /** * * Returns the view of the page. * * [Api set: 1.1] */ view?: Visio.Interfaces.PageViewLoadOptions; /** * * Returns the height of the page. Read-only. * * [Api set: 1.1] */ height?: boolean; /** * * Index of the Page. Read-only. * * [Api set: 1.1] */ index?: boolean; /** * * Whether the page is a background page or not. Read-only. * * [Api set: 1.1] */ isBackground?: boolean; /** * * Page name. Read-only. * * [Api set: 1.1] */ name?: boolean; /** * * Returns the width of the page. Read-only. * * [Api set: 1.1] */ width?: boolean; } /** * * Represents the PageView class. * * [Api set: 1.1] */ export interface PageViewLoadOptions { $all?: boolean; /** * * Get and set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. * * [Api set: 1.1] */ zoom?: boolean; } /** * * Represents a collection of Page objects that are part of the document. * * [Api set: 1.1] */ export interface PageCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Returns the view of the page. * * [Api set: 1.1] */ view?: Visio.Interfaces.PageViewLoadOptions; /** * * For EACH ITEM in the collection: Returns the height of the page. Read-only. * * [Api set: 1.1] */ height?: boolean; /** * * For EACH ITEM in the collection: Index of the Page. Read-only. * * [Api set: 1.1] */ index?: boolean; /** * * For EACH ITEM in the collection: Whether the page is a background page or not. Read-only. * * [Api set: 1.1] */ isBackground?: boolean; /** * * For EACH ITEM in the collection: Page name. Read-only. * * [Api set: 1.1] */ name?: boolean; /** * * For EACH ITEM in the collection: Returns the width of the page. Read-only. * * [Api set: 1.1] */ width?: boolean; } /** * * Represents the Shape Collection. * * [Api set: 1.1] */ export interface ShapeCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Returns the view of the shape. * * [Api set: 1.1] */ view?: Visio.Interfaces.ShapeViewLoadOptions; /** * * For EACH ITEM in the collection: Shape's identifier. Read-only. * * [Api set: 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Shape's name. Read-only. * * [Api set: 1.1] */ name?: boolean; /** * * For EACH ITEM in the collection: Returns true, if shape is selected. User can set true to select the shape explicitly. * * [Api set: 1.1] */ select?: boolean; /** * * For EACH ITEM in the collection: Shape's text. Read-only. * * [Api set: 1.1] */ text?: boolean; } /** * * Represents the Shape class. * * [Api set: 1.1] */ export interface ShapeLoadOptions { $all?: boolean; /** * * Returns the view of the shape. * * [Api set: 1.1] */ view?: Visio.Interfaces.ShapeViewLoadOptions; /** * * Shape's identifier. Read-only. * * [Api set: 1.1] */ id?: boolean; /** * * Shape's name. Read-only. * * [Api set: 1.1] */ name?: boolean; /** * * Returns true, if shape is selected. User can set true to select the shape explicitly. * * [Api set: 1.1] */ select?: boolean; /** * * Shape's text. Read-only. * * [Api set: 1.1] */ text?: boolean; } /** * * Represents the ShapeView class. * * [Api set: 1.1] */ export interface ShapeViewLoadOptions { $all?: boolean; /** * * Represents the highlight around the shape. * * [Api set: 1.1] */ highlight?: boolean; } /** * * Represents the ShapeDataItemCollection for a given Shape. * * [Api set: 1.1] */ export interface ShapeDataItemCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: A string that specifies the format of the shape data item. Read-only. * * [Api set: 1.1] */ format?: boolean; /** * * For EACH ITEM in the collection: A string that specifies the formatted value of the shape data item. Read-only. * * [Api set: 1.1] */ formattedValue?: boolean; /** * * For EACH ITEM in the collection: A string that specifies the label of the shape data item. Read-only. * * [Api set: 1.1] */ label?: boolean; /** * * For EACH ITEM in the collection: A string that specifies the value of the shape data item. Read-only. * * [Api set: 1.1] */ value?: boolean; } /** * * Represents the ShapeDataItem. * * [Api set: 1.1] */ export interface ShapeDataItemLoadOptions { $all?: boolean; /** * * A string that specifies the format of the shape data item. Read-only. * * [Api set: 1.1] */ format?: boolean; /** * * A string that specifies the formatted value of the shape data item. Read-only. * * [Api set: 1.1] */ formattedValue?: boolean; /** * * A string that specifies the label of the shape data item. Read-only. * * [Api set: 1.1] */ label?: boolean; /** * * A string that specifies the value of the shape data item. Read-only. * * [Api set: 1.1] */ value?: boolean; } /** * * Represents the Hyperlink Collection. * * [Api set: 1.1] */ export interface HyperlinkCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ address?: boolean; /** * * For EACH ITEM in the collection: Gets the description of a hyperlink. Read-only. * * [Api set: 1.1] */ description?: boolean; /** * * For EACH ITEM in the collection: Gets the extra URL request information used to resolve the hyperlink's URL. Read-only. * * [Api set: 1.1] */ extraInfo?: boolean; /** * * For EACH ITEM in the collection: Gets the sub-address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ subAddress?: boolean; } /** * * Represents the Hyperlink. * * [Api set: 1.1] */ export interface HyperlinkLoadOptions { $all?: boolean; /** * * Gets the address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ address?: boolean; /** * * Gets the description of a hyperlink. Read-only. * * [Api set: 1.1] */ description?: boolean; /** * * Gets the extra URL request information used to resolve the hyperlink's URL. Read-only. * * [Api set: 1.1] */ extraInfo?: boolean; /** * * Gets the sub-address of the Hyperlink object. Read-only. * * [Api set: 1.1] */ subAddress?: boolean; } /** * * Represents the CommentCollection for a given Shape. * * [Api set: 1.1] */ export interface CommentCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: A string that specifies the name of the author of the comment. * * [Api set: 1.1] */ author?: boolean; /** * * For EACH ITEM in the collection: A string that specifies the date when the comment was created. * * [Api set: 1.1] */ date?: boolean; /** * * For EACH ITEM in the collection: A string that contains the comment text. * * [Api set: 1.1] */ text?: boolean; } /** * * Represents the Comment. * * [Api set: 1.1] */ export interface CommentLoadOptions { $all?: boolean; /** * * A string that specifies the name of the author of the comment. * * [Api set: 1.1] */ author?: boolean; /** * * A string that specifies the date when the comment was created. * * [Api set: 1.1] */ date?: boolean; /** * * A string that contains the comment text. * * [Api set: 1.1] */ text?: boolean; } } } export declare namespace Visio { /** * The RequestContext object facilitates requests to the Visio application. Since the Office add-in and the Visio application run in two different processes, the request context is required to get access to the Visio object model from the add-in. */ export class RequestContext extends OfficeExtension.ClientRequestContext { constructor(url?: string | OfficeExtension.EmbeddedSession); readonly document: Document; } /** * Executes a batch script that performs actions on the Visio object model, using a new request context. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. * @param batch - A function that takes in an Visio.RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Visio application. Since the Office add-in and the Visio application run in two different processes, the request context is required to get access to the Visio object model from the add-in. */ export function run<T>(batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the Visio object model, using the request context of a previously-created API object. * @param object - A previously-created API object. The batch will use the same request context as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". * @param batch - A function that takes in an Visio.RequestContext and returns a promise (typically, just the result of "context.sync()"). When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. */ export function run<T>(object: OfficeExtension.ClientObject | OfficeExtension.EmbeddedSession, batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the Visio object model, using the request context of previously-created API objects. * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared request context, which means that any changes applied to these objects will be picked up by "context.sync()". * @param batch - A function that takes in a Visio.RequestContext and returns a promise (typically, just the result of "context.sync()"). When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. */ export function run<T>(objects: OfficeExtension.ClientObject[], batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the Visio object model, using the RequestContext of a previously-created object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. * @param contextObject - A previously-created Visio.RequestContext. This context will get re-used by the batch function (instead of having a new context created). This means that the batch will be able to pick up changes made to existing API objects, if those objects were derived from this same context. * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Visio application. Since the Office add-in and the Visio application run in two different processes, the RequestContext is required to get access to the Visio object model from the add-in. * @remarks * In addition to this signature, the method also has the following signatures: * * `run<T>(batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>;` * * `run<T>(object: OfficeExtension.ClientObject | OfficeExtension.EmbeddedSession, batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>;` * * `run<T>(objects: OfficeExtension.ClientObject[], batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>;` */ export function run<T>(contextObject: OfficeExtension.ClientRequestContext, batch: (context: Visio.RequestContext) => Promise<T>): Promise<T>; } //////////////////////////////////////////////////////////////// //////////////////////// End Visio APIs //////////////////////// ////////////////////////////////////////////////////////////////
the_stack
import { Assertion, Orbit } from '@orbit/core'; import { Dict } from '@orbit/utils'; import { DefaultRequestOptions, RequestOptions } from '@orbit/data'; import { RecordIdentity, KeyDefinition, AttributeDefinition, RelationshipDefinition, InitializedRecord, ModelDefinition } from '@orbit/records'; import { destroy, associateDestroyableChild, registerDestructor } from '@ember/destroyable'; import { tracked } from '@glimmer/tracking'; import Cache from './cache'; import { getModelDefinition } from './utils/model-definition'; import { notifyPropertyChange } from './utils/property-cache'; const { assert, deprecate } = Orbit; export interface ModelSettings { cache: Cache; identity: RecordIdentity; } export default class Model { @tracked protected _isDisconnected = false; protected _cache?: Cache; #identity: RecordIdentity; constructor(settings: ModelSettings) { const { cache, identity } = settings; assert('Model must be initialized with a cache', cache !== undefined); this._cache = cache; this.#identity = identity; associateDestroyableChild(cache, this); registerDestructor(this, (record) => cache.unload(record)); } get identity(): RecordIdentity { deprecate( '`Model#identity` is deprecated to avoid potential conflicts with field names. Access `$identity` instead.' ); return this.#identity; } get $identity(): RecordIdentity { return this.#identity; } get id(): string { return this.#identity.id; } get type(): string { return this.#identity.type; } get disconnected(): boolean { deprecate( '`Model#disconnected` is deprecated to avoid potential conflicts with field names. Access `$isDisconnected` instead.' ); return this.$isDisconnected; } get $isDisconnected(): boolean { return this._isDisconnected; } /** * @deprecated */ getData(): InitializedRecord | undefined { deprecate( '`Model#getData` is deprecated to avoid potential conflicts with field names. Call `$getData` instead.' ); return this.$getData(); } $getData(): InitializedRecord | undefined { return this.$cache.getRecordData(this.type, this.id); } /** * @deprecated */ getKey(field: string): string | undefined { deprecate( '`Model#getKey` is deprecated to avoid potential conflicts with field names. Call `$getKey` instead.' ); return this.$getKey(field); } $getKey(field: string): string | undefined { return this.$getData()?.keys?.[field]; } /** * @deprecated */ replaceKey( key: string, value: string, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#replaceKey` is deprecated to avoid potential conflicts with field names. Call `$replaceKey` instead.' ); this.$replaceKey(key, value, options); } $replaceKey( key: string, value: string, options?: DefaultRequestOptions<RequestOptions> ): void { this.$cache.update( (t) => t.replaceKey(this.#identity, key, value), options ); } /** * @deprecated */ getAttribute(attribute: string): unknown { deprecate( '`Model#getAttribute` is deprecated to avoid potential conflicts with field names. Call `$getAttribute` instead.' ); return this.$getAttribute(attribute); } $getAttribute(attribute: string): unknown { return this.$getData()?.attributes?.[attribute]; } /** * @deprecated */ replaceAttribute( attribute: string, value: unknown, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#replaceAttribute` is deprecated to avoid potential conflicts with field names. Call `$replaceAttribute` instead.' ); this.$replaceAttribute(attribute, value, options); } $replaceAttribute( attribute: string, value: unknown, options?: DefaultRequestOptions<RequestOptions> ): void { this.$cache.update( (t) => t.replaceAttribute(this.#identity, attribute, value), options ); } /** * @deprecated */ getRelatedRecord(relationship: string): Model | null | undefined { deprecate( '`Model#getRelatedRecord` is deprecated to avoid potential conflicts with field names. Call `$getRelatedRecord` instead.' ); return this.$getRelatedRecord(relationship); } $getRelatedRecord(relationship: string): Model | null | undefined { const cache = this.$cache; const relatedRecord = cache.sourceCache.getRelatedRecordSync( this.#identity, relationship ); if (relatedRecord) { return cache.lookup(relatedRecord) as Model; } else { return relatedRecord; } } /** * @deprecated */ replaceRelatedRecord( relationship: string, relatedRecord: Model | null, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#replaceRelatedRecord` is deprecated to avoid potential conflicts with field names. Call `$replaceRelatedRecord` instead.' ); this.$replaceRelatedRecord(relationship, relatedRecord, options); } $replaceRelatedRecord( relationship: string, relatedRecord: Model | null, options?: DefaultRequestOptions<RequestOptions> ): void { this.$cache.update( (t) => t.replaceRelatedRecord( this.#identity, relationship, relatedRecord ? relatedRecord.$identity : null ), options ); } /** * @deprecated */ getRelatedRecords(relationship: string): ReadonlyArray<Model> | undefined { deprecate( '`Model#getRelatedRecords` is deprecated to avoid potential conflicts with field names. Call `$getRelatedRecords` instead.' ); return this.$getRelatedRecords(relationship); } $getRelatedRecords(relationship: string): ReadonlyArray<Model> | undefined { const cache = this.$cache; const relatedRecords = cache.sourceCache.getRelatedRecordsSync( this.#identity, relationship ); if (relatedRecords) { return relatedRecords.map((r) => cache.lookup(r)); } else { return undefined; } } /** * @deprecated */ addToRelatedRecords( relationship: string, record: Model, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#addToRelatedRecords` is deprecated to avoid potential conflicts with field names. Call `$addToRelatedRecords` instead.' ); this.$addToRelatedRecords(relationship, record, options); } $addToRelatedRecords( relationship: string, record: Model, options?: DefaultRequestOptions<RequestOptions> ): void { this.$cache.update( (t) => t.addToRelatedRecords(this.#identity, relationship, record.$identity), options ); } /** * @deprecated */ removeFromRelatedRecords( relationship: string, record: Model, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#removeFromRelatedRecords` is deprecated to avoid potential conflicts with field names. Call `$removeFromRelatedRecords` instead.' ); this.$removeFromRelatedRecords(relationship, record, options); } $removeFromRelatedRecords( relationship: string, record: Model, options?: DefaultRequestOptions<RequestOptions> ): void { this.$cache.update( (t) => t.removeFromRelatedRecords( this.#identity, relationship, record.$identity ), options ); } /** * @deprecated */ replaceAttributes( properties: Dict<unknown>, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#replaceAttributes` is deprecated. Call `$update` instead (with the same arguments).' ); this.$update(properties, options); } /** * @deprecated */ update( properties: Dict<unknown>, options?: DefaultRequestOptions<RequestOptions> ): void { deprecate( '`Model#update` is deprecated to avoid potential conflicts with field names. Call `$update` instead.' ); this.$update(properties, options); } $update( properties: Dict<unknown>, options?: DefaultRequestOptions<RequestOptions> ): void { this.$cache.update( (t) => t.updateRecord({ ...properties, ...this.#identity }), options ); } /** * @deprecated */ remove(options?: DefaultRequestOptions<RequestOptions>): void { deprecate( '`Model#remove` is deprecated to avoid potential conflicts with field names. Call `$remove` instead.' ); this.$remove(options); } $remove(options?: DefaultRequestOptions<RequestOptions>): void { this.$cache.update((t) => t.removeRecord(this.#identity), options); } /** * @deprecated */ disconnect(): void { deprecate( '`Model#disconnect` is deprecated to avoid potential conflicts with field names. Call `$disconnect` instead.' ); this.$disconnect(); } $disconnect(): void { this._cache = undefined; this._isDisconnected = true; } /** * @deprecated */ destroy(): void { deprecate( '`Model#destroy` is deprecated to avoid potential conflicts with field names. Call `$destroy` instead.' ); this.$destroy(); } $destroy(): void { destroy(this); } /** * @deprecated */ notifyPropertyChange(key: string) { deprecate( '`Model#notifyPropertyChange` is deprecated to avoid potential conflicts with field names. Call `$notifyPropertyChange` instead.' ); this.$notifyPropertyChange(key); } $notifyPropertyChange(key: string) { notifyPropertyChange(this, key); } get $cache(): Cache { if (this._cache === undefined) { throw new Assertion('Record has been disconnected from its cache.'); } return this._cache; } static get definition(): ModelDefinition { return getModelDefinition(this.prototype); } static get keys(): Dict<KeyDefinition> { return getModelDefinition(this.prototype).keys ?? {}; } static get attributes(): Dict<AttributeDefinition> { return getModelDefinition(this.prototype).attributes ?? {}; } static get relationships(): Dict<RelationshipDefinition> { return getModelDefinition(this.prototype).relationships ?? {}; } static create(injections: ModelSettings) { const { identity, cache, ...otherInjections } = injections; const record = new this({ identity, cache }); return Object.assign(record, otherInjections); } }
the_stack
import { mount, shallowMount, Wrapper } from '@vue/test-utils'; import Vue from 'vue'; import Sortable, { GroupOptions, PutResult, SortableEvent, SortableOptions, } from 'sortablejs'; import QueryBuilder from '@/QueryBuilder.vue'; import QueryBuilderGroup from '@/QueryBuilderGroup.vue'; import QueryBuilderChild from '@/QueryBuilderChild.vue'; import { RuleSet, QueryBuilderConfig, Rule, GroupCtrlSlotProps, } from '@/types'; import Component from '../components/Component.vue'; interface QueryBuilderGroupInterface extends Vue { depth: number, maxDepthExeeded: boolean, dragOptions: SortableOptions, groupControlSlotProps: GroupCtrlSlotProps, } interface GroupOptionsInterface extends GroupOptions { put: ((to: Sortable, from: Sortable, dragEl: HTMLElement, event: SortableEvent) => PutResult) } interface DragOptionsInstance extends SortableOptions { group: GroupOptionsInterface, } describe('Testing max-depth behaviour', () => { const value: RuleSet = { operatorIdentifier: 'OR', children: [{ operatorIdentifier: 'AND', children: [{ identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, { operatorIdentifier: 'AND', children: [{ identifier: 'txt', value: 'D', }, { identifier: 'txt', value: 'E', }, { operatorIdentifier: 'AND', children: [{ identifier: 'txt', value: 'F', }, { operatorIdentifier: 'AND', children: [{ identifier: 'txt', value: 'G', }], }, { identifier: 'txt', value: 'H', }], }], }], }, { operatorIdentifier: 'AND', children: [{ identifier: 'txt', value: 'X', }, { operatorIdentifier: 'AND', children: [{ identifier: 'txt', value: 'T', }], }, { identifier: 'txt', value: 'Y', }, { identifier: 'txt', value: 'Z', }], }], }; const config: QueryBuilderConfig = { operators: [ { name: 'AND', identifier: 'AND', }, { name: 'OR', identifier: 'OR', }, ], rules: [ { identifier: 'txt', name: 'Text Selection', component: Component, initialValue: '', }, { identifier: 'num', name: 'Number Selection', component: Component, initialValue: 10, }, ], dragging: { animation: 300, disabled: false, ghostClass: 'ghost', }, maxDepth: 4, }; it('verifies not groups are added upon max-depth', () => { const createApp = () => mount(QueryBuilder, { propsData: { value: { ...value }, config: { ...config }, }, }); // Test non-leave group let app = createApp(); let group = app.findAllComponents(QueryBuilderGroup) .wrappers .filter(g => g.vm.$props.depth === 3) .shift() as Wrapper<QueryBuilderGroupInterface, Element>; // Assert button is present let button = group.find('.query-builder-group__group-adding-button'); expect(button.exists()).toBeTruthy(); button.trigger('click'); let evQueryUpdate = app.emitted('input'); expect(evQueryUpdate).toHaveLength(1); // Test "leaf" group app = createApp(); group = app.findAllComponents(QueryBuilderGroup) .wrappers .filter(g => g.vm.$props.depth === 4) .shift() as Wrapper<QueryBuilderGroupInterface, Element>; // Assert button is absent button = group.find('.query-builder-group__group-adding-button'); expect(button.exists()).toBeFalsy(); evQueryUpdate = app.emitted('input'); expect(evQueryUpdate).toBeUndefined(); }); it('verifies the behaviour of GroupCtrlSlotProps slot', () => { const createApp = () => mount(QueryBuilder, { propsData: { value: { ...value }, config: { ...config }, }, scopedSlots: { groupControl: ` <div slot-scope="props" class="slot-wrapper" > SLOT <select> <option v-for="rule in props.rules" :key="rule.identifier" :value="rule.identifier" v-text="rule.name" /> </select> <button @click="props.addRule('txt')" class="slot-new-rule" > Add Rule </button> <button v-if="! props.maxDepthExeeded" @click="props.newGroup" class="slot-new-group" > Add Group </button> </div> `, }, }); let app = createApp(); let group = app.findAllComponents(QueryBuilderGroup) .wrappers .filter(g => g.vm.$props.depth === 3) .shift() as Wrapper<QueryBuilderGroupInterface, Element>; expect(group.vm.groupControlSlotProps.maxDepthExeeded).toBeFalsy(); // Assert button is present let button = group.find('.slot-new-group'); expect(button.exists()).toBeTruthy(); button.trigger('click'); let evQueryUpdate = app.emitted('input'); expect(evQueryUpdate).toHaveLength(1); // Test leaf group app = createApp(); group = app.findAllComponents(QueryBuilderGroup) .wrappers .filter(g => g.vm.$props.depth === 4) .shift() as Wrapper<QueryBuilderGroupInterface, Element>; expect(group.vm.groupControlSlotProps.maxDepthExeeded).toBeTruthy(); // Assert button is absent button = group.find('.slot-new-group'); expect(button.exists()).toBeFalsy(); evQueryUpdate = app.emitted('input'); expect(evQueryUpdate).toBeUndefined(); }); it('prunes existing branches which are beyond the max-depth setting', async () => { const app = mount(QueryBuilder, { propsData: { value: { ...value }, config: { ...config }, }, }); const wrapper = app.findComponent(QueryBuilder); // Before, ensure nothing has been changed expect(wrapper.vm.$props.value).toHaveProperty('children.0.children.3.children.2.children.1.children.0.value', 'G'); expect(app.emitted('input')).toBeUndefined(); // Reduce max depth await app.setProps({ value: { ...value }, config: { ...config, maxDepth: 3 }, }); expect(app.emitted('input')).toHaveLength(1); expect((app.emitted('input') as any[])[0]).not.toHaveProperty('0.children.0.children.3.children.2.children.1.children.0.value', 'G'); expect((app.emitted('input') as any[])[0][0].children[0].children[3].children[2].children).toHaveLength(2); expect((app.emitted('input') as any[])[0]).toHaveProperty('0.children.0.children.3.children.2.children', [{ identifier: 'txt', value: 'F' }, { identifier: 'txt', value: 'H' }]); // Don't allow any group children await app.setProps({ value: { ...value }, config: { ...config, maxDepth: 0 }, }); expect((app.emitted('input') as any[]).pop()[0].children).toHaveLength(0); }); it('asserts no additional group can be created, beyond the mad-depth setting', () => { const app = mount(QueryBuilder, { propsData: { value: { ...value }, config: { ...config }, }, }); const groups = app.findAllComponents(QueryBuilderGroup).wrappers; const group1 = ( groups.filter(g => g.vm.$props.depth === 1) .shift() ) as Wrapper<QueryBuilderGroupInterface, Element>; expect((group1.vm as QueryBuilderGroupInterface).maxDepthExeeded).toBeFalsy(); expect(group1.find('.query-builder-group__group-adding-button').exists()).toBeTruthy(); const group4 = ( groups.filter(g => g.vm.$props.depth === 4) .shift() ) as Wrapper<QueryBuilderGroupInterface, Element>; expect((group4.vm as QueryBuilderGroupInterface).maxDepthExeeded).toBeTruthy(); expect(group4.find('.query-builder-group__group-adding-button').exists()).toBeFalsy(); }); it('checks and rejects movements, violating the max depth policy', () => { const buildDragEl = (r: Rule | RuleSet, c: QueryBuilderConfig): HTMLElement => { const rChild = shallowMount(QueryBuilderChild, { propsData: { query: { ...r }, config: { ...c }, }, }); const rEl = { __vue__: rChild.vm, } as unknown; return rEl as HTMLElement; }; const buildDragOptions = (ws: Array<Wrapper<Vue, Element>>): DragOptionsInstance => { const w = ws.shift() as Wrapper<Vue, Element>; const qbgi = w.vm as QueryBuilderGroupInterface; return (qbgi.dragOptions as DragOptionsInstance); }; const app = mount(QueryBuilder, { propsData: { value: { ...value }, config: { ...config }, }, }); const groups = app.findAllComponents(QueryBuilderGroup).wrappers; const s = (null as never) as Sortable; const se = (null as never) as SortableEvent; // Moving rule is always fine const movingRule = (value as any) .children[0].children[3].children[2].children[1].children[0] as Rule | RuleSet; const dragOptions1 = buildDragOptions(groups.filter(g => g.vm.$props.depth === 1)); expect(dragOptions1.group.put(s, s, buildDragEl(movingRule, config), se)).toBeTruthy(); const dragOptions2 = buildDragOptions(groups.filter(g => g.vm.$props.depth === 4)); expect(dragOptions2.group.put(s, s, buildDragEl(movingRule, config), se)).toBeTruthy(); // Moving ruleset needs extra check const movingRuleSet = (value as any).children[1] as Rule | RuleSet; expect(dragOptions1.group.put(s, s, buildDragEl(movingRuleSet, config), se)).toBeTruthy(); expect(dragOptions2.group.put(s, s, buildDragEl(movingRuleSet, config), se)).toBeFalsy(); }); it('checks and verifies GroupCtrlSlot\'s props behaviour', async () => { const newRuleSet = (): RuleSet => ({ operatorIdentifier: 'AND', children: [], }); const getMergeTrap = jest.fn(); const app = shallowMount(QueryBuilderGroup, { propsData: { config: { ...config }, query: newRuleSet(), depth: 4, }, provide: { getMergeTrap, }, }) as Wrapper<QueryBuilderGroupInterface>; const slotPropsLeafGroup = app.vm.groupControlSlotProps; expect(slotPropsLeafGroup.maxDepthExeeded).toBeTruthy(); slotPropsLeafGroup.newGroup(); expect(app.emitted('query-update')).toBeUndefined(); // Now try adding another by stepping down 1 depth app.setProps({ config: { ...config }, query: newRuleSet(), depth: 3, }); await app.vm.$nextTick(); const slotPropsNonLeafGroup = app.vm.groupControlSlotProps; expect(slotPropsNonLeafGroup.maxDepthExeeded).toBeFalsy(); slotPropsNonLeafGroup.newGroup(); expect(app.emitted('query-update')).toHaveLength(1); expect(getMergeTrap).not.toBeCalled(); }); });
the_stack
import { expect } from 'chai' import { Quaternion, Vector3 } from 'decentraland-ecs/src' const results = { staticAngle01: '90.00', staticAngle02: '14.85', staticAngle03: '4.99997', staticAngle04: '180', staticEuler01: '(0.0, 0.0, 0.0, 1.0)', staticEuler02: '(0.5, -0.5, 0.5, 0.5)', staticEuler03: '(0.0, 0.9, -0.4, 0.0)', staticEuler04: '(0.8, 0.0, 0.6, 0.0)', staticEuler05: '(-0.7, 0.2, -0.2, -0.6)', staticFromToRotation01: '(0.0, 180.0, 0.0)', staticFromToRotation02: '(0.0, 93.9, 0.0)', staticFromToRotation03: '(0.0, 0.0, 44.5)', staticFromToRotation04: '(45.0, 360.0, 360.0)', staticFromToRotation05: '(335.2, 276.2, 152.5)', staticFromToRotation06: '(39.1, 335.6, 352.5)', staticFromToRotation07: '(12.8, 45.1, 351.9)', staticFromToRotation08: '(35.3, 345.0, 315.0)', staticRotateTowards01: '(0.1, 0.1, 0.1, 1.0)', staticRotateTowards02: '(0.0, 0.1, 0.0, 1.0)', staticRotateTowards03: '(0.0, 0.1, -0.1, -1.0)', staticRotateTowards04: '(0.0, 0.0, 0.0, 1.0)', staticLookRotation01: '(-0.3, 0.4, 0.1, 0.9)', staticLookRotation02: '(0.0, 0.0, 0.0, 1.0)', staticLookRotation03: '(0.0, 0.7, 0.0, 0.7)', staticLookRotation04: '(0.0, 0.9, 0.4, 0.0)', staticSlerp01: '(0.5, 0.2, 0.2, 0.8)', staticSlerp02: '(0.0, 0.1, 0.8, 0.6)', staticSlerp03: '(-0.1, 0.0, -0.1, 1.0)', staticSlerp04: '(0.0, 0.3, 0.0, 0.9)', eulerAngles01: '(10.0, 10.0, 10.0)', eulerAngles02: '(0.0, 90.0, 0.0)', eulerAngles03: '(80.0, 190.0, 220.0)', eulerAngles04: '(360.0, 10.0, 0.0)', normalized01: '(0.1, 0.1, 0.1, 1.0)', normalized02: '(0.0, 0.7, 0.0, 0.7)', normalized03: '(-0.7, 0.2, -0.2, -0.6)', normalized04: '(0.0, -0.1, 0.0, -1.0)', setFromToRotation01: '(0.0, 0.0, -0.7, 0.7)', setFromToRotation02: '(0.7, 0.0, 0.0, 0.7)', setFromToRotation03: '(0.5, -0.3, -0.1, 0.8)', setFromToRotation04: '(-0.1, -0.5, -0.3, 0.8)', setFromToRotation05: '(0.0, 1.0, 0.0, 0.0)', setFromToRotation06: '(0.0, 0.0, 0.0, 1.0)', setFromToRotation07: '(-1.0, 0.0, 0.0, 0.0)', setFromToRotation08: '(0.0, 0.0, 0.0, 1.0)' } const normalize = (v: string) => (v === '-0.0' ? '0.0' : v) function quaternionToString(quat: Quaternion) { const x = normalize(quat.x.toFixed(1).substr(0, 6)) const y = normalize(quat.y.toFixed(1).substr(0, 6)) const z = normalize(quat.z.toFixed(1).substr(0, 6)) const w = normalize(quat.w.toFixed(1).substr(0, 6)) return `(${x}, ${y}, ${z}, ${w})` } function vector3ToString(vec: Vector3) { const x = normalize(vec.x.toFixed(1).substr(0, 6)) const y = normalize(vec.y.toFixed(1).substr(0, 6)) const z = normalize(vec.z.toFixed(1).substr(0, 6)) return `(${x}, ${y}, ${z})` } describe('ECS Quaternion tests', () => { it('Quaternion.Angle', () => { expect( Quaternion.Angle(Quaternion.Euler(0, 0, 0), Quaternion.Euler(90, 90, 90)) .toString() .substr(0, 5) ).to.eq(results.staticAngle01.substr(0, 5), 'staticAngle01') expect( Quaternion.Angle(Quaternion.Euler(10, 0, 10), Quaternion.Euler(360, 0, -1)) .toString() .substr(0, 5) ).to.eq(results.staticAngle02.substr(0, 5), 'staticAngle02') expect( Quaternion.Angle(Quaternion.Euler(0, 5, 0), Quaternion.Euler(0, 0, 0)) .toString() .substr(0, 5) ).to.eq(results.staticAngle03.substr(0, 5), 'staticAngle03') expect( Quaternion.Angle(Quaternion.Euler(360, -360, 0), Quaternion.Euler(180, 90, 0)) .toString() .substr(0, 5) ).to.eq(results.staticAngle04.substr(0, 5), 'staticAngle04') }) it('Quaternion.Euler', () => { expect(quaternionToString(Quaternion.Euler(0, 0, 0))).to.eq(results.staticEuler01, 'staticEuler01') expect(quaternionToString(Quaternion.Euler(90, 0, 90))).to.eq(results.staticEuler02, 'staticEuler02') expect(quaternionToString(Quaternion.Euler(45, 180, -1))).to.eq(results.staticEuler03, 'staticEuler03') expect(quaternionToString(Quaternion.Euler(360, 110, -180))).to.eq(results.staticEuler04, 'staticEuler04') expect(quaternionToString(Quaternion.Euler(100, 10, 400))).to.eq(results.staticEuler05, 'staticEuler05') }) it('Quaternion.RotateTowards', () => { expect( quaternionToString(Quaternion.RotateTowards(Quaternion.Euler(10, 10, 10), Quaternion.Euler(100, 100, 100), 0.1)) ).to.eq(results.staticRotateTowards01, 'staticRotateTowards01') expect( quaternionToString(Quaternion.RotateTowards(Quaternion.Euler(0, 10, -0), Quaternion.Euler(0, 9, 45), 0.1)) ).to.eq(results.staticRotateTowards02, 'staticRotateTowards02') expect( quaternionToString(Quaternion.RotateTowards(Quaternion.Euler(360, -10, 10), Quaternion.Euler(0, 100, 0), 0.1)) ).to.eq(results.staticRotateTowards03, 'staticRotateTowards03') expect( quaternionToString(Quaternion.RotateTowards(Quaternion.Euler(0, 0, 0), Quaternion.Euler(0, 0, 0), 0.1)) ).to.eq(results.staticRotateTowards04, 'staticRotateTowards04') }) it('Quaternion.LookRotation', () => { expect(quaternionToString(Quaternion.LookRotation(new Vector3(1, 1, 1), Vector3.Up()))).to.eq( results.staticLookRotation01, 'staticLookRotation01' ) expect(quaternionToString(Quaternion.LookRotation(new Vector3(-10, -0, 110), Vector3.Up()))).to.eq( results.staticLookRotation02, 'staticLookRotation02' ) expect(quaternionToString(Quaternion.LookRotation(new Vector3(1230, 10, 0), Vector3.Up()))).to.eq( results.staticLookRotation03, 'staticLookRotation03' ) expect(quaternionToString(Quaternion.LookRotation(new Vector3(0, 123, -123), Vector3.Up()))).to.eq( results.staticLookRotation04, 'staticLookRotation04' ) }) // These tests check against euler angles since we get a different quaternion result in Unity, but represent the same euler angles rotation. it('Quaternion.FromToRotation', () => { expect(vector3ToString(Quaternion.FromToRotation(new Vector3(0, 0, 0), new Vector3(100, 100, 100)).eulerAngles)).to.eq( results.staticFromToRotation01, 'staticFromToRotation01' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(-10, -0, 110), new Vector3(4452, 0, 100)).eulerAngles)).to.eq( results.staticFromToRotation02, 'staticFromToRotation02' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(1230, 10, 0), new Vector3(100, 100, 0)).eulerAngles)).to.eq( results.staticFromToRotation03, 'staticFromToRotation03' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(0, 123, -123), new Vector3(100, 213123, 100)).eulerAngles)).to.eq( results.staticFromToRotation04, 'staticFromToRotation04' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(-10, -10, -10), new Vector3(360, -10, 360)).eulerAngles)).to.eq( results.staticFromToRotation05, 'staticFromToRotation05' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(12, -0, -400), new Vector3(200, 360, -400)).eulerAngles)).to.eq( results.staticFromToRotation06, 'staticFromToRotation06' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(25, 45, 180), new Vector3(127, 0, 90)).eulerAngles)).to.eq( results.staticFromToRotation07, 'staticFromToRotation07' ) expect(vector3ToString(Quaternion.FromToRotation(new Vector3(0, 1, 0), new Vector3(1, 1, 1)).eulerAngles)).to.eq( results.staticFromToRotation08, 'staticFromToRotation08' ) }) it('quaternion.eulerAngles', () => { expect(vector3ToString(Quaternion.Euler(10, 10, 10).eulerAngles)).to.eq(results.eulerAngles01, 'eulerAngles01') expect(vector3ToString(Quaternion.Euler(0, 90, 0).eulerAngles)).to.eq(results.eulerAngles02, 'eulerAngles02') expect(vector3ToString(Quaternion.Euler(100, 10, 400).eulerAngles)).to.eq(results.eulerAngles03, 'eulerAngles03') expect(vector3ToString(Quaternion.Euler(360, 10, 0).eulerAngles)).to.eq(results.eulerAngles04, 'eulerAngles04') }) it('quaternion.normalized', () => { expect(quaternionToString(Quaternion.Euler(10, 10, 10).normalized)).to.eq(results.normalized01, 'normalized01') expect(quaternionToString(Quaternion.Euler(0, 90, 0).normalized)).to.eq(results.normalized02, 'normalized02') expect(quaternionToString(Quaternion.Euler(100, 10, 400).normalized)).to.eq(results.normalized03, 'normalized03') expect(quaternionToString(Quaternion.Euler(360, 10, 0).normalized)).to.eq(results.normalized04, 'normalized04') }) it('quaternion.setFromToRotation', () => { let upVector = Vector3.Up() let quat = Quaternion.Identity quat.setFromToRotation(Vector3.Up(), Vector3.Right(), upVector) expect(quaternionToString(quat)).to.eq(results.setFromToRotation01, 'setFromToRotation01') upVector = Vector3.Up() quat = Quaternion.Identity quat.setFromToRotation(Vector3.Up(), Vector3.Forward(), upVector) expect(quaternionToString(quat)).to.eq(results.setFromToRotation02, 'setFromToRotation02') upVector = new Vector3(50, 0, -39) quat = Quaternion.Identity quat.setFromToRotation(new Vector3(38, 56, 23), new Vector3(12, -5, 99), upVector) expect(quaternionToString(quat)).to.eq(results.setFromToRotation03, 'setFromToRotation03') upVector = new Vector3(-60, -80, -23) quat = Quaternion.Identity quat.setFromToRotation(new Vector3(-50, 0.5, 15), new Vector3(-66, 66, -91), upVector) expect(quaternionToString(quat)).to.eq(results.setFromToRotation04, 'setFromToRotation04') upVector = Vector3.Up() quat = Quaternion.Identity quat.setFromToRotation(new Vector3(-1, 0, 0), new Vector3(1, 0, 0), upVector) // Parallel opposite vectors case expect(quaternionToString(quat)).to.eq(results.setFromToRotation05, 'setFromToRotation05') upVector = Vector3.Up() quat = Quaternion.Identity quat.setFromToRotation(new Vector3(1, 0, 0), new Vector3(1, 0, 0), upVector) // same vectors case expect(quaternionToString(quat)).to.eq(results.setFromToRotation06, 'setFromToRotation06') upVector = Vector3.Left() quat = Quaternion.Identity quat.setFromToRotation(new Vector3(0, 1, 0), new Vector3(0, -1, 0), upVector) expect(quaternionToString(quat)).to.eq(results.setFromToRotation07, 'setFromToRotation07') upVector = Vector3.Left() quat = Quaternion.Identity quat.setFromToRotation(new Vector3(0, -1, 0), new Vector3(0, -1, 0), upVector) expect(quaternionToString(quat)).to.eq(results.setFromToRotation08, 'setFromToRotation08') }) it('Quaternion.Slerp', () => { expect(quaternionToString(Quaternion.Slerp(Quaternion.Euler(10, 10, 10), Quaternion.Euler(45, 45, 45), 1))).to.eq( results.staticSlerp01, 'staticSlerp01' ) expect( quaternionToString(Quaternion.Slerp(Quaternion.Euler(-10, -0, 110), Quaternion.Euler(4100, 100, 100), 0.00123)) ).to.eq(results.staticSlerp02, 'staticSlerp02') expect( quaternionToString(Quaternion.Slerp(Quaternion.Euler(0, 123, -123), Quaternion.Euler(360, -10, 360), 0.9)) ).to.eq(results.staticSlerp03, 'staticSlerp03') expect(quaternionToString(Quaternion.Slerp(Quaternion.Euler(1, 1, 0), Quaternion.Euler(12, 12341, 1), 0.4))).to.eq( results.staticSlerp04, 'staticSlerp04' ) }) })
the_stack
import "reflect-metadata"; import "mocha"; import { expect } from "chai"; import { Container } from "inversify"; import { TYPES } from "../types"; import defaultModule from "../di.config"; import { IViewer } from "../views/viewer"; import { Command, HiddenCommand, SystemCommand, CommandExecutionContext, CommandResult, MergeableCommand, PopupCommand } from './command'; import { ICommandStack } from "./command-stack"; let operations: string[] = []; class TestCommand extends Command { constructor(public name: string) { super(); } execute(context: CommandExecutionContext): CommandResult { operations.push('exec ' + this.name); return context.root; } undo(context: CommandExecutionContext): CommandResult { operations.push('undo ' + this.name); return context.root; } redo(context: CommandExecutionContext): CommandResult { operations.push('redo ' + this.name); return context.root; } } class TestSystemCommand extends SystemCommand { constructor(public name: string) { super(); } execute(context: CommandExecutionContext): CommandResult { operations.push('exec ' + this.name); return context.root; } undo(context: CommandExecutionContext): CommandResult { operations.push('undo ' + this.name); return context.root; } redo(context: CommandExecutionContext): CommandResult { operations.push('redo ' + this.name); return context.root; } } class TestMergeableCommand extends MergeableCommand { constructor(public name: string) { super(); } execute(context: CommandExecutionContext): CommandResult { operations.push('exec ' + this.name); return context.root; } undo(context: CommandExecutionContext): CommandResult { operations.push('undo ' + this.name); return context.root; } redo(context: CommandExecutionContext): CommandResult { operations.push('redo ' + this.name); return context.root; } merge(other: TestCommand, context: CommandExecutionContext) { if (other instanceof TestMergeableCommand) { this.name = this.name + '/' + other.name; return true; } return false; } } class TestHiddenCommand extends HiddenCommand { constructor(public name: string) { super(); } execute(context: CommandExecutionContext) { operations.push('exec ' + this.name); return context.root; } } class TestPopupCommand extends PopupCommand { constructor(public name: string ) { super(); } execute(context: CommandExecutionContext): CommandResult { operations.push('exec ' + this.name); return context.root; } undo(context: CommandExecutionContext): CommandResult { operations.push('undo ' + this.name); return context.root; } redo(context: CommandExecutionContext): CommandResult { operations.push('redo ' + this.name); return context.root; } } describe('CommandStack', () => { let viewerUpdates: number = 0; let hiddenViewerUpdates: number = 0; let popupUpdates: number = 0; const mockViewer: IViewer = { update() { ++viewerUpdates; }, updateHidden() { ++hiddenViewerUpdates; }, updatePopup() { ++popupUpdates; } }; const container = new Container(); container.load(defaultModule); container.rebind(TYPES.IViewer).toConstantValue(mockViewer); const commandStack = container.get<ICommandStack>(TYPES.ICommandStack); const foo = new TestCommand('Foo'); const bar = new TestCommand('Bar'); const system = new TestSystemCommand('System'); const mergable = new TestMergeableCommand('Mergable'); const hidden = new TestHiddenCommand('Hidden'); const popup = new TestPopupCommand('Popup'); it('calls viewer correctly', async () => { await commandStack.executeAll([foo, bar, system]); expect(viewerUpdates).to.be.equal(1); await commandStack.execute(foo); expect(viewerUpdates).to.be.equal(2); await commandStack.execute(bar); expect(viewerUpdates).to.be.equal(3); await commandStack.execute(system); expect(viewerUpdates).to.be.equal(4); await commandStack.execute(popup); expect(popupUpdates).to.be.equal(1); expect(0).to.be.equal(hiddenViewerUpdates); }); it('handles plain undo/redo', async () => { operations = []; viewerUpdates = 0; popupUpdates = 0; await commandStack.executeAll([foo, bar, popup]); await commandStack.undo(); await commandStack.redo(); await commandStack.undo(); await commandStack.undo(); await commandStack.redo(); expect(operations).to.be.eql( ['exec Foo', 'exec Bar', 'exec Popup', 'undo Bar', 'redo Bar', 'undo Bar', 'undo Foo', 'redo Foo']); expect(6).to.be.equal(viewerUpdates); expect(0).to.be.equal(hiddenViewerUpdates); }); it('handles system command at the end', async () => { operations = []; viewerUpdates = 0; await commandStack.executeAll([foo, bar, system]); expect(1).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'exec System']).to.be.eql(operations); await commandStack.undo(); expect(2).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'exec System', 'undo System', 'undo Bar']).to.be.eql(operations); await commandStack.execute(system); expect(3).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'exec System', 'undo System', 'undo Bar', 'exec System']).to.be.eql(operations); await commandStack.redo(); expect(4).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'exec System', 'undo System', 'undo Bar', 'exec System', 'undo System', 'redo Bar', 'redo System']).to.be.eql(operations); expect(0).to.be.equal(hiddenViewerUpdates); }); it('handles system command in the middle', async () => { operations = []; viewerUpdates = 0; await commandStack.executeAll([foo, bar]); expect(1).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar']).to.be.eql(operations); await commandStack.undo(); expect(2).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'undo Bar']).to.be.eql(operations); await commandStack.execute(system); expect(3).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'undo Bar', 'exec System']).to.be.eql(operations); await commandStack.undo(); expect(4).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'undo Bar', 'exec System', 'undo System', 'undo Foo']).to.be.eql(operations); await commandStack.executeAll([system, system]); expect(5).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'undo Bar', 'exec System', 'undo System', 'undo Foo', 'exec System', 'exec System']).to.be.eql(operations); await commandStack.redo(); expect(6).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'undo Bar', 'exec System', 'undo System', 'undo Foo', 'exec System', 'exec System', 'undo System', 'undo System', 'redo Foo']).to.be.eql(operations); await commandStack.redo(); expect(7).to.be.equal(viewerUpdates); expect(['exec Foo', 'exec Bar', 'undo Bar', 'exec System', 'undo System', 'undo Foo', 'exec System', 'exec System', 'undo System', 'undo System', 'redo Foo', 'redo Bar']).to.be.eql(operations); expect(0).to.be.equal(hiddenViewerUpdates); }); it('handles merge command', async () => { operations = []; viewerUpdates = 0; await commandStack.executeAll([mergable, mergable]); expect(1).to.be.equal(viewerUpdates); expect(['exec Mergable', 'exec Mergable']).to.be.eql(operations); await commandStack.undo(); expect(2).to.be.equal(viewerUpdates); expect(['exec Mergable', 'exec Mergable', 'undo Mergable/Mergable']).to.be.eql(operations); await commandStack.redo(); expect(3).to.be.equal(viewerUpdates); expect(['exec Mergable', 'exec Mergable', 'undo Mergable/Mergable', 'redo Mergable/Mergable']).to.be.eql(operations); await commandStack.execute(foo); expect(4).to.be.equal(viewerUpdates); expect(['exec Mergable', 'exec Mergable', 'undo Mergable/Mergable', 'redo Mergable/Mergable', 'exec Foo']).to.be.eql(operations); expect(0).to.be.equal(hiddenViewerUpdates); }); it('handles hidden command', async () => { operations = []; viewerUpdates = 0; hiddenViewerUpdates = 0; await commandStack.executeAll([foo, bar]); expect(1).to.be.equal(viewerUpdates); expect(0).to.be.equal(hiddenViewerUpdates); expect(['exec Foo', 'exec Bar']).to.be.eql(operations); await commandStack.execute(hidden); expect(1).to.be.equal(viewerUpdates); expect(1).to.be.equal(hiddenViewerUpdates); expect(['exec Foo', 'exec Bar', 'exec Hidden']).to.be.eql(operations); await commandStack.undo(); expect(2).to.be.equal(viewerUpdates); expect(1).to.be.equal(hiddenViewerUpdates); expect(['exec Foo', 'exec Bar', 'exec Hidden', 'undo Bar']).to.be.eql(operations); await commandStack.execute(hidden); expect(2).to.be.equal(viewerUpdates); expect(2).to.be.equal(hiddenViewerUpdates); expect(['exec Foo', 'exec Bar', 'exec Hidden', 'undo Bar', 'exec Hidden']).to.be.eql(operations); await commandStack.redo(); expect(3).to.be.equal(viewerUpdates); expect(2).to.be.equal(hiddenViewerUpdates); expect(['exec Foo', 'exec Bar', 'exec Hidden', 'undo Bar', 'exec Hidden', 'redo Bar']).to.be.eql(operations); }); });
the_stack
import * as core from '@actions/core' import * as gha_exec from '@actions/exec' import { spawnSync } from 'child_process' import type { SpawnSyncOptions } from 'child_process' import * as path from 'path' import * as fs from 'fs' import semver, { Range } from 'semver' import type { SemVer } from 'semver' async function mdls(path: string): Promise<SemVer | undefined> { const v = await exec('mdls', ['-raw', '-name', 'kMDItemVersion', path]) if (core.getInput('verbosity') == 'verbose') { // in verbose mode all commands and outputs are printed // and mdls in `raw` mode does not terminate its lines process.stdout.write('\n') } return semver.coerce(v) ?? undefined } async function xcodes(): Promise<[string, SemVer][]> { const paths = ( await exec('mdfind', ['kMDItemCFBundleIdentifier = com.apple.dt.Xcode']) ).split('\n') const rv: [string, SemVer][] = [] for (const path of paths) { if (!path.trim()) continue const v = await mdls(path) if (v) { rv.push([path, v]) } } return rv } export function spawn( arg0: string, args: string[], options: SpawnSyncOptions = { stdio: 'inherit' } ): void { const { error, signal, status } = spawnSync(arg0, args, options) if (error) throw error if (signal) throw new Error(`\`${arg0}\` terminated with signal (${signal})`) if (status != 0) throw new Error(`\`${arg0}\` aborted (${status})`) } export async function xcselect(xcode?: Range, swift?: Range): Promise<SemVer> { if (swift) { return selectSwift(swift) } else if (xcode) { return selectXcode(xcode) } const gotDotSwiftVersion = dotSwiftVersion() if (gotDotSwiftVersion) { core.info(`» \`.swift-version\` » ~> ${gotDotSwiftVersion}`) return selectSwift(gotDotSwiftVersion) } else { // figure out the GHA image default Xcode’s version const devdir = await exec('xcode-select', ['--print-path']) const xcodePath = path.dirname(path.dirname(devdir)) const version = await mdls(xcodePath) if (version) { return version } else { // shouldn’t happen, but this action needs to know the Xcode version // or we cannot function, this way we are #continuously-resilient return selectXcode() } } async function selectXcode(range?: Range): Promise<SemVer> { const rv = (await xcodes()) .filter(([, v]) => (range ? semver.satisfies(v, range) : true)) .sort((a, b) => semver.compare(a[1], b[1])) .pop() if (!rv) throw new Error(`No Xcode ~> ${range}`) spawn('sudo', ['xcode-select', '--switch', rv[0]]) return rv[1] } async function selectSwift(range: Range): Promise<SemVer> { const rv1 = await xcodes() const rv2 = await Promise.all(rv1.map(swiftVersion)) const rv3 = rv2 .filter(([, , sv]) => semver.satisfies(sv, range)) .sort((a, b) => semver.compare(a[1], b[1])) .pop() if (!rv3) throw new Error(`No Xcode with Swift ~> ${range}`) core.info(`» Selected Swift ${rv3[2]}`) spawn('sudo', ['xcode-select', '--switch', rv3[0]]) return rv3[1] async function swiftVersion([DEVELOPER_DIR, xcodeVersion]: [ string, SemVer ]): Promise<[string, SemVer, SemVer]> { // This command emits 'swift-driver version: ...' to stderr. const stdout = await exec( 'swift', ['--version'], { DEVELOPER_DIR }, false ) const matches = stdout.match(/Swift version (.+?)\s/m) if (!matches || !matches[1]) throw new Error( `failed to extract Swift version from Xcode ${xcodeVersion}` ) const version = semver.coerce(matches[1]) if (!version) throw new Error( `failed to parse Swift version from Xcode ${xcodeVersion}` ) return [DEVELOPER_DIR, xcodeVersion, version] } } function dotSwiftVersion(): Range | undefined { if (!fs.existsSync('.swift-version')) return undefined const version = fs.readFileSync('.swift-version').toString().trim() try { // A .swift-version of '5.0' indicates a SemVer Range of '>=5.0.0 <5.1.0' return new Range('~' + version) } catch (error) { core.warning( `Failed to parse Swift version from .swift-version: ${error}` ) } } } interface Devices { devices: { [key: string]: [ { udid: string } ] } } type DeviceType = 'watchOS' | 'tvOS' | 'iOS' type Destination = { [key: string]: string } interface Schemes { workspace?: { schemes: string[] } project?: { schemes: string[] } } export async function getSchemeFromPackage(): Promise<string> { const out = await exec('xcodebuild', ['-list', '-json']) const json = parseJSON<Schemes>(out) const schemes = (json?.workspace ?? json?.project)?.schemes if (!schemes || schemes.length == 0) throw new Error('Could not determine scheme') for (const scheme of schemes) { if (scheme.endsWith('-Package')) return scheme } return schemes[0] } function parseJSON<T>(input: string): T { try { input = input.trim() // works around xcodebuild sometimes outputting this string in CI conditions const xcodebuildSucks = 'build session not created after 15 seconds - still waiting' if (input.endsWith(xcodebuildSucks)) { input = input.slice(0, -xcodebuildSucks.length) } return JSON.parse(input) as T } catch (error) { core.startGroup('JSON') core.error(input) core.endGroup() throw error } } async function destinations(): Promise<Destination> { const out = await exec('xcrun', [ 'simctl', 'list', '--json', 'devices', 'available', ]) const devices = parseJSON<Devices>(out).devices const rv: { [key: string]: { v: SemVer; id: string } } = {} for (const opaqueIdentifier in devices) { const device = (devices[opaqueIdentifier] ?? [])[0] if (!device) continue const [type, v] = parse(opaqueIdentifier) if (v && (!rv[type] || semver.lt(rv[type].v, v))) { rv[type] = { v, id: device.udid } } } return { tvOS: rv.tvOS?.id, watchOS: rv.watchOS?.id, iOS: rv.iOS?.id, } function parse(key: string): [DeviceType, SemVer?] { const [type, ...vv] = (key.split('.').pop() ?? '').split('-') const v = semver.coerce(vv.join('.')) return [type as DeviceType, v ?? undefined] } } async function exec( command: string, args?: string[], env?: { [key: string]: string }, stdErrToWarning = true ): Promise<string> { let out = '' try { await gha_exec.exec(command, args, { listeners: { stdout: (data) => (out += data.toString()), stderr: (data) => { const message = `${command}: ${'\u001b[33m'}${data.toString()}` if (stdErrToWarning) { core.warning(message) } else { core.info(message) } }, }, silent: verbosity() != 'verbose', env, }) return out } catch (error) { // help debug efforts by showing what we ran if there was an error core.info(`» ${command} ${args ? args.join(' \\\n') : ''}`) throw error } } export function verbosity(): 'xcpretty' | 'quiet' | 'verbose' { const value = core.getInput('verbosity') switch (value) { case 'xcpretty': case 'quiet': case 'verbose': return value default: // backwards compatability if (core.getBooleanInput('quiet')) return 'quiet' core.warning(`invalid value for \`verbosity\` (${value})`) return 'xcpretty' } } export function getConfiguration(): string { const conf = core.getInput('configuration') switch (conf) { // both `.xcodeproj` and SwiftPM projects capitalize these // by default, and are case-sensitive. And for both if an // incorrect configuration is specified do not error, but // do not behave as expected instead. case 'debug': return 'Debug' case 'release': return 'Release' default: return conf } } export type Platform = 'watchOS' | 'iOS' | 'tvOS' | 'macOS' | 'mac-catalyst' export function getAction( xcodeVersion: SemVer, platform?: Platform ): string | undefined { const action = core.getInput('action') if ( platform == 'watchOS' && actionIsTestable(action) && semver.lt(xcodeVersion, '12.5.0') ) { core.notice('Setting `action=build` for Apple Watch / Xcode <12.5') return 'build' } return action ?? undefined } export function actionIsTestable(action?: string): boolean { return action == 'test' || action == 'build-for-testing' } export async function getDestination( xcodeVersion: SemVer, platform?: Platform ): Promise<string[]> { switch (platform) { case 'iOS': case 'tvOS': case 'watchOS': { const id = (await destinations())[platform] return ['-destination', `id=${id}`] } case 'macOS': return ['-destination', 'platform=macOS'] case 'mac-catalyst': return ['-destination', 'platform=macOS,variant=Mac Catalyst'] case undefined: if (semver.gte(xcodeVersion, '13.0.0')) { //FIXME should parse output from xcodebuild -showdestinations //NOTE `-json` doesn’t work // eg. the Package.swift could only allow iOS, assuming macOS is going to work OFTEN // but not ALWAYS return ['-destination', 'platform=macOS'] } else { return [] } default: throw new Error(`Invalid platform: ${platform}`) } } export function getIdentity( identity: string, platform?: Platform ): string | undefined { if (identity) { return `CODE_SIGN_IDENTITY="${identity}"` } if (platform == 'mac-catalyst') { // Disable code signing for Mac Catalyst unless overridden. core.notice('Disabling code signing for Mac Catalyst.') return 'CODE_SIGN_IDENTITY=-' } } // In order to avoid exposure to command line audit logging, we pass commands in // via stdin. We allow only one command at a time in an effort to avoid injection. function security(...args: string[]): void { for (const arg of args) { if (arg.includes('\n')) throw new Error('Invalid security argument') } const command = args.join(' ').concat('\n') spawn('/usr/bin/security', ['-i'], { input: command }) } export async function createKeychain( certificate: string, passphrase: string ): Promise<void> { // The user should have already stored these as encrypted secrets, but we'll be paranoid on their behalf. core.setSecret(certificate) core.setSecret(passphrase) // Avoid using a well-known password. const password = (await exec('/usr/bin/uuidgen')).trim() core.setSecret(password) // Avoid using well-known paths. const name = (await exec('/usr/bin/uuidgen')).trim() core.setSecret(name) // Unfortunately, a keychain must be stored on disk. We remove it in a post action that calls deleteKeychain. const keychainPath = `${process.env.RUNNER_TEMP}/${name}.keychain-db` core.saveState('keychainPath', keychainPath) const keychainSearchPath = ( await exec('/usr/bin/security', ['list-keychains', '-d', 'user']) ) .split('\n') .map((value) => value.trim()) core.saveState('keychainSearchPath', keychainSearchPath) core.info('Creating keychain') security('create-keychain', '-p', password, keychainPath) security('set-keychain-settings', '-lut', '21600', keychainPath) security('unlock-keychain', '-p', password, keychainPath) // Unfortunately, a certificate must be stored on disk in order to be imported. We remove it immediately after import. core.info('Importing certificate to keychain') const certificatePath = `${process.env.RUNNER_TEMP}/${name}.p12` fs.writeFileSync(certificatePath, certificate, { encoding: 'base64' }) try { security( 'import', certificatePath, '-P', passphrase, '-A', '-t', 'cert', '-f', 'pkcs12', '-x', '-k', keychainPath ) } finally { fs.unlinkSync(certificatePath) } core.info('Updating keychain search path') security( 'list-keychains', '-d', 'user', '-s', keychainPath, ...keychainSearchPath ) } export function deleteKeychain(): void { const state = core.getState('keychainSearchPath') if (state) { const keychainSearchPath: string[] = JSON.parse(state) core.info('Restoring keychain search path') try { security('list-keychains', '-d', 'user', '-s', ...keychainSearchPath) } catch (error) { core.error('Failed to restore keychain search path: ' + error) // Continue cleaning up. } } const keychainPath = core.getState('keychainPath') if (keychainPath) { core.info('Deleting keychain') try { security('delete-keychain', keychainPath) } catch (error) { core.error('Failed to delete keychain: ' + error) // Best we can do is deleting the keychain file. if (fs.existsSync(keychainPath)) { fs.unlinkSync(keychainPath) } } } }
the_stack
import ref = require("ref-napi"); interface Foo { x: number; } declare const typeLike: ref.NamedType | ref.Type; declare const numberPointer: ref.Pointer<number>; declare const numberPointerType: ref.Type<ref.Pointer<number>>; declare const fooPointer: ref.Pointer<Foo>; declare const buffer: Buffer; declare const string: string; declare const encoding: BufferEncoding; declare const number: number; declare const any: any; declare const int64Like: string | number; declare const jsObject: Object; // $ExpectType number ref.address(buffer); // $ExpectType string ref.hexAddress(buffer); // $ExpectType Value<any> ref.alloc(typeLike, 0); // $ExpectType Value<number> ref.alloc("int"); // $ExpectType Value<number> ref.alloc("int", 4); // $ExpectType Value<string> ref.allocCString(string); // $ExpectType Value<string> ref.allocCString(string, undefined); // $ExpectType Value<string> ref.allocCString(string, encoding); // $ExpectType Value<string | null> ref.allocCString(null); // $ExpectType Value<string | null> ref.allocCString(null, undefined); // $ExpectType Value<string | null> ref.allocCString(null, encoding); // $ExpectType Type<any> ref.coerceType(typeLike); // $ExpectType Type<number> ref.coerceType(ref.types.int); // $ExpectType Type<number> ref.coerceType("int"); // $ExpectType any ref.deref(buffer); // $ExpectType number ref.deref(numberPointer); // $ExpectType Type<unknown> ref.derefType(typeLike); // $ExpectType Type<number> ref.derefType(numberPointerType); // $ExpectType "LE" | "BE" ref.endianness; // $ExpectType any ref.get(buffer); // $ExpectType any ref.get(buffer, undefined); // $ExpectType any ref.get(buffer, undefined, undefined); // $ExpectType any ref.get(buffer, number); // $ExpectType any ref.get(buffer, number, undefined); // $ExpectType any ref.get(buffer, number, typeLike); // $ExpectType number ref.get(numberPointer); // $ExpectType number ref.get(numberPointer, undefined); // $ExpectType number ref.get(numberPointer, 0); // $ExpectType any ref.get(numberPointer, number); // $ExpectType number ref.get(buffer, number, ref.types.int); // $ExpectType Type<any> ref.getType(buffer); // $ExpectType Type<number> ref.getType(numberPointer); // $ExpectType boolean ref.isNull(buffer); // $ExpectType string ref.readCString(buffer); // $ExpectType string ref.readCString(buffer, undefined); // $ExpectType string ref.readCString(buffer, number); // $ExpectType string | number ref.readInt64BE(buffer); // $ExpectType string | number ref.readInt64BE(buffer, undefined); // $ExpectType string | number ref.readInt64BE(buffer, number); // $ExpectType string | number ref.readInt64LE(buffer); // $ExpectType string | number ref.readInt64LE(buffer, undefined); // $ExpectType string | number ref.readInt64LE(buffer, number); // $ExpectType Object ref.readObject(buffer); // $ExpectType Object ref.readObject(buffer, undefined); // $ExpectType Object ref.readObject(buffer, number); // $ExpectType Foo ref.readObject(fooPointer); // $ExpectType Foo ref.readObject(fooPointer, undefined); // $ExpectType Foo ref.readObject(fooPointer, 0); // $ExpectType Object ref.readObject(fooPointer, number); // $ExpectType Buffer ref.ref(buffer); // $ExpectType Pointer<Pointer<number>> ref.ref(numberPointer); // $ExpectType Type<Pointer<any>> ref.refType(typeLike); // $ExpectType Type<Pointer<number>> ref.refType(ref.types.int); // $ExpectType Buffer ref.reinterpret(buffer, number); // $ExpectType Buffer ref.reinterpret(buffer, number, undefined); // $ExpectType Buffer ref.reinterpret(buffer, number, number); // $ExpectType Buffer ref.reinterpretUntilZeros(buffer, number); // $ExpectType Buffer ref.reinterpretUntilZeros(buffer, number, undefined); // $ExpectType Buffer ref.reinterpretUntilZeros(buffer, number, number); // $ExpectType void ref.set(buffer, number, any); // $ExpectType void ref.set(buffer, number, any, undefined); // $ExpectType void ref.set(buffer, number, any, typeLike); // $ExpectType void ref.writeCString(buffer, number, string); // $ExpectType void ref.writeCString(buffer, number, string, undefined); // $ExpectType void ref.writeCString(buffer, number, string, encoding); // $ExpectType void ref.writeInt64BE(buffer, number, int64Like); // $ExpectType void ref.writeInt64LE(buffer, number, int64Like); // $ExpectType void ref.writeObject(buffer, number, jsObject); // $ExpectType void ref.writePointer(buffer, number, buffer); // $ExpectType void ref.writeUInt64BE(buffer, number, int64Like); // $ExpectType void ref.writeUInt64LE(buffer, number, int64Like); // $ExpectType void ref._attach(buffer, jsObject); // $ExpectType Buffer ref._reinterpret(buffer, number); // $ExpectType Buffer ref._reinterpret(buffer, number, undefined); // $ExpectType Buffer ref._reinterpret(buffer, number, number); // $ExpectType Buffer ref._reinterpretUntilZeros(buffer, number); // $ExpectType Buffer ref._reinterpretUntilZeros(buffer, number, undefined); // $ExpectType Buffer ref._reinterpretUntilZeros(buffer, number, number); // $ExpectType void ref._writePointer(buffer, number, buffer); // $ExpectType void ref._writeObject(buffer, number, jsObject); // $ExpectType Type<void> ref.types.void; // @ts-expect-error ref.types.pointer; // `pointer` doesn't exist on `types`, though it exists on `sizeof`/`alignof` // $ExpectType Type<string | number> ref.types.int64; // $ExpectType Type<number> ref.types.ushort; // $ExpectType Type<number> ref.types.int; // $ExpectType Type<string | number> ref.types.uint64; // $ExpectType Type<number> ref.types.float; // $ExpectType Type<number> ref.types.uint; // $ExpectType Type<string | number> ref.types.long; // $ExpectType Type<number> ref.types.double; // $ExpectType Type<number> ref.types.int8; // $ExpectType Type<string | number> ref.types.ulong; // $ExpectType Type<unknown> ref.types.Object; // $ExpectType Type<number> ref.types.uint8; // $ExpectType Type<string | number> ref.types.longlong; // $ExpectType Type<string | null> ref.types.CString; // $ExpectType Type<number> ref.types.int16; // $ExpectType Type<string | number> ref.types.ulonglong; // $ExpectType Type<boolean> ref.types.bool; // $ExpectType Type<number> ref.types.uint16; // $ExpectType Type<number> ref.types.char; // $ExpectType Type<number> ref.types.byte; // $ExpectType Type<number> ref.types.int32; // $ExpectType Type<number> ref.types.uchar; // $ExpectType Type<string | number> ref.types.size_t; // $ExpectType Type<number> ref.types.uint32; // $ExpectType Type<number> ref.types.short; // @ts-expect-error ref.alignof.void; // `void` doesn't have an alignment // $ExpectType number ref.alignof.pointer; // $ExpectType number ref.alignof.int64; // $ExpectType number ref.alignof.ushort; // $ExpectType number ref.alignof.int; // $ExpectType number ref.alignof.uint64; // $ExpectType number ref.alignof.float; // $ExpectType number ref.alignof.uint; // $ExpectType number ref.alignof.long; // $ExpectType number ref.alignof.double; // $ExpectType number ref.alignof.int8; // $ExpectType number ref.alignof.ulong; // $ExpectType number ref.alignof.Object; // $ExpectType number ref.alignof.uint8; // $ExpectType number ref.alignof.longlong; // @ts-expect-error ref.alignof.CString; // `CString` doesn't have an alignment // $ExpectType number ref.alignof.int16; // $ExpectType number ref.alignof.ulonglong; // $ExpectType number ref.alignof.bool; // $ExpectType number ref.alignof.uint16; // $ExpectType number ref.alignof.char; // $ExpectType number ref.alignof.byte; // $ExpectType number ref.alignof.int32; // $ExpectType number ref.alignof.uchar; // $ExpectType number ref.alignof.size_t; // $ExpectType number ref.alignof.uint32; // $ExpectType number ref.alignof.short; // @ts-expect-error ref.sizeof.void; // `void` doesn't have an size // $ExpectType number ref.sizeof.pointer; // $ExpectType number ref.sizeof.int64; // $ExpectType number ref.sizeof.ushort; // $ExpectType number ref.sizeof.int; // $ExpectType number ref.sizeof.uint64; // $ExpectType number ref.sizeof.float; // $ExpectType number ref.sizeof.uint; // $ExpectType number ref.sizeof.long; // $ExpectType number ref.sizeof.double; // $ExpectType number ref.sizeof.int8; // $ExpectType number ref.sizeof.ulong; // $ExpectType number ref.sizeof.Object; // $ExpectType number ref.sizeof.uint8; // $ExpectType number ref.sizeof.longlong; // @ts-expect-error ref.sizeof.CString; // `CString` doesn't have an size // $ExpectType number ref.sizeof.int16; // $ExpectType number ref.sizeof.ulonglong; // $ExpectType number ref.sizeof.bool; // $ExpectType number ref.sizeof.uint16; // $ExpectType number ref.sizeof.char; // $ExpectType number ref.sizeof.byte; // $ExpectType number ref.sizeof.int32; // $ExpectType number ref.sizeof.uchar; // $ExpectType number ref.sizeof.size_t; // $ExpectType number ref.sizeof.uint32; // $ExpectType number ref.sizeof.short; // $ExpectType number buffer.address(); // $ExpectType string buffer.hexAddress(); // $ExpectType boolean buffer.isNull(); // $ExpectType Buffer buffer.ref(); // $ExpectType any buffer.deref(); // $ExpectType Object buffer.readObject(); // $ExpectType Object buffer.readObject(undefined); // $ExpectType Object buffer.readObject(number); // $ExpectType void buffer.writeObject(jsObject, number); // $ExpectType Buffer buffer.readPointer(); // $ExpectType Buffer buffer.readPointer(undefined); // $ExpectType Buffer buffer.readPointer(undefined, undefined); // $ExpectType Buffer buffer.readPointer(number); // $ExpectType Buffer buffer.readPointer(number, undefined); // $ExpectType Buffer buffer.readPointer(number, number); // $ExpectType void buffer.writePointer(buffer, number); // $ExpectType string buffer.readCString(); // $ExpectType string buffer.readCString(undefined); // $ExpectType string buffer.readCString(number); // $ExpectType void buffer.writeCString(string, number); // $ExpectType void buffer.writeCString(string, number, undefined); // $ExpectType void buffer.writeCString(string, number, string); // $ExpectType string | number buffer.readInt64BE(); // $ExpectType string | number buffer.readInt64BE(undefined); // $ExpectType string | number buffer.readInt64BE(number); // $ExpectType void buffer.writeInt64BE(int64Like, number); // $ExpectType string | number buffer.readUInt64BE(); // $ExpectType string | number buffer.readUInt64BE(undefined); // $ExpectType string | number buffer.readUInt64BE(number); // $ExpectType void buffer.writeUInt64BE(int64Like, number); // $ExpectType string | number buffer.readInt64LE(); // $ExpectType string | number buffer.readInt64LE(undefined); // $ExpectType string | number buffer.readInt64LE(number); // $ExpectType void buffer.writeInt64LE(int64Like, number); // $ExpectType string | number buffer.readUInt64LE(); // $ExpectType string | number buffer.readUInt64LE(undefined); // $ExpectType string | number buffer.readUInt64LE(number); // $ExpectType void buffer.writeUInt64LE(int64Like, number); // $ExpectType Buffer buffer.reinterpret(number); // $ExpectType Buffer buffer.reinterpret(number, undefined); // $ExpectType Buffer buffer.reinterpret(number, number); // $ExpectType Buffer buffer.reinterpretUntilZeros(number); // $ExpectType Buffer buffer.reinterpretUntilZeros(number, undefined); // $ExpectType Buffer buffer.reinterpretUntilZeros(number, number); // $ExpectType Type<any> | undefined buffer.type; // Override types test: declare module "ref-napi" { interface UnderlyingTypeOverrideRegistry { "foo": number; } } // $ExpectType Type<number> ref.coerceType("foo");
the_stack
import sleep from 'sleep-promise' import { execCmdWithExitOnFailure } from 'src/lib/cmd-utils' import { retryCmd } from 'src/lib/utils' import { getAksClusterConfig } from './context-utils' import { AksClusterConfig } from './k8s-cluster/aks' /** * getIdentity gets basic info on an existing identity. If the identity doesn't * exist, undefined is returned */ export async function getIdentity(clusterConfig: AksClusterConfig, identityName: string) { const [matchingIdentitiesStr] = await execCmdWithExitOnFailure( `az identity list -g ${clusterConfig.resourceGroup} --query "[?name == '${identityName}']" -o json` ) const matchingIdentities = JSON.parse(matchingIdentitiesStr) if (!matchingIdentities.length) { return } // There should only be one exact match by name return matchingIdentities[0] } // createIdentityIdempotent creates an identity if it doesn't already exist. // Returns an object including basic info on the identity. export async function createIdentityIdempotent( clusterConfig: AksClusterConfig, identityName: string ) { const identity = await getIdentity(clusterConfig, identityName) if (identity) { console.info( `Skipping identity creation, ${identityName} in resource group ${clusterConfig.resourceGroup} already exists` ) return identity } console.info(`Creating identity ${identityName} in resource group ${clusterConfig.resourceGroup}`) // This command is idempotent-- if the identity exists, the existing one is given const [results] = await execCmdWithExitOnFailure( `az identity create -n ${identityName} -g ${clusterConfig.resourceGroup} -o json` ) return JSON.parse(results) } /** * deleteIdentity gets basic info on an existing identity */ export function deleteIdentity(clusterConfig: AksClusterConfig, identityName: string) { return execCmdWithExitOnFailure( `az identity delete -n ${identityName} -g ${clusterConfig.resourceGroup} -o json` ) } async function roleIsAssigned(assignee: string, scope: string, role: string) { const [matchingAssignedRoles] = await retryCmd( () => execCmdWithExitOnFailure( `az role assignment list --assignee ${assignee} --scope ${scope} --query "length([?roleDefinitionName == '${role}'])" -o tsv` ), 10 ) return parseInt(matchingAssignedRoles.trim(), 10) > 0 } export async function assignRoleIdempotent( assigneeObjectId: string, assigneePrincipalType: string, scope: string, role: string ) { if (await roleIsAssigned(assigneeObjectId, scope, role)) { console.info( `Skipping role assignment, role ${role} already assigned to ${assigneeObjectId} for scope ${scope}` ) return } console.info( `Assigning role ${role} to ${assigneeObjectId} type ${assigneePrincipalType} for scope ${scope}` ) await retryCmd( () => execCmdWithExitOnFailure( `az role assignment create --role "${role}" --assignee-object-id ${assigneeObjectId} --assignee-principal-type ${assigneePrincipalType} --scope ${scope}` ), 10 ) } export async function getAKSNodeResourceGroup(clusterConfig: AksClusterConfig) { const [nodeResourceGroup] = await execCmdWithExitOnFailure( `az aks show --name ${clusterConfig.clusterName} --resource-group ${clusterConfig.resourceGroup} --query nodeResourceGroup -o tsv` ) return nodeResourceGroup.trim() } /** * Gets the AKS Service Principal Object ID if one exists. Otherwise, an empty string is given. */ export async function getAKSServicePrincipalObjectId(clusterConfig: AksClusterConfig) { // Get the correct object ID depending on the cluster configuration // See https://github.com/Azure/aad-pod-identity/blob/b547ba86ab9b16d238db8a714aaec59a046afdc5/docs/readmes/README.role-assignment.md#obtaining-the-id-of-the-managed-identity--service-principal const [rawServicePrincipalClientId] = await execCmdWithExitOnFailure( `az aks show -n ${clusterConfig.clusterName} --query servicePrincipalProfile.clientId -g ${clusterConfig.resourceGroup} -o tsv` ) const servicePrincipalClientId = rawServicePrincipalClientId.trim() // This will be the value of the service principal client ID if a managed service identity // is being used instead of a service principal. if (servicePrincipalClientId === 'msi') { return '' } const [rawObjectId] = await execCmdWithExitOnFailure( `az ad sp show --id ${servicePrincipalClientId} --query objectId -o tsv` ) return rawObjectId.trim() } /** * If an AKS cluster is using a managed service identity, the objectId is returned. * Otherwise, an empty string is given. */ export async function getAKSManagedServiceIdentityObjectId(clusterConfig: AksClusterConfig) { const [managedIdentityObjectId] = await execCmdWithExitOnFailure( `az aks show -n ${clusterConfig.clusterName} --query identityProfile.kubeletidentity.objectId -g ${clusterConfig.resourceGroup} -o tsv` ) return managedIdentityObjectId.trim() } export async function registerStaticIPIfNotRegistered(name: string, resourceGroupIP: string) { // This returns an array of matching IP addresses. If there is no matching IP // address, an empty array is returned. We expect at most 1 matching IP const [existingIpsStr] = await execCmdWithExitOnFailure( `az network public-ip list --resource-group ${resourceGroupIP} --query "[?name == '${name}' && sku.name == 'Standard'].ipAddress" -o json` ) const existingIps = JSON.parse(existingIpsStr) if (existingIps.length) { console.info(`Skipping IP address registration, ${name} on ${resourceGroupIP} exists`) // We expect only 1 matching IP return existingIps[0] } console.info(`Registering IP address ${name} on ${resourceGroupIP}`) const [address] = await execCmdWithExitOnFailure( `az network public-ip create --resource-group ${resourceGroupIP} --name ${name} --allocation-method Static --sku Standard --query publicIp.ipAddress -o tsv` ) return address.trim() } export async function deallocateStaticIP(name: string, resourceGroupIP: string) { console.info(`Deallocating IP address ${name} on ${resourceGroupIP}`) return execCmdWithExitOnFailure( `az network public-ip delete --resource-group ${resourceGroupIP} --name ${name}` ) } export async function waitForStaticIPDetachment(name: string, resourceGroup: string) { const maxTryCount = 15 const tryIntervalMs = 3000 for (let tryCount = 0; tryCount < maxTryCount; tryCount++) { const [allocated] = await execCmdWithExitOnFailure( `az network public-ip show --resource-group ${resourceGroup} --name ${name} --query ipConfiguration.id -o tsv` ) if (allocated.trim() === '') { return true } await sleep(tryIntervalMs) } throw Error(`Too many tries waiting for static IP association ID removal`) } /** * This creates an Azure identity to access a key vault */ export async function createKeyVaultIdentityIfNotExists( context: string, identityName: string, keyVaultName: string, keyVaultResourceGroup: string | null | undefined, keyPermissions: string[] | null, secretPermissions: string[] | null ) { const clusterConfig = getAksClusterConfig(context) const identity = await createIdentityIdempotent(clusterConfig, identityName) // We want to grant the identity for the cluster permission to manage the odis signer identity. // Get the correct object ID depending on the cluster configuration, either // the service principal or the managed service identity. // See https://github.com/Azure/aad-pod-identity/blob/b547ba86ab9b16d238db8a714aaec59a046afdc5/docs/readmes/README.role-assignment.md#obtaining-the-id-of-the-managed-identity--service-principal let assigneeObjectId = await getAKSServicePrincipalObjectId(clusterConfig) let assigneePrincipalType = 'ServicePrincipal' // TODO Check how to manage the MSI type if (!assigneeObjectId) { assigneeObjectId = await getAKSManagedServiceIdentityObjectId(clusterConfig) // assigneePrincipalType = 'MSI' assigneePrincipalType = 'ServicePrincipal' } await assignRoleIdempotent( assigneeObjectId, assigneePrincipalType, identity.id, 'Managed Identity Operator' ) // Allow the odis signer identity to access the correct key vault await setKeyVaultPolicyIfNotSet( clusterConfig, keyVaultName, keyVaultResourceGroup, identity, keyPermissions, secretPermissions ) return identity } async function setKeyVaultPolicyIfNotSet( clusterConfig: AksClusterConfig, keyVaultName: string, keyVaultResourceGroup: string | null | undefined, azureIdentity: any, keyPermissions: string[] | null, secretPermissions: string[] | null ) { const kvResourceGroup = keyVaultResourceGroup ? keyVaultResourceGroup : clusterConfig.resourceGroup const queryFilters = [`?objectId == '${azureIdentity.principalId}'`] if (keyPermissions) { queryFilters.push( `sort(permissions.keys) == [${keyPermissions.map((perm) => `'${perm}'`).join(', ')}]` ) } if (secretPermissions) { queryFilters.push( `sort(permissions.secrets) == [${secretPermissions.map((perm) => `'${perm}'`).join(', ')}]` ) } const [keyVaultPoliciesStr] = await execCmdWithExitOnFailure( `az keyvault show --name ${keyVaultName} -g ${kvResourceGroup} --query "properties.accessPolicies[${queryFilters.join( ' && ' )}]"` ) const keyVaultPolicies = JSON.parse(keyVaultPoliciesStr) if (keyVaultPolicies.length) { const keyPermStr = keyPermissions ? `key permissions: ${keyPermissions.join(' ')}` : '' const secretPermStr = secretPermissions ? `secret permissions: ${secretPermissions.join(' ')}` : '' console.info( `Skipping setting policy {${keyPermStr}, ${secretPermStr}}. Already set for vault ${keyVaultName} and identity objectId ${azureIdentity.principalId}` ) return } if (keyPermissions) { console.info( `Setting key permissions ${keyPermissions.join( ' ' )} for vault ${keyVaultName} and identity objectId ${azureIdentity.principalId}` ) return execCmdWithExitOnFailure( `az keyvault set-policy --name ${keyVaultName} --key-permissions ${keyPermissions.join( ' ' )} --object-id ${azureIdentity.principalId} -g ${kvResourceGroup}` ) } if (secretPermissions) { console.info( `Setting secret permissions ${secretPermissions.join( ' ' )} for vault ${keyVaultName} and identity objectId ${azureIdentity.principalId}` ) return execCmdWithExitOnFailure( `az keyvault set-policy --name ${keyVaultName} --secret-permissions ${secretPermissions.join( ' ' )} --object-id ${azureIdentity.principalId} -g ${kvResourceGroup}` ) } } /** * deleteAzureKeyVaultIdentity deletes the key vault policy and the managed identity */ export async function deleteAzureKeyVaultIdentity( context: string, identityName: string, keyVaultName: string ) { const clusterConfig = getAksClusterConfig(context) await deleteKeyVaultPolicy(clusterConfig, identityName, keyVaultName) return deleteIdentity(clusterConfig, identityName) } async function deleteKeyVaultPolicy( clusterConfig: AksClusterConfig, identityName: string, keyVaultName: string ) { const azureIdentity = await getIdentity(clusterConfig, identityName) return execCmdWithExitOnFailure( `az keyvault delete-policy --name ${keyVaultName} --object-id ${azureIdentity.principalId} -g ${clusterConfig.resourceGroup}` ) } /** * @return the intended name of an azure identity given a key vault name */ export function getAzureKeyVaultIdentityName( context: string, prefix: string, keyVaultName: string ) { // from https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/resource-name-rules#microsoftmanagedidentity const maxIdentityNameLength = 128 return `${prefix}-${keyVaultName}-${context}`.substring(0, maxIdentityNameLength) }
the_stack
import * as React from "react"; import { ZxSpectrumCoreBase } from "../machines/zx-spectrum/ZxSpectrumCoreBase"; import { Z88ButtonClickArgs } from "./ui-core-types"; import Key from "./Cz88Key"; import { defaultZ88KeyboardLayout } from "../machines/cambridge-z88/key-layout-default"; import { esZ88KeyboardLayout } from "../machines/cambridge-z88/key-layout-es"; import { frZ88KeyboardLayout } from "../machines/cambridge-z88/key-layout-fr"; import { deZ88KeyboardLayout } from "../machines/cambridge-z88/key-layout-de"; import { dkZ88KeyboardLayout } from "../machines/cambridge-z88/key-layout-dk"; import { seZ88KeyboardLayout } from "../machines/cambridge-z88/key-layout-se"; import { Cz88KeyboardLayout } from "../machines/cambridge-z88/cz88-keys"; import styles from "styled-components"; import { getVmEngineService } from "../machines/core/vm-engine-service"; const DEFAULT_WIDTH = 15 * 108 + 200 + 48; const DEFAULT_HEIGHT = 5 * (100 + 8) + 48; // --- Special key codes const LEFT_SHIFT_KEY = 54; const SQUARE_KEY = 62; const DIAMOND_KEY = 52; /** * Component properties */ interface Props { width: number; height: number; layout?: string; } /** * Represents the keyboard of Czmbridge Z88 */ export default function Cz88Keyboard(props: Props) { // --- Prepare keyboard layout information let l: Cz88KeyboardLayout; switch (props.layout) { case "es": l = esZ88KeyboardLayout; break; case "fr": l = frZ88KeyboardLayout; break; case "de": l = deZ88KeyboardLayout; break; case "dk": l = dkZ88KeyboardLayout; break; case "se": l = seZ88KeyboardLayout; break; default: l = defaultZ88KeyboardLayout; break; } const zoom = calculateZoom(props.width, props.height); return ( <Root> <KeyRow> <Key zoom={zoom} code={61} layoutInfo={l.Escape} keyAction={click} /> <Key zoom={zoom} code={45} layoutInfo={l.N1} keyAction={click} /> <Key zoom={zoom} code={37} layoutInfo={l.N2} keyAction={click} /> <Key zoom={zoom} code={29} layoutInfo={l.N3} keyAction={click} /> <Key zoom={zoom} code={21} layoutInfo={l.N4} keyAction={click} /> <Key zoom={zoom} code={13} layoutInfo={l.N5} keyAction={click} /> <Key zoom={zoom} code={5} layoutInfo={l.N6} keyAction={click} /> <Key zoom={zoom} code={1} layoutInfo={l.N7} keyAction={click} /> <Key zoom={zoom} code={0} layoutInfo={l.N8} keyAction={click} /> <Key zoom={zoom} code={24} layoutInfo={l.N9} keyAction={click} /> <Key zoom={zoom} code={40} layoutInfo={l.N0} keyAction={click} /> <Key zoom={zoom} code={31} layoutInfo={l.Minus} keyAction={click} /> <Key zoom={zoom} code={23} layoutInfo={l.Equal} keyAction={click} /> <Key zoom={zoom} code={15} layoutInfo={l.Backslash} keyAction={click} /> <Key zoom={zoom} code={7} layoutInfo={l.Delete} keyAction={click} /> </KeyRow> <KeyRow2To3> <div style={{ margin: 0 }}> <KeyRow> <Key zoom={zoom} code={53} layoutInfo={l.Tab} keyAction={click} xwidth={140} /> <Key zoom={zoom} code={44} layoutInfo={l.Q} keyAction={click} /> <Key zoom={zoom} code={36} layoutInfo={l.W} keyAction={click} /> <Key zoom={zoom} code={28} layoutInfo={l.E} keyAction={click} /> <Key zoom={zoom} code={20} layoutInfo={l.R} keyAction={click} /> <Key zoom={zoom} code={12} layoutInfo={l.T} keyAction={click} /> <Key zoom={zoom} code={4} layoutInfo={l.Y} keyAction={click} /> <Key zoom={zoom} code={9} layoutInfo={l.U} keyAction={click} /> <Key zoom={zoom} code={8} layoutInfo={l.I} keyAction={click} /> <Key zoom={zoom} code={16} layoutInfo={l.O} keyAction={click} /> <Key zoom={zoom} code={32} layoutInfo={l.P} keyAction={click} /> <Key zoom={zoom} code={47} layoutInfo={l.SBracketL} keyAction={click} /> <Key zoom={zoom} code={39} layoutInfo={l.SBracketR} keyAction={click} /> </KeyRow> <KeyRow> <Key zoom={zoom} code={52} layoutInfo={l.Diamond} keyAction={click} vshift={8} fontSize={60} xwidth={180} /> <Key zoom={zoom} code={43} layoutInfo={l.A} keyAction={click} /> <Key zoom={zoom} code={35} layoutInfo={l.S} keyAction={click} /> <Key zoom={zoom} code={27} layoutInfo={l.D} keyAction={click} /> <Key zoom={zoom} code={19} layoutInfo={l.F} keyAction={click} /> <Key zoom={zoom} code={11} layoutInfo={l.G} keyAction={click} /> <Key zoom={zoom} code={3} layoutInfo={l.H} keyAction={click} /> <Key zoom={zoom} code={17} layoutInfo={l.J} keyAction={click} /> <Key zoom={zoom} code={25} layoutInfo={l.K} keyAction={click} /> <Key zoom={zoom} code={41} layoutInfo={l.L} keyAction={click} /> <Key zoom={zoom} code={49} layoutInfo={l.Semicolon} keyAction={click} /> <Key zoom={zoom} code={48} layoutInfo={l.Quote} keyAction={click} /> <Key zoom={zoom} code={56} layoutInfo={l.Pound} keyAction={click} /> </KeyRow> </div> <EnterContainer> <Key zoom={zoom} code={6} keyAction={click} isEnter={true} xwidth={122} xheight={200} /> </EnterContainer> </KeyRow2To3> <KeyRow> <Key zoom={zoom} code={54} layoutInfo={l.ShiftL} keyAction={click} xwidth={240} /> <Key zoom={zoom} code={42} layoutInfo={l.Z} keyAction={click} /> <Key zoom={zoom} code={34} layoutInfo={l.X} keyAction={click} /> <Key zoom={zoom} code={26} layoutInfo={l.C} keyAction={click} /> <Key zoom={zoom} code={18} layoutInfo={l.V} keyAction={click} /> <Key zoom={zoom} code={10} layoutInfo={l.B} keyAction={click} /> <Key zoom={zoom} code={2} layoutInfo={l.N} keyAction={click} /> <Key zoom={zoom} code={33} layoutInfo={l.M} keyAction={click} /> <Key zoom={zoom} code={50} layoutInfo={l.Comma} keyAction={click} /> <Key zoom={zoom} code={58} layoutInfo={l.Period} keyAction={click} /> <Key zoom={zoom} code={57} layoutInfo={l.Slash} keyAction={click} /> <Key zoom={zoom} code={63} layoutInfo={l.ShiftR} keyAction={click} xwidth={160} /> <Key zoom={zoom} code={14} layoutInfo={l.Up} keyAction={click} vshift={8} fontSize={60} /> </KeyRow> <KeyRow> <Key zoom={zoom} code={60} layoutInfo={l.Index} keyAction={click} /> <Key zoom={zoom} code={51} layoutInfo={l.Menu} keyAction={click} /> <Key zoom={zoom} code={55} layoutInfo={l.Help} keyAction={click} /> <Key zoom={zoom} code={62} layoutInfo={l.Square} keyAction={click} vshift={8} fontSize={60} /> <Key zoom={zoom} code={46} layoutInfo={l.Space} keyAction={click} xwidth={702} /> <Key zoom={zoom} code={59} keyAction={click} top="CAPS" bottom="LOCK" /> <Key zoom={zoom} code={38} layoutInfo={l.Left} keyAction={click} fontSize={60} vshift={8} /> <Key zoom={zoom} code={30} layoutInfo={l.Right} keyAction={click} vshift={8} fontSize={60} /> <Key zoom={zoom} code={22} layoutInfo={l.Down} keyAction={click} vshift={8} fontSize={60} /> </KeyRow> </Root> ); function click(e: Z88ButtonClickArgs): void { const vmEngineService = getVmEngineService(); if (!vmEngineService.hasEngine) { // --- No engine return; } const engine = vmEngineService.getEngine() as ZxSpectrumCoreBase; // --- Set status of the primary key engine.setKeyStatus(e.code, e.down); // --- Set status of the secondary key switch (e.iconCount) { case 0: case 1: if (!e.isLeft) { engine.setKeyStatus(LEFT_SHIFT_KEY, e.down); } break; case 2: if (e.keyCategory === "symbol") { engine.setKeyStatus(e.isLeft ? LEFT_SHIFT_KEY : SQUARE_KEY, e.down); } break; case 3: if (e.keyCategory === "key" && !e.isLeft) { engine.setKeyStatus(LEFT_SHIFT_KEY, e.down); } else if (e.keyCategory === "symbol") { if (e.special === "dk") { engine.setKeyStatus(SQUARE_KEY, e.down); } else { engine.setKeyStatus(e.isLeft ? LEFT_SHIFT_KEY : SQUARE_KEY, e.down); } } else if (e.keyCategory === "secondSymbol" && e.isLeft) { engine.setKeyStatus(DIAMOND_KEY, e.down); } break; } } function calculateZoom(width: number, height: number): number { if (!width || !height) return 0.05; let widthRatio = (width - 24) / DEFAULT_WIDTH; let heightRatio = (height - 32) / DEFAULT_HEIGHT; return Math.min(widthRatio, heightRatio); } } // --- Helper component tags const Root = styles.div` display: flex; flex-direction: column; flex-shrink: 0; flex-grow: 0; height: 100%; background-color: transparent; box-sizing: border-box; align-content: start; justify-items: start; justify-content: center; overflow: hidden; `; const KeyRow = styles.div` padding: 0px 0px; margin: 0; display: flex; flex-grow: 0; flex-shrink: 0; font-weight: bold; `; const KeyRow2To3 = styles.div` display: flex; flex-direction: row; flex-grow: 0; flex-shrink: 0; margin: 0; `; const EnterContainer = styles.div` display: flex; flex-grow: 0; flex-shrink: 0; font-weight: bold; margin: 0; `;
the_stack
import { Id } from "./Data"; import { Doc, Indent, Level, OpenOp } from "./Doc"; import React, { Dispatch, FunctionComponent, useState } from "react"; import { InlineDocComponent } from "./InlineDoc"; import './TreeAndDoc.css'; import { Callout, Classes, Tag, Tooltip } from "@blueprintjs/core"; import { decorators as TreebeardDecorators, Treebeard, TreebeardProps, TreeNode as TreebeardTreeNode, } from "react-treebeard"; import { State } from "./state"; // FormatterDecisions formatting stuff type ExplorationNode = { type: "exploration", parentId?: Id, id: Id, humanDescription: string, children: ReadonlyArray<LevelNode>, startColumn: number, result?: ExplorationResult, incomingState?: State, }; type LevelNode = { type: "level", id: Id, parentId: Id, flat: string, toString: string, acceptedExplorationId: Id, levelId: Id, children: ReadonlyArray<ExplorationNode>, incomingState: State, openOp: OpenOp, evaluatedIndent: number }; interface ExplorationResult { outputLevel: Level; finalState: State; } export type FormatterDecisions = ExplorationNode; export interface ITreeState { nodes: TreeNode[]; selectedNodeId?: string, /** Treebeard's caching is broken as it mutates its props... Therefore, we force it to only render when we want it to. */ treeCacheBust: number, } /** Treebeard doesn't have typescript bindings, so have to manually specify them. */ interface TreeNode extends TreebeardTreeNode { // Custom data: NodeData, } type ExplorationNodeData = ExplorationNode & { parentLevelId?: Id }; type LevelNodeData = { levelId: Id, incomingState: State }; type NodeData = LevelNodeData | ExplorationNodeData; /** A doc that should be displayed because it's currently being highlighted in the {@link DecisionTree}. */ type DisplayableLevel = { level: Level, startingColumn: number }; type Highlighted = DisplayableLevel | undefined; export const TreeAndDoc: React.FC<{ formatterDecisions: FormatterDecisions, doc: Doc }> = props => { const [highlighted, setHighlighted] = useState<Highlighted>(); const [highlightedLevelId, setHighlightedLevelId] = useState<Id>(); const [selected, setSelected] = useState<NodeData>(); function formatState(state: State) { return <span>{JSON.stringify(state)}</span> } function formatNodeData(data: NodeData): JSX.Element | undefined { if ("levelId" in data) { return <table> <tbody> <tr> <td><Tag intent={"primary"}>Incoming</Tag></td> <td>{formatState(data.incomingState)}</td> </tr> </tbody> </table> } if (data.result) { // We always have an incoming state unless we're the root. return <table> <tbody> <tr> <td><Tag intent={"primary"}>Incoming</Tag></td> <td>{formatState(data.incomingState!!)}</td> </tr> {data.result ? <tr> <td><Tag intent={"success"}>Result</Tag></td> <td>{formatState(data.result.finalState)}</td> </tr> : null} </tbody> </table>; } } function nodeInfoBlock() { const title = selected !== undefined ? "levelId" in selected ? "Level node" : "Exploration node" : "<no node selected>"; return <Callout intent={"none"} title={title} className={"node-info"}> {selected !== undefined ? formatNodeData(selected) : null} </Callout>; } return <div className={"TreeAndDoc"}> <div className={"column1"}> {nodeInfoBlock()} <DecisionTree formatterDecisions={props.formatterDecisions} highlightDoc={setHighlighted} highlightLevelId={setHighlightedLevelId} select={setSelected}/> </div> <div className={"InlineDocs"}> <InlineDocComponent key={"entire-doc"} doc={props.doc} statingColumn={0} className={"InlineDoc"} highlightedLevelId={highlightedLevelId}/> {/* TODO grab this from `selected` */} {highlighted !== undefined ? ([ <Callout intent={"primary"} title={"Rendered exploration output"}/>, <InlineDocComponent key={"exploration"} doc={highlighted.level} statingColumn={highlighted.startingColumn} className={"HighlightInlineDoc"}/>, ]) : null } </div> </div> }; interface DecisionTreeProps { formatterDecisions: FormatterDecisions; highlightDoc: Dispatch<Highlighted>; highlightLevelId: Dispatch<Id | undefined>; select: Dispatch<NodeData>; } export class DecisionTree extends React.PureComponent<DecisionTreeProps, ITreeState> { public state: ITreeState = { nodes: DecisionTree.createExplorationNode(this.props.formatterDecisions).children!!, treeCacheBust: 0, }; private static readonly duration = 50; /** Default TreeBeard animations are too slow (300), sadly have to reimplement this to get a shorter duration. */ static Animations = { toggle: function (_ref: { node: { toggled: boolean } }): { duration: number; animation: { rotateZ: number } } { const toggled = _ref.node.toggled; const duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DecisionTree.duration; return { animation: { rotateZ: toggled ? 90 : 0, }, duration: duration, }; }, drawer: function () { return ( /* props */ { enter: { animation: 'slideDown', duration: DecisionTree.duration, }, leave: { animation: 'slideUp', duration: DecisionTree.duration, }, } ); }, }; private static CastTreebeard<N extends TreeNode>(): FunctionComponent<TreebeardProps<N>> { return Treebeard; } /** * Treebeard isn't defined as a memoized thing so we need to. * We use this memoization to indicate that only decorators.cacheBust should matter when determining up-to-dateness. */ private static MemoTreebeard: React.NamedExoticComponent<TreebeardProps<TreeNode>> = React.memo( DecisionTree.CastTreebeard<TreeNode>(), (prevProps, nextProps) => prevProps.decorators.cacheBust === nextProps.decorators.cacheBust); public render() { return <div className={`${Classes.ELEVATION_0} DecisionTree`}> {/* Indicate which line is selected without refreshing the tree, because that is too slow. */} {/* See https://medium.learnreact.com/the-style-tag-and-react-24d6dd3ca974 */} <style dangerouslySetInnerHTML={{ __html: ` .node-${this.state.selectedNodeId} { background-color: #2B95D6 !important } `, }}/> <DecisionTree.MemoTreebeard data={this.state.nodes} onToggle={this.onToggle} animations={DecisionTree.Animations} decorators={this.Decorators()} /> </div>; } private static createExplorationNode(node: ExplorationNode, parent?: LevelNode): TreeNode { const onAcceptedPath = !parent || parent.acceptedExplorationId === node.id; return { id: node.id.toString(), children: node.children.length > 0 ? node.children.map(child => DecisionTree.createLevelNode(child, onAcceptedPath)) : undefined, name: <div> <Tooltip content={node.id.toString()}> <span className={"explorationNode-description"}>{node.humanDescription}</span> </Tooltip> </div>, toggled: onAcceptedPath, active: onAcceptedPath, data: { ...node, parentLevelId: parent !== undefined ? parent.levelId : undefined, }, }; } private static createLevelNode(node: LevelNode, parentAccepted: boolean): TreeNode { const indent = this.renderIndentTag(node.openOp.plusIndent, node.evaluatedIndent); return { id: node.id.toString(), children: node.children.length > 0 ? node.children.map(child => DecisionTree.createExplorationNode(child, node)) : undefined, name: ( <div> <Tooltip content={`Node ID: ${node.id.toString()}, Level ID: ${node.levelId.toString()}`}> {node.openOp.debugName || node.id} </Tooltip> {" "}{indent} </div> ), toggled: true, active: parentAccepted, data: { levelId: node.levelId, incomingState: node.incomingState, }, }; } private static renderConstIndent(indent: Indent) { switch (indent.type) { case "const": return <Tag intent={"success"}>+{indent.amount}</Tag>; case "if": throw Error(`Expected const indent but got ${indent}`) } } /** Render an indent differently, depending on whether it was conditional or not. */ private static renderIndentTag(indent: Indent, evaluatedIndent?: number) { switch (indent.type) { case "const": if (indent.amount === 0) { return; } return <Tag intent={"success"}>+{indent.amount}</Tag>; case "if": return <Tooltip position={"bottom-right"} content={ <span> thenIndent={this.renderConstIndent(indent.thenIndent)}{" "} elseIndent={this.renderConstIndent(indent.elseIndent)} </span>}> <Tag intent={"warning"}> {evaluatedIndent !== undefined ? `+${evaluatedIndent}` : '(unknown)'} </Tag> </Tooltip> } } private onToggle = (nodeData: TreeNode, toggled: boolean) => { nodeData.toggled = toggled; this.setState(prevState => ({...prevState, treeCacheBust: prevState.treeCacheBust + 1})); }; private highlightInlineDocLevel(id: Id) { this.props.highlightLevelId(id); } private highlightLevel(nodeData: TreeNode) { const data = nodeData.data; if ("levelId" in data) { this.highlightInlineDocLevel(data.levelId); } else { // It's an ExplorationNodeData if (data.parentLevelId !== undefined) { this.highlightInlineDocLevel(data.parentLevelId); } if (nodeData === this.state.nodes[0]) { this.props.highlightDoc(undefined); // no point highlighting the root } else if (data.result) { // The exploration had a result this.props.highlightDoc({ level: data.result.outputLevel, startingColumn: data.startColumn, }); } else { this.props.highlightDoc(undefined); } } this.props.select(data); } private onMouseEnter = (nodeData: TreeNode) => { this.highlightLevel(nodeData); this.setState(prevState => ({...prevState, selectedNodeId: nodeData.id})); }; /** * This is a hack to override the Container of {@link TreebeardDecorators} and still have access to the main * component object, because we don't control what gets passed to this inner component via props. */ private Container = ((outer: DecisionTree) => class extends TreebeardDecorators.Container { render() { const {style, decorators, terminal, onClick, node} = this.props; return ( <div onClick={onClick} className={`node-${node.id}`} style={node.active ? {...style.container} : {...style.link}} onMouseEnter={() => outer.onMouseEnter(node)} > {!terminal ? this.renderToggle() : null} <decorators.Header node={node} style={style.header}/> </div> ); } })(this); private Decorators = () => Object.assign({}, TreebeardDecorators, { Container: this.Container, // Force the tree to re-render cacheBust: this.state.treeCacheBust, }); }
the_stack
import { $TSAny, $TSContext, $TSObject, AmplifyCategories, AmplifySupportedService, exitOnNextTick, isResourceNameUnique, open, pathManager, ResourceDoesNotExistError, stateManager, } from 'amplify-cli-core'; import { byValues, printer, prompter } from 'amplify-prompts'; import inquirer from 'inquirer'; import _ from 'lodash'; import os from 'os'; import { v4 as uuid } from 'uuid'; import { ADMIN_QUERIES_NAME } from '../../../category-constants'; import { ApigwInputState } from '../apigw-input-state'; import { CrudOperation, PermissionSetting } from '../cdk-stack-builder'; import { getAllDefaults } from '../default-values/apigw-defaults'; import { ApigwAnswers, ApigwPath, ApigwWalkthroughReturnPromise, ApiRequirements } from '../service-walkthrough-types/apigw-types'; import { checkForPathOverlap, formatCFNPathParamsForExpressJs, validatePathName } from '../utils/rest-api-path-utils'; const category = AmplifyCategories.API; const serviceName = AmplifySupportedService.APIGW; const elasticContainerServiceName = 'ElasticContainer'; export async function serviceWalkthrough(context: $TSContext): ApigwWalkthroughReturnPromise { const allDefaultValues = getAllDefaults(context.amplify.getProjectDetails()); const resourceName = await askApiName(context, allDefaultValues.resourceName); const answers = { paths: {}, resourceName, dependsOn: undefined }; return pathFlow(context, answers); } export async function updateWalkthrough(context: $TSContext) { const { allResources } = await context.amplify.getResourceStatus(); const allDefaultValues = getAllDefaults(context.amplify.getProjectDetails()); const resources = allResources .filter(resource => resource.service === serviceName && resource.mobileHubMigrated !== true) .map(resource => resource.resourceName); if (resources.length === 0) { const errMessage = 'No REST API resource to update. Use "amplify add api" command to create a new REST API'; printer.error(errMessage); await context.usageData.emitError(new ResourceDoesNotExistError(errMessage)); exitOnNextTick(0); return; } let answers: $TSAny = { paths: [], }; const selectedApiName = await prompter.pick<'one', string>('Select the REST API you want to update:', resources); let updateApiOperation = await prompter.pick<'one', string>('What would you like to do?', [ { name: 'Add another path', value: 'add' }, { name: 'Update path', value: 'update' }, { name: 'Remove path', value: 'remove' }, ]); // Inquirer does not currently support combining 'when' and 'default', so // manually set the operation if the user ended up here via amplify api add. if (context.input.command === 'add') { updateApiOperation = 'add'; } if (selectedApiName === ADMIN_QUERIES_NAME) { const errMessage = `The Admin Queries API is maintained through the Auth category and should be updated using 'amplify update auth' command`; printer.warn(errMessage); await context.usageData.emitError(new ResourceDoesNotExistError(errMessage)); exitOnNextTick(0); } const projRoot = pathManager.findProjectRoot(); if (!stateManager.resourceInputsJsonExists(projRoot, category, selectedApiName)) { // Not yet migrated await migrate(context, projRoot, selectedApiName); // chose not to migrate if (!stateManager.resourceInputsJsonExists(projRoot, category, selectedApiName)) { exitOnNextTick(0); } } const parameters = stateManager.getResourceInputsJson(projRoot, category, selectedApiName); parameters.resourceName = selectedApiName; Object.assign(allDefaultValues, parameters); answers = { ...answers, ...parameters }; [answers.uuid] = uuid().split('-'); const pathNames = Object.keys(answers.paths); let updatedResult = {}; switch (updateApiOperation) { case 'add': { updatedResult = pathFlow(context, answers); break; } case 'remove': { const pathToRemove = await inquirer.prompt({ name: 'path', message: 'Select the path to remove', type: 'list', choices: pathNames, }); delete answers.paths[pathToRemove.path]; const { dependsOn, functionArns } = await findDependsOn(answers.paths); answers.dependsOn = dependsOn; answers.functionArns = functionArns; updatedResult = { answers }; break; } case 'update': { const pathToEdit = await inquirer.prompt({ name: 'pathName', message: 'Select the path to edit', type: 'list', choices: pathNames, }); // removing path from paths list const currentPath: ApigwPath = answers.paths[pathToEdit.pathName]; delete answers.paths[pathToEdit.pathName]; updatedResult = pathFlow(context, answers, currentPath); break; } default: { throw new Error(`Unrecognized API update operation "${updateApiOperation}"`); } } return updatedResult; } async function pathFlow(context: $TSContext, answers: ApigwAnswers, currentPath?: ApigwPath): ApigwWalkthroughReturnPromise { const pathsAnswer = await askPaths(context, answers, currentPath); return { answers: pathsAnswer }; } async function askApiName(context: $TSContext, defaultResourceName: string) { const apiNameValidator = (input: string) => { const amplifyValidatorOutput = context.amplify.inputValidation({ validation: { operator: 'regex', value: '^[a-zA-Z0-9]+$', onErrorMsg: 'Resource name should be alphanumeric', }, required: true, })(input); const adminQueriesName = 'AdminQueries'; if (input === adminQueriesName) { return `${adminQueriesName} is a reserved name for REST API resources for use by the auth category. Run "amplify update auth" to create an Admin Queries API.`; } let uniqueCheck = false; try { uniqueCheck = isResourceNameUnique(category, input); } catch (e) { return e.message || e; } return typeof amplifyValidatorOutput === 'string' ? amplifyValidatorOutput : uniqueCheck; }; const resourceName = await prompter.input<'one', string>( 'Provide a friendly name for your resource to be used as a label for this category in the project:', { initial: defaultResourceName, validate: apiNameValidator }, ); return resourceName; } async function askPermissions( context: $TSContext, answers: $TSObject, currentPath?: ApigwPath, ): Promise<{ setting?: PermissionSetting; auth?: CrudOperation[]; open?: boolean; userPoolGroups?: $TSObject; guest?: CrudOperation[] }> { while (true) { const apiAccess = await prompter.yesOrNo('Restrict API access?', currentPath?.permissions?.setting !== PermissionSetting.OPEN); if (!apiAccess) { return { setting: PermissionSetting.OPEN }; } const userPoolGroupList = context.amplify.getUserPoolGroupList(); let permissionSelected = 'Auth/Guest Users'; const permissions: $TSObject = {}; if (userPoolGroupList.length > 0) { do { if (permissionSelected === 'Learn more') { printer.blankLine(); printer.info( 'You can restrict access using CRUD policies for Authenticated Users, Guest Users, or on individual Group that users belong to' + ' in a User Pool. If a user logs into your application and is not a member of any group they will use policy set for ' + '“Authenticated Users”, however if they belong to a group they will only get the policy associated with that specific group.', ); printer.blankLine(); } const permissionSelection = await prompter.pick<'one', string>('Restrict access by:', [ 'Auth/Guest Users', 'Individual Groups', 'Both', 'Learn more', ]); permissionSelected = permissionSelection; } while (permissionSelected === 'Learn more'); } if (permissionSelected === 'Both' || permissionSelected === 'Auth/Guest Users') { const permissionSetting = await prompter.pick<'one', string>( 'Who should have access?', [ { name: 'Authenticated users only', value: PermissionSetting.PRIVATE, }, { name: 'Authenticated and Guest users', value: PermissionSetting.PROTECTED, }, ], { initial: currentPath?.permissions?.setting === PermissionSetting.PROTECTED ? 1 : 0 }, ); permissions.setting = permissionSetting; let { permissions: { auth: authPermissions }, } = currentPath || { permissions: { auth: [] } }; let { permissions: { guest: unauthPermissions }, } = currentPath || { permissions: { guest: [] } }; if (permissionSetting === PermissionSetting.PRIVATE) { permissions.auth = await askCRUD('Authenticated', authPermissions); const apiRequirements: ApiRequirements = { authSelections: 'identityPoolAndUserPool' }; await ensureAuth(context, apiRequirements, answers.resourceName); } if (permissionSetting === PermissionSetting.PROTECTED) { permissions.auth = await askCRUD('Authenticated', authPermissions); permissions.guest = await askCRUD('Guest', unauthPermissions); const apiRequirements: ApiRequirements = { authSelections: 'identityPoolAndUserPool', allowUnauthenticatedIdentities: true }; await ensureAuth(context, apiRequirements, answers.resourceName); } } if (permissionSelected === 'Both' || permissionSelected === 'Individual Groups') { // Enable Auth if not enabled const apiRequirements: ApiRequirements = { authSelections: 'identityPoolAndUserPool' }; await ensureAuth(context, apiRequirements, answers.resourceName); // Get Auth resource name const authResourceName = getAuthResourceName(); answers.authResourceName = authResourceName; let defaultSelectedGroups: string[] = []; if (currentPath?.permissions?.groups) { defaultSelectedGroups = Object.keys(currentPath.permissions.groups); } let selectedUserPoolGroupList = await prompter.pick<'many', string>('Select groups:', userPoolGroupList, { initial: byValues(defaultSelectedGroups)(userPoolGroupList), returnSize: 'many', pickAtLeast: 1, }); //if single user pool group is selected, convert to array if (selectedUserPoolGroupList && !Array.isArray(selectedUserPoolGroupList)) { selectedUserPoolGroupList = [selectedUserPoolGroupList]; } for (const selectedUserPoolGroup of selectedUserPoolGroupList) { let defaults = []; if (currentPath?.permissions?.groups?.[selectedUserPoolGroup]) { defaults = currentPath.permissions.groups[selectedUserPoolGroup]; } if (!permissions.groups) { permissions.groups = {}; } permissions.groups[selectedUserPoolGroup] = await askCRUD(selectedUserPoolGroup, defaults); } if (!permissions.setting) { permissions.setting = PermissionSetting.PRIVATE; } } return permissions; } } async function ensureAuth(context: $TSContext, apiRequirements: ApiRequirements, resourceName: string) { const checkResult: $TSAny = await context.amplify.invokePluginMethod(context, 'auth', undefined, 'checkRequirements', [ apiRequirements, context, 'api', resourceName, ]); // If auth is imported and configured, we have to throw the error instead of printing since there is no way to adjust the auth // configuration. if (checkResult.authImported === true && checkResult.errors && checkResult.errors.length > 0) { throw new Error(checkResult.errors.join(os.EOL)); } if (checkResult.errors && checkResult.errors.length > 0) { printer.warn(checkResult.errors.join(os.EOL)); } // If auth is not imported and there were errors, adjust or enable auth configuration if (!checkResult.authEnabled || !checkResult.requirementsMet) { try { await context.amplify.invokePluginMethod(context, 'auth', undefined, 'externalAuthEnable', [ context, AmplifyCategories.API, resourceName, apiRequirements, ]); } catch (error) { printer.error(error); throw error; } } } async function askCRUD(userType: string, permissions: CrudOperation[] = []) { const crudOptions = [CrudOperation.CREATE, CrudOperation.READ, CrudOperation.UPDATE, CrudOperation.DELETE]; const crudAnswers = await prompter.pick<'many', string>(`What permissions do you want to grant to ${userType} users?`, crudOptions, { returnSize: 'many', initial: byValues(permissions), pickAtLeast: 1, }); return crudAnswers; } async function askPaths(context: $TSContext, answers: $TSObject, currentPath?: ApigwPath): Promise<ApigwAnswers> { const existingFunctions = functionsExist(); let defaultFunctionType = 'newFunction'; const defaultChoice = { name: 'Create a new Lambda function', value: defaultFunctionType, }; const choices = [defaultChoice]; if (existingFunctions) { choices.push({ name: 'Use a Lambda function already added in the current Amplify project', value: 'projectFunction', }); } const paths = answers.paths; let addAnotherPath: boolean; do { let pathName: string; let isPathValid: boolean; do { pathName = await prompter.input('Provide a path (e.g., /book/{isbn}):', { initial: currentPath ? currentPath.name : '/items', validate: validatePathName, }); const overlapCheckResult = checkForPathOverlap(pathName, Object.keys(paths)); if (overlapCheckResult === false) { // The path provided by the user is valid, and doesn't overlap with any other endpoints that they've stood up with API Gateway. isPathValid = true; } else { // The path provided by the user overlaps with another endpoint that they've stood up with API Gateway. // Ask them if they're okay with this. If they are, then we'll consider their provided path to be valid. const higherOrderPath = overlapCheckResult.higherOrderPath; const lowerOrderPath = overlapCheckResult.lowerOrderPath; isPathValid = await prompter.confirmContinue( `The path ${lowerOrderPath} overlaps with ${higherOrderPath}. Users authorized to access ${higherOrderPath} will also have access` + ` to ${lowerOrderPath}. Are you sure you want to continue?`, ); } } while (!isPathValid); const functionType = await prompter.pick<'one', string>('Choose a Lambda source', choices, { initial: choices.indexOf(defaultChoice) }); let path = { name: pathName }; let lambda; do { lambda = await askLambdaSource(context, functionType, pathName, currentPath); } while (!lambda); const permissions = await askPermissions(context, answers, currentPath); path = { ...path, ...lambda, permissions }; paths[pathName] = path; if (currentPath) { break; } addAnotherPath = await prompter.confirmContinue('Do you want to add another path?'); } while (addAnotherPath); const { dependsOn, functionArns } = await findDependsOn(paths); return { paths, dependsOn, resourceName: answers.resourceName, functionArns }; } async function findDependsOn(paths: $TSObject[]) { // go thru all paths and add lambdaFunctions to dependsOn and functionArns uniquely const dependsOn = []; const functionArns = []; for (const path of Object.values(paths)) { if (path.lambdaFunction && !path.lambdaArn) { if (!dependsOn.find(func => func.resourceName === path.lambdaFunction)) { dependsOn.push({ category: 'function', resourceName: path.lambdaFunction, attributes: ['Name', 'Arn'], }); } } if (!functionArns.find(func => func.lambdaFunction === path.lambdaFunction)) { functionArns.push({ lambdaFunction: path.lambdaFunction, lambdaArn: path.lambdaArn, }); } if (path?.permissions?.groups) { const userPoolGroups = Object.keys(path.permissions.groups); if (userPoolGroups.length > 0) { // Get auth resource name const authResourceName = getAuthResourceName(); if (!dependsOn.find(resource => resource.resourceName === authResourceName)) { dependsOn.push({ category: 'auth', resourceName: authResourceName, attributes: ['UserPoolId'], }); } userPoolGroups.forEach(group => { if (!dependsOn.find(resource => resource.attributes[0] === `${group}GroupRole`)) { dependsOn.push({ category: 'auth', resourceName: 'userPoolGroups', attributes: [`${group}GroupRole`], }); } }); } } } return { dependsOn, functionArns }; } function getAuthResourceName(): string { const meta = stateManager.getMeta(); const authResources = (Object.entries(meta?.auth) || []).filter( ([_, resource]: [key: string, resource: $TSObject]) => resource.service === AmplifySupportedService.COGNITO, ); if (authResources.length === 0) { throw new Error('No auth resource found. Add it using amplify add auth'); } const [authResourceName] = authResources[0]; return authResourceName; } function functionsExist() { const meta = stateManager.getMeta(); if (!meta.function) { return false; } const functionResources = meta.function; const lambdaFunctions = []; Object.keys(functionResources).forEach(resourceName => { if (functionResources[resourceName].service === AmplifySupportedService.LAMBDA) { lambdaFunctions.push(resourceName); } }); if (lambdaFunctions.length === 0) { return false; } return true; } async function askLambdaSource(context: $TSContext, functionType: string, path: string, currentPath?: ApigwPath) { switch (functionType) { case 'arn': return askLambdaArn(context, currentPath); case 'projectFunction': return askLambdaFromProject(currentPath); case 'newFunction': return newLambdaFunction(context as $TSAny, path); default: throw new Error('Type not supported'); } } async function newLambdaFunction(context: $TSContext, path: string) { let params = { functionTemplate: { parameters: { path, expressPath: formatCFNPathParamsForExpressJs(path), }, }, }; const resourceName = await context.amplify.invokePluginMethod(context, AmplifyCategories.FUNCTION, undefined, 'add', [ context, 'awscloudformation', AmplifySupportedService.LAMBDA, params, ]); printer.success('Succesfully added the Lambda function locally'); return { lambdaFunction: resourceName }; } async function askLambdaFromProject(currentPath?: ApigwPath) { const meta = stateManager.getMeta(); const lambdaFunctions = []; Object.keys(meta?.function || {}).forEach(resourceName => { if (meta.function[resourceName].service === AmplifySupportedService.LAMBDA) { lambdaFunctions.push(resourceName); } }); const lambdaFunction = await prompter.pick<'one', string>('Choose the Lambda function to invoke by this path', lambdaFunctions, { initial: currentPath ? lambdaFunctions.indexOf(currentPath.lambdaFunction) : 0, }); return { lambdaFunction }; } async function askLambdaArn(context: $TSContext, currentPath?: ApigwPath) { const lambdaFunctions = await context.amplify.executeProviderUtils(context, 'awscloudformation', 'getLambdaFunctions'); const lambdaOptions = lambdaFunctions.map(lambdaFunction => ({ value: lambdaFunction.FunctionArn, name: `${lambdaFunction.FunctionName} (${lambdaFunction.FunctionArn})`, })); if (lambdaOptions.length === 0) { printer.error('You do not have any Lambda functions configured for the selected Region'); return null; } const lambdaCloudOptionQuestion = { type: 'list', name: 'lambdaChoice', message: 'Select a Lambda function', choices: lambdaOptions, default: currentPath && currentPath.lambdaFunction ? `${currentPath.lambdaFunction}` : `${lambdaOptions[0].value}`, }; let lambdaOption; while (!lambdaOption) { try { lambdaOption = await inquirer.prompt([lambdaCloudOptionQuestion]); } catch (err) { printer.error('Select a Lambda Function'); } } const lambdaCloudOptionAnswer = lambdaFunctions.find(lambda => lambda.FunctionArn === lambdaOption.lambdaChoice); return { lambdaArn: lambdaCloudOptionAnswer.FunctionArn, lambdaFunction: lambdaCloudOptionAnswer.FunctionName, }; } export async function migrate(context: $TSContext, projectPath: string, resourceName: string) { const apigwInputState = new ApigwInputState(context, resourceName); if (resourceName === ADMIN_QUERIES_NAME) { const meta = stateManager.getMeta(); const adminQueriesDependsOn = _.get(meta, [AmplifyCategories.API, ADMIN_QUERIES_NAME, 'dependsOn'], undefined); if (!adminQueriesDependsOn) { throw new Error('Failed to migrate Admin Queries API. Could not find expected information in amplify-meta.json.'); } const functionName = adminQueriesDependsOn.filter(dependency => dependency.category === AmplifyCategories.FUNCTION)?.[0]?.resourceName; const adminQueriesProps = { apiName: resourceName, authResourceName: getAuthResourceName(), functionName, dependsOn: adminQueriesDependsOn, }; return apigwInputState.migrateAdminQueries(adminQueriesProps); } return apigwInputState.migrateApigwResource(resourceName); } export function getIAMPolicies(resourceName: string, crudOptions: string[]) { let policy = {}; const actions = []; crudOptions.forEach(crudOption => { switch (crudOption) { case CrudOperation.CREATE: actions.push('apigateway:POST', 'apigateway:PUT'); break; case CrudOperation.UPDATE: actions.push('apigateway:PATCH'); break; case CrudOperation.READ: actions.push('apigateway:GET', 'apigateway:HEAD', 'apigateway:OPTIONS'); break; case CrudOperation.DELETE: actions.push('apigateway:DELETE'); break; default: printer.info(`${crudOption} not supported`); } }); policy = { Effect: 'Allow', Action: actions, Resource: [ { 'Fn::Join': [ '', [ 'arn:aws:apigateway:', { Ref: 'AWS::Region', }, '::/restapis/', { Ref: `${category}${resourceName}ApiName`, }, '/*', ], ], }, ], }; const attributes = ['ApiName', 'ApiId']; return { policy, attributes }; } export const openConsole = async (context?: $TSContext) => { const amplifyMeta = stateManager.getMeta(); const categoryAmplifyMeta = amplifyMeta[category]; const { Region } = amplifyMeta.providers.awscloudformation; const restApis = Object.keys(categoryAmplifyMeta).filter(resourceName => { const resource = categoryAmplifyMeta[resourceName]; return ( resource.output && (resource.service === serviceName || (resource.service === elasticContainerServiceName && resource.apiType === 'REST')) ); }); if (restApis) { let url; const selectedApi = await prompter.pick<'one', string>('Select the API', restApis); const selectedResource = categoryAmplifyMeta[selectedApi]; if (selectedResource.service === serviceName) { const { output: { ApiId }, } = selectedResource; url = `https://${Region}.console.aws.amazon.com/apigateway/home?region=${Region}#/apis/${ApiId}/resources/`; } else { // Elastic Container API const { output: { PipelineName, ServiceName, ClusterName }, } = selectedResource; const codePipeline = 'CodePipeline'; const elasticContainer = 'ElasticContainer'; const selectedConsole = await prompter.pick<'one', string>('Which console do you want to open?', [ { name: 'Elastic Container Service (Deployed container status)', value: elasticContainer, }, { name: 'CodePipeline (Container build status)', value: codePipeline, }, ]); if (selectedConsole === elasticContainer) { url = `https://console.aws.amazon.com/ecs/home?region=${Region}#/clusters/${ClusterName}/services/${ServiceName}/details`; } else if (selectedConsole === codePipeline) { url = `https://${Region}.console.aws.amazon.com/codesuite/codepipeline/pipelines/${PipelineName}/view`; } else { printer.error('Option not available'); return; } } open(url, { wait: false }); } else { printer.error('There are no REST APIs pushed to the cloud'); } };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Represents an OSPolicyAssignment resource. * * ## Example Usage * ### Fixed_os_policy_assignment * An example of an osconfig os policy assignment with fixed rollout disruption budget * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const primary = new gcp.osconfig.OsPolicyAssignment("primary", { * description: "A test os policy assignment", * instanceFilter: { * all: false, * exclusionLabels: [{ * labels: { * "label-two": "value-two", * }, * }], * inclusionLabels: [{ * labels: { * "label-one": "value-one", * }, * }], * inventories: [{ * osShortName: "centos", * osVersion: "8.*", * }], * }, * location: "us-west1-a", * osPolicies: [{ * allowNoResourceGroupMatch: false, * description: "A test os policy", * id: "policy", * mode: "VALIDATION", * resourceGroups: [ * { * inventoryFilters: [{ * osShortName: "centos", * osVersion: "8.*", * }], * resources: [ * { * id: "apt", * pkg: { * apt: { * name: "bazel", * }, * desiredState: "INSTALLED", * }, * }, * { * id: "deb1", * pkg: { * deb: { * source: { * localPath: "$HOME/package.deb", * }, * }, * desiredState: "INSTALLED", * }, * }, * { * id: "deb2", * pkg: { * deb: { * pullDeps: true, * source: { * allowInsecure: true, * remote: { * sha256Checksum: "3bbfd1043cd7afdb78cf9afec36c0c5370d2fea98166537b4e67f3816f256025", * uri: "ftp.us.debian.org/debian/package.deb", * }, * }, * }, * desiredState: "INSTALLED", * }, * }, * { * id: "deb3", * pkg: { * deb: { * pullDeps: true, * source: { * gcs: { * bucket: "test-bucket", * generation: 1, * object: "test-object", * }, * }, * }, * desiredState: "INSTALLED", * }, * }, * { * id: "yum", * pkg: { * desiredState: "INSTALLED", * yum: { * name: "gstreamer-plugins-base-devel.x86_64", * }, * }, * }, * { * id: "zypper", * pkg: { * desiredState: "INSTALLED", * zypper: { * name: "gcc", * }, * }, * }, * { * id: "rpm1", * pkg: { * desiredState: "INSTALLED", * rpm: { * pullDeps: true, * source: { * localPath: "$HOME/package.rpm", * }, * }, * }, * }, * { * id: "rpm2", * pkg: { * desiredState: "INSTALLED", * rpm: { * source: { * allowInsecure: true, * remote: { * sha256Checksum: "3bbfd1043cd7afdb78cf9afec36c0c5370d2fea98166537b4e67f3816f256025", * uri: "https://mirror.jaleco.com/centos/8.3.2011/BaseOS/x86_64/os/Packages/efi-filesystem-3-2.el8.noarch.rpm", * }, * }, * }, * }, * }, * { * id: "rpm3", * pkg: { * desiredState: "INSTALLED", * rpm: { * source: { * gcs: { * bucket: "test-bucket", * generation: 1, * object: "test-object", * }, * }, * }, * }, * }, * ], * }, * { * resources: [ * { * id: "apt-to-deb", * pkg: { * apt: { * name: "bazel", * }, * desiredState: "INSTALLED", * }, * }, * { * id: "deb-local-path-to-gcs", * pkg: { * deb: { * source: { * localPath: "$HOME/package.deb", * }, * }, * desiredState: "INSTALLED", * }, * }, * { * id: "googet", * pkg: { * desiredState: "INSTALLED", * googet: { * name: "gcc", * }, * }, * }, * { * id: "msi1", * pkg: { * desiredState: "INSTALLED", * msi: { * properties: ["REBOOT=ReallySuppress"], * source: { * localPath: "$HOME/package.msi", * }, * }, * }, * }, * { * id: "msi2", * pkg: { * desiredState: "INSTALLED", * msi: { * source: { * allowInsecure: true, * remote: { * sha256Checksum: "3bbfd1043cd7afdb78cf9afec36c0c5370d2fea98166537b4e67f3816f256025", * uri: "https://remote.uri.com/package.msi", * }, * }, * }, * }, * }, * { * id: "msi3", * pkg: { * desiredState: "INSTALLED", * msi: { * source: { * gcs: { * bucket: "test-bucket", * generation: 1, * object: "test-object", * }, * }, * }, * }, * }, * ], * }, * ], * }], * project: "my-project-name", * rollout: { * disruptionBudget: { * fixed: 1, * }, * minWaitDuration: "3.5s", * }, * }); * ``` * ### Percent_os_policy_assignment * An example of an osconfig os policy assignment with percent rollout disruption budget * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const primary = new gcp.osconfig.OsPolicyAssignment("primary", { * description: "A test os policy assignment", * instanceFilter: { * all: true, * }, * location: "us-west1-a", * osPolicies: [{ * id: "policy", * mode: "VALIDATION", * resourceGroups: [ * { * resources: [ * { * id: "apt-to-yum", * repository: { * apt: { * archiveType: "DEB", * components: ["doc"], * distribution: "debian", * gpgKey: ".gnupg/pubring.kbx", * uri: "https://atl.mirrors.clouvider.net/debian", * }, * }, * }, * { * id: "yum", * repository: { * yum: { * baseUrl: "http://centos.s.uw.edu/centos/", * displayName: "yum", * gpgKeys: ["RPM-GPG-KEY-CentOS-7"], * id: "yum", * }, * }, * }, * { * id: "zypper", * repository: { * zypper: { * baseUrl: "http://mirror.dal10.us.leaseweb.net/opensuse", * displayName: "zypper", * gpgKeys: ["sample-key-uri"], * id: "zypper", * }, * }, * }, * { * id: "goo", * repository: { * goo: { * name: "goo", * url: "https://foo.com/googet/bar", * }, * }, * }, * { * exec: { * enforce: { * args: ["arg1"], * file: { * allowInsecure: true, * remote: { * sha256Checksum: "c7938fed83afdccbb0e86a2a2e4cad7d5035012ca3214b4a61268393635c3063", * uri: "https://www.example.com/script.sh", * }, * }, * interpreter: "SHELL", * outputFilePath: "$HOME/out", * }, * validate: { * args: ["arg1"], * file: { * localPath: "$HOME/script.sh", * }, * interpreter: "SHELL", * outputFilePath: "$HOME/out", * }, * }, * id: "exec1", * }, * { * exec: { * enforce: { * args: ["arg1"], * file: { * localPath: "$HOME/script.sh", * }, * interpreter: "SHELL", * outputFilePath: "$HOME/out", * }, * validate: { * args: ["arg1"], * file: { * allowInsecure: true, * remote: { * sha256Checksum: "c7938fed83afdccbb0e86a2a2e4cad7d5035012ca3214b4a61268393635c3063", * uri: "https://www.example.com/script.sh", * }, * }, * interpreter: "SHELL", * outputFilePath: "$HOME/out", * }, * }, * id: "exec2", * }, * { * exec: { * enforce: { * interpreter: "SHELL", * outputFilePath: "$HOME/out", * script: "pwd", * }, * validate: { * file: { * allowInsecure: true, * gcs: { * bucket: "test-bucket", * generation: 1, * object: "test-object", * }, * }, * interpreter: "SHELL", * outputFilePath: "$HOME/out", * }, * }, * id: "exec3", * }, * { * exec: { * enforce: { * file: { * allowInsecure: true, * gcs: { * bucket: "test-bucket", * generation: 1, * object: "test-object", * }, * }, * interpreter: "SHELL", * outputFilePath: "$HOME/out", * }, * validate: { * interpreter: "SHELL", * outputFilePath: "$HOME/out", * script: "pwd", * }, * }, * id: "exec4", * }, * { * file: { * file: { * localPath: "$HOME/file", * }, * path: "$HOME/file", * state: "PRESENT", * }, * id: "file1", * }, * ], * }, * { * resources: [ * { * file: { * file: { * allowInsecure: true, * remote: { * sha256Checksum: "c7938fed83afdccbb0e86a2a2e4cad7d5035012ca3214b4a61268393635c3063", * uri: "https://www.example.com/file", * }, * }, * path: "$HOME/file", * state: "PRESENT", * }, * id: "file2", * }, * { * file: { * file: { * gcs: { * bucket: "test-bucket", * generation: 1, * object: "test-object", * }, * }, * path: "$HOME/file", * state: "PRESENT", * }, * id: "file3", * }, * { * file: { * content: "sample-content", * path: "$HOME/file", * state: "PRESENT", * }, * id: "file4", * }, * ], * }, * ], * }], * project: "my-project-name", * rollout: { * disruptionBudget: { * percent: 1, * }, * minWaitDuration: "3.5s", * }, * }); * ``` * * ## Import * * OSPolicyAssignment can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:osconfig/osPolicyAssignment:OsPolicyAssignment default projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}} * ``` * * ```sh * $ pulumi import gcp:osconfig/osPolicyAssignment:OsPolicyAssignment default {{project}}/{{location}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:osconfig/osPolicyAssignment:OsPolicyAssignment default {{location}}/{{name}} * ``` */ export class OsPolicyAssignment extends pulumi.CustomResource { /** * Get an existing OsPolicyAssignment 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?: OsPolicyAssignmentState, opts?: pulumi.CustomResourceOptions): OsPolicyAssignment { return new OsPolicyAssignment(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:osconfig/osPolicyAssignment:OsPolicyAssignment'; /** * Returns true if the given object is an instance of OsPolicyAssignment. 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 OsPolicyAssignment { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === OsPolicyAssignment.__pulumiType; } /** * Output only. Indicates that this revision has been successfully rolled out in this zone and new VMs will be assigned OS * policies from this revision. For a given OS policy assignment, there is only one revision with a value of `true` for * this field. */ public /*out*/ readonly baseline!: pulumi.Output<boolean>; /** * Output only. Indicates that this revision deletes the OS policy assignment. */ public /*out*/ readonly deleted!: pulumi.Output<boolean>; /** * OS policy assignment description. Length of the description is limited to 1024 characters. */ public readonly description!: pulumi.Output<string | undefined>; /** * The etag for this OS policy assignment. If this is provided on update, it must match the server's etag. */ public /*out*/ readonly etag!: pulumi.Output<string>; /** * Required. Filter to select VMs. */ public readonly instanceFilter!: pulumi.Output<outputs.osconfig.OsPolicyAssignmentInstanceFilter>; /** * The location for the resource */ public readonly location!: pulumi.Output<string>; /** * Required. The name of the repository. */ public readonly name!: pulumi.Output<string>; /** * Required. List of OS policies to be applied to the VMs. */ public readonly osPolicies!: pulumi.Output<outputs.osconfig.OsPolicyAssignmentOsPolicy[]>; /** * The project for the resource */ public readonly project!: pulumi.Output<string>; /** * Output only. Indicates that reconciliation is in progress for the revision. This value is `true` when the * `rollout_state` is one of: * IN_PROGRESS * CANCELLING */ public /*out*/ readonly reconciling!: pulumi.Output<boolean>; /** * Output only. The timestamp that the revision was created. */ public /*out*/ readonly revisionCreateTime!: pulumi.Output<string>; /** * Output only. The assignment revision ID A new revision is committed whenever a rollout is triggered for a OS policy * assignment */ public /*out*/ readonly revisionId!: pulumi.Output<string>; /** * Required. Rollout to deploy the OS policy assignment. A rollout is triggered in the following situations: 1) OSPolicyAssignment is created. 2) OSPolicyAssignment is updated and the update contains changes to one of the following fields: - instanceFilter - osPolicies 3) OSPolicyAssignment is deleted. */ public readonly rollout!: pulumi.Output<outputs.osconfig.OsPolicyAssignmentRollout>; /** * Output only. OS policy assignment rollout state Possible values: ROLLOUT_STATE_UNSPECIFIED, IN_PROGRESS, CANCELLING, * CANCELLED, SUCCEEDED */ public /*out*/ readonly rolloutState!: pulumi.Output<string>; /** * Output only. Server generated unique id for the OS policy assignment resource. */ public /*out*/ readonly uid!: pulumi.Output<string>; /** * Create a OsPolicyAssignment 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: OsPolicyAssignmentArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: OsPolicyAssignmentArgs | OsPolicyAssignmentState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as OsPolicyAssignmentState | undefined; inputs["baseline"] = state ? state.baseline : undefined; inputs["deleted"] = state ? state.deleted : undefined; inputs["description"] = state ? state.description : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["instanceFilter"] = state ? state.instanceFilter : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["osPolicies"] = state ? state.osPolicies : undefined; inputs["project"] = state ? state.project : undefined; inputs["reconciling"] = state ? state.reconciling : undefined; inputs["revisionCreateTime"] = state ? state.revisionCreateTime : undefined; inputs["revisionId"] = state ? state.revisionId : undefined; inputs["rollout"] = state ? state.rollout : undefined; inputs["rolloutState"] = state ? state.rolloutState : undefined; inputs["uid"] = state ? state.uid : undefined; } else { const args = argsOrState as OsPolicyAssignmentArgs | undefined; if ((!args || args.instanceFilter === undefined) && !opts.urn) { throw new Error("Missing required property 'instanceFilter'"); } if ((!args || args.location === undefined) && !opts.urn) { throw new Error("Missing required property 'location'"); } if ((!args || args.osPolicies === undefined) && !opts.urn) { throw new Error("Missing required property 'osPolicies'"); } if ((!args || args.rollout === undefined) && !opts.urn) { throw new Error("Missing required property 'rollout'"); } inputs["description"] = args ? args.description : undefined; inputs["instanceFilter"] = args ? args.instanceFilter : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["osPolicies"] = args ? args.osPolicies : undefined; inputs["project"] = args ? args.project : undefined; inputs["rollout"] = args ? args.rollout : undefined; inputs["baseline"] = undefined /*out*/; inputs["deleted"] = undefined /*out*/; inputs["etag"] = undefined /*out*/; inputs["reconciling"] = undefined /*out*/; inputs["revisionCreateTime"] = undefined /*out*/; inputs["revisionId"] = undefined /*out*/; inputs["rolloutState"] = undefined /*out*/; inputs["uid"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(OsPolicyAssignment.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering OsPolicyAssignment resources. */ export interface OsPolicyAssignmentState { /** * Output only. Indicates that this revision has been successfully rolled out in this zone and new VMs will be assigned OS * policies from this revision. For a given OS policy assignment, there is only one revision with a value of `true` for * this field. */ baseline?: pulumi.Input<boolean>; /** * Output only. Indicates that this revision deletes the OS policy assignment. */ deleted?: pulumi.Input<boolean>; /** * OS policy assignment description. Length of the description is limited to 1024 characters. */ description?: pulumi.Input<string>; /** * The etag for this OS policy assignment. If this is provided on update, it must match the server's etag. */ etag?: pulumi.Input<string>; /** * Required. Filter to select VMs. */ instanceFilter?: pulumi.Input<inputs.osconfig.OsPolicyAssignmentInstanceFilter>; /** * The location for the resource */ location?: pulumi.Input<string>; /** * Required. The name of the repository. */ name?: pulumi.Input<string>; /** * Required. List of OS policies to be applied to the VMs. */ osPolicies?: pulumi.Input<pulumi.Input<inputs.osconfig.OsPolicyAssignmentOsPolicy>[]>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Output only. Indicates that reconciliation is in progress for the revision. This value is `true` when the * `rollout_state` is one of: * IN_PROGRESS * CANCELLING */ reconciling?: pulumi.Input<boolean>; /** * Output only. The timestamp that the revision was created. */ revisionCreateTime?: pulumi.Input<string>; /** * Output only. The assignment revision ID A new revision is committed whenever a rollout is triggered for a OS policy * assignment */ revisionId?: pulumi.Input<string>; /** * Required. Rollout to deploy the OS policy assignment. A rollout is triggered in the following situations: 1) OSPolicyAssignment is created. 2) OSPolicyAssignment is updated and the update contains changes to one of the following fields: - instanceFilter - osPolicies 3) OSPolicyAssignment is deleted. */ rollout?: pulumi.Input<inputs.osconfig.OsPolicyAssignmentRollout>; /** * Output only. OS policy assignment rollout state Possible values: ROLLOUT_STATE_UNSPECIFIED, IN_PROGRESS, CANCELLING, * CANCELLED, SUCCEEDED */ rolloutState?: pulumi.Input<string>; /** * Output only. Server generated unique id for the OS policy assignment resource. */ uid?: pulumi.Input<string>; } /** * The set of arguments for constructing a OsPolicyAssignment resource. */ export interface OsPolicyAssignmentArgs { /** * OS policy assignment description. Length of the description is limited to 1024 characters. */ description?: pulumi.Input<string>; /** * Required. Filter to select VMs. */ instanceFilter: pulumi.Input<inputs.osconfig.OsPolicyAssignmentInstanceFilter>; /** * The location for the resource */ location: pulumi.Input<string>; /** * Required. The name of the repository. */ name?: pulumi.Input<string>; /** * Required. List of OS policies to be applied to the VMs. */ osPolicies: pulumi.Input<pulumi.Input<inputs.osconfig.OsPolicyAssignmentOsPolicy>[]>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Required. Rollout to deploy the OS policy assignment. A rollout is triggered in the following situations: 1) OSPolicyAssignment is created. 2) OSPolicyAssignment is updated and the update contains changes to one of the following fields: - instanceFilter - osPolicies 3) OSPolicyAssignment is deleted. */ rollout: pulumi.Input<inputs.osconfig.OsPolicyAssignmentRollout>; }
the_stack
// Vendor import { GL_ALIASED_LINE_WIDTH_RANGE, GL_ALIASED_POINT_SIZE_RANGE, GL_ALPHA_BITS, GL_BLUE_BITS, GL_DEPTH_BITS, GL_FRAGMENT_SHADER, GL_GREEN_BITS, GL_HIGH_FLOAT, GL_LOW_FLOAT, GL_MAX_3D_TEXTURE_SIZE, GL_MAX_ARRAY_TEXTURE_LAYERS, GL_MAX_CLIENT_WAIT_TIMEOUT_WEBGL, GL_MAX_COLOR_ATTACHMENTS, GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS, GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, GL_MAX_COMBINED_UNIFORM_BLOCKS, GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS, GL_MAX_CUBE_MAP_TEXTURE_SIZE, GL_MAX_DRAW_BUFFERS, GL_MAX_ELEMENT_INDEX, GL_MAX_ELEMENTS_INDICES, GL_MAX_ELEMENTS_VERTICES, GL_MAX_FRAGMENT_INPUT_COMPONENTS, GL_MAX_FRAGMENT_UNIFORM_BLOCKS, GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, GL_MAX_FRAGMENT_UNIFORM_VECTORS, GL_MAX_PROGRAM_TEXEL_OFFSET, GL_MAX_RENDERBUFFER_SIZE, GL_MAX_SAMPLES, GL_MAX_SERVER_WAIT_TIMEOUT, GL_MAX_TEXTURE_IMAGE_UNITS, GL_MAX_TEXTURE_LOD_BIAS, GL_MAX_TEXTURE_SIZE, GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, GL_MAX_UNIFORM_BLOCK_SIZE, GL_MAX_UNIFORM_BUFFER_BINDINGS, GL_MAX_VARYING_COMPONENTS, GL_MAX_VARYING_VECTORS, GL_MAX_VERTEX_ATTRIBS, GL_MAX_VERTEX_OUTPUT_COMPONENTS, GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, GL_MAX_VERTEX_UNIFORM_BLOCKS, GL_MAX_VERTEX_UNIFORM_COMPONENTS, GL_MAX_VERTEX_UNIFORM_VECTORS, GL_MAX_VIEWPORT_DIMS, GL_MEDIUM_FLOAT, GL_MIN_PROGRAM_TEXEL_OFFSET, GL_RED_BITS, GL_RENDERER, GL_SHADING_LANGUAGE_VERSION, GL_STENCIL_BITS, GL_STENCIL_TEST, GL_SUBPIXEL_BITS, GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, GL_VENDOR, GL_VERSION, GL_VERTEX_SHADER, } from 'webgl-constants'; // Features import { getExtension, getParameter, getShaderPrecisionFormat, } from './getWebGLFeatures'; /** * Collect and structure all major device and browser specific WebGL2 features */ // TODO: add proper type definition export default ((): any => { const attributes = { stencil: true, }; const canvas = document.createElement('canvas'); const gl = canvas.getContext('webgl2', attributes); if (!gl || !(gl instanceof WebGL2RenderingContext)) { return false; } const glExtensionDebugRendererInfo = getExtension( gl, 'WEBGL_debug_renderer_info' ); // Enable features gl.enable(GL_STENCIL_TEST); // Enable extensions const glAnisotropicExtension = getExtension(gl, 'EXT_texture_filter_anisotropic') || getExtension(gl, 'WEBKIT_EXT_texture_filter_anisotropic') || getExtension(gl, 'MOZ_EXT_texture_filter_anisotropic'); const features = { // Base base: { renderer: getParameter(gl, GL_RENDERER), rendererUnmasked: glExtensionDebugRendererInfo && getParameter(gl, glExtensionDebugRendererInfo.UNMASKED_RENDERER_WEBGL), shaderVersion: getParameter(gl, GL_SHADING_LANGUAGE_VERSION), vendor: getParameter(gl, GL_VENDOR), vendorUnmasked: glExtensionDebugRendererInfo && getParameter(gl, glExtensionDebugRendererInfo.UNMASKED_VENDOR_WEBGL), version: getParameter(gl, GL_VERSION), }, // General general: { aliasedLineWidthRange: getParameter( gl, GL_ALIASED_LINE_WIDTH_RANGE ).toString(), aliasedPointSizeRange: getParameter( gl, GL_ALIASED_POINT_SIZE_RANGE ).toString(), alphaBits: getParameter(gl, GL_ALPHA_BITS), // @ts-ignore gl.getContextAttributes could return null antialias: !!gl.getContextAttributes().antialias, blueBits: getParameter(gl, GL_BLUE_BITS), depthBits: getParameter(gl, GL_DEPTH_BITS), greenBits: getParameter(gl, GL_GREEN_BITS), maxCombinedTextureImageUnits: getParameter( gl, GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS ), maxCubeMapTextureSize: getParameter(gl, GL_MAX_CUBE_MAP_TEXTURE_SIZE), maxFragmentUniformVectors: getParameter( gl, GL_MAX_FRAGMENT_UNIFORM_VECTORS ), maxRenderBufferSize: getParameter(gl, GL_MAX_RENDERBUFFER_SIZE), maxTextureImageUnits: getParameter(gl, GL_MAX_TEXTURE_IMAGE_UNITS), maxTextureSize: getParameter(gl, GL_MAX_TEXTURE_SIZE), maxVaryingVectors: getParameter(gl, GL_MAX_VARYING_VECTORS), maxVertexAttributes: getParameter(gl, GL_MAX_VERTEX_ATTRIBS), maxVertexTextureImageUnits: getParameter( gl, GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS ), maxVertexUniformVectors: getParameter(gl, GL_MAX_VERTEX_UNIFORM_VECTORS), maxViewportDimensions: getParameter(gl, GL_MAX_VIEWPORT_DIMS).toString(), precision: { fragmentShaderHighPrecision: [ // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_HIGH_FLOAT) .rangeMin, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_HIGH_FLOAT) .rangeMax, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_HIGH_FLOAT) .precision, ].toString(), fragmentShaderLowPrecision: [ // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_LOW_FLOAT) .rangeMin, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_LOW_FLOAT) .rangeMax, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_LOW_FLOAT) .precision, ].toString(), fragmentShaderMediumPrecision: [ // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_MEDIUM_FLOAT) .rangeMin, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_MEDIUM_FLOAT) .rangeMax, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_FRAGMENT_SHADER, GL_MEDIUM_FLOAT) .precision, ].toString(), vertexShaderHighPrecision: [ // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_HIGH_FLOAT) .rangeMin, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_HIGH_FLOAT) .rangeMax, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_HIGH_FLOAT) .precision, ].toString(), vertexShaderLowPrecision: [ // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_LOW_FLOAT).rangeMin, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_LOW_FLOAT).rangeMax, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_LOW_FLOAT) .precision, ].toString(), vertexShaderMediumPrecision: [ // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_MEDIUM_FLOAT) .rangeMin, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_MEDIUM_FLOAT) .rangeMax, // @ts-ignore gl.getShaderPrecisionFormat could return null getShaderPrecisionFormat(gl, GL_VERTEX_SHADER, GL_MEDIUM_FLOAT) .precision, ].toString(), }, redBits: getParameter(gl, GL_RED_BITS), stencilBits: getParameter(gl, GL_STENCIL_BITS), subPixelBits: getParameter(gl, GL_SUBPIXEL_BITS), }, // Extensions extensions: { maxAnisotropy: glAnisotropicExtension ? getParameter( gl, glAnisotropicExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0, supportedExtensions: gl.getSupportedExtensions(), // Compressed texture extensions compressedTextureASTCExtension: getExtension(gl, 'WEBGL_compressed_texture_astc') || null, compressedTextureATCExtension: getExtension(gl, 'WEBGL_compressed_texture_atc') || null, compressedTextureETC1Extension: getExtension(gl, 'WEBGL_compressed_texture_etc1') || null, compressedTextureETCExtension: getExtension(gl, 'WEBGL_compressed_texture_etc') || null, compressedTexturePVRTCExtension: getExtension(gl, 'WEBGL_compressed_texture_pvrtc') || getExtension(gl, 'WEBKIT_WEBGL_compressed_texture_pvrtc') || null, compressedTextureS3TCExtension: getExtension(gl, 'WEBGL_compressed_texture_s3tc') || null, compressedTextureS3TCSRGBExtension: getExtension(gl, 'WEBGL_compressed_texture_s3tc_srgb') || null, }, // WebGL2 specific specific: { max3DTextureSize: getParameter(gl, GL_MAX_3D_TEXTURE_SIZE), maxArrayTextureLayers: getParameter(gl, GL_MAX_ARRAY_TEXTURE_LAYERS), maxClientWaitTimeout: getParameter(gl, GL_MAX_CLIENT_WAIT_TIMEOUT_WEBGL), maxColorAttachments: getParameter(gl, GL_MAX_COLOR_ATTACHMENTS), maxCombinedFragmentUniformComponents: getParameter( gl, GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS ), maxCombinedUniformBlocks: getParameter( gl, GL_MAX_COMBINED_UNIFORM_BLOCKS ), maxCombinedVertexUniformComponents: getParameter( gl, GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS ), maxDrawBuffers: getParameter(gl, GL_MAX_DRAW_BUFFERS), maxElementIndex: getParameter(gl, GL_MAX_ELEMENT_INDEX), maxElementsIndices: getParameter(gl, GL_MAX_ELEMENTS_INDICES), maxElementsVertices: getParameter(gl, GL_MAX_ELEMENTS_VERTICES), maxFragmentInputComponents: getParameter( gl, GL_MAX_FRAGMENT_INPUT_COMPONENTS ), maxFragmentUniformBlocks: getParameter( gl, GL_MAX_FRAGMENT_UNIFORM_BLOCKS ), maxFragmentUniformComponents: getParameter( gl, GL_MAX_FRAGMENT_UNIFORM_COMPONENTS ), maxProgramTexelOffset: getParameter(gl, GL_MAX_PROGRAM_TEXEL_OFFSET), maxSamples: getParameter(gl, GL_MAX_SAMPLES), maxServerWaitTimeout: getParameter(gl, GL_MAX_SERVER_WAIT_TIMEOUT), maxTextureLODBias: getParameter(gl, GL_MAX_TEXTURE_LOD_BIAS), maxTransformFeedbackInterleavedComponents: getParameter( gl, GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS ), maxTransformFeedbackSeparateAttribs: getParameter( gl, GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS ), maxTransformFeedbackSeparateComponents: getParameter( gl, GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS ), maxUniformBlockSize: getParameter(gl, GL_MAX_UNIFORM_BLOCK_SIZE), maxUniformBufferBindings: getParameter( gl, GL_MAX_UNIFORM_BUFFER_BINDINGS ), maxVaryingComponents: getParameter(gl, GL_MAX_VARYING_COMPONENTS), maxVertexOutputComponents: getParameter( gl, GL_MAX_VERTEX_OUTPUT_COMPONENTS ), maxVertexUniformBlocks: getParameter(gl, GL_MAX_VERTEX_UNIFORM_BLOCKS), maxVertexUniformComponents: getParameter( gl, GL_MAX_VERTEX_UNIFORM_COMPONENTS ), minProgramTexelOffset: getParameter(gl, GL_MIN_PROGRAM_TEXEL_OFFSET), uniformBufferOffsetAlignment: getParameter( gl, GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT ), }, }; return features; })();
the_stack
import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import ArtifactsIcon from '@material-ui/icons/BubbleChart'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ExecutionsIcon from '@material-ui/icons/PlayArrow'; import * as React from 'react'; import {RoutePage, RoutePrefix} from '../components/Router'; import {RouterProps} from 'react-router'; import {Link} from 'react-router-dom'; import {classes, stylesheet} from 'typestyle'; import {commonCss, fontsize} from '../Css'; import {LocalStorage, LocalStorageKey} from '../lib/LocalStorage'; import {logger} from '../lib/Utils'; export interface BuildInfo { apiServerCommitHash?: string; apiServerReady?: boolean; buildDate?: string; frontendCommitHash?: string; } const v1beta1Prefix = 'apis/v1beta1'; async function getBuildInfo(): Promise<BuildInfo> { return await _fetchAndParse<BuildInfo>('/healthz', v1beta1Prefix); } async function _fetchAndParse<T>( path: string, apisPrefix?: string, query?: string, init?: RequestInit, ): Promise<T> { const responseText = await _fetch(path, apisPrefix, query, init); try { return JSON.parse(responseText) as T; } catch (err) { throw new Error( `Error parsing response for path: ${path}\n\n` + `Response was: ${responseText}\n\nError was: ${JSON.stringify(err)}`, ); } } async function _fetch( path: string, apisPrefix?: string, query?: string, init?: RequestInit, ): Promise<string> { init = Object.assign(init || {}, { credentials: 'same-origin' }); const response = await fetch((apisPrefix || '') + path + (query ? '?' + query : ''), init); const responseText = await response.text(); if (response.ok) { return responseText; } else { logger.error( `Response for path: ${path} was not 'ok'\n\nResponse was: ${responseText}`, ); throw new Error(responseText); } } export const sideNavColors = { bg: '#f8fafb', fgActive: '#0d6de7', fgActiveInvisible: 'rgb(227, 233, 237, 0)', fgDefault: '#9aa0a6', hover: '#f1f3f4', separator: '#bdc1c6', sideNavBorder: '#e8eaed', }; const COLLAPSED_SIDE_NAV_SIZE = 72; const EXPANDED_SIDE_NAV_SIZE = 220; export const css = stylesheet({ active: { color: sideNavColors.fgActive + ' !important', }, button: { $nest: { '&::hover': { backgroundColor: sideNavColors.hover, }, }, borderRadius: 0, color: sideNavColors.fgDefault, display: 'block', fontSize: fontsize.medium, fontWeight: 'bold', height: 44, marginBottom: 16, maxWidth: EXPANDED_SIDE_NAV_SIZE, overflow: 'hidden', padding: '12px 10px 10px 26px', textAlign: 'left', textTransform: 'none', transition: 'max-width 0.3s', whiteSpace: 'nowrap', width: EXPANDED_SIDE_NAV_SIZE, }, chevron: { color: sideNavColors.fgDefault, marginLeft: 16, padding: 6, transition: 'transform 0.3s', }, collapsedButton: { maxWidth: COLLAPSED_SIDE_NAV_SIZE, minWidth: COLLAPSED_SIDE_NAV_SIZE, padding: '12px 10px 10px 26px', }, collapsedChevron: { transform: 'rotate(180deg)', }, collapsedExternalLabel: { // Hide text when collapsing, but do it with a transition of both height and // opacity height: 0, opacity: 0, }, collapsedLabel: { // Hide text when collapsing, but do it with a transition opacity: 0, }, collapsedRoot: { width: `${COLLAPSED_SIDE_NAV_SIZE}px !important`, }, collapsedSeparator: { margin: '20px !important', }, envMetadata: { color: sideNavColors.fgDefault, marginBottom: 16, marginLeft: 30, }, icon: { height: 20, width: 20, }, iconImage: { opacity: 0.6, // Images are too colorful there by default, reduce their color. }, indicator: { borderBottom: '3px solid transparent', borderLeft: `3px solid ${sideNavColors.fgActive}`, borderTop: '3px solid transparent', height: 38, left: 0, position: 'absolute', zIndex: 1, }, indicatorHidden: { opacity: 0, }, infoHidden: { opacity: 0, transition: 'opacity 0s', transitionDelay: '0s', }, infoVisible: { opacity: 'initial', transition: 'opacity 0.2s', transitionDelay: '0.3s', }, label: { fontSize: fontsize.base, letterSpacing: 0.25, marginLeft: 20, transition: 'opacity 0.3s', verticalAlign: 'super', }, link: { color: '#77abda', }, openInNewTabIcon: { height: 12, marginBottom: 8, marginLeft: 5, width: 12, }, root: { background: sideNavColors.bg, borderRight: `1px ${sideNavColors.sideNavBorder} solid`, paddingTop: 15, transition: 'width 0.3s', width: EXPANDED_SIDE_NAV_SIZE, }, separator: { border: '0px none transparent', borderTop: `1px solid ${sideNavColors.separator}`, margin: 20, }, }); interface DisplayBuildInfo { commitHash: string; commitUrl: string; date: string; } interface SideNavProps extends RouterProps { page: string; } interface SideNavState { displayBuildInfo?: DisplayBuildInfo; collapsed: boolean; jupyterHubAvailable: boolean; manualCollapseState: boolean; } export class SideNav extends React.Component<SideNavProps, SideNavState> { private _isMounted = true; private readonly _AUTO_COLLAPSE_WIDTH = 800; constructor(props: any) { super(props); const collapsed = LocalStorage.isNavbarCollapsed(); this.state = { collapsed, // Set jupyterHubAvailable to false so UI don't show Jupyter Hub link jupyterHubAvailable: false, manualCollapseState: LocalStorage.hasKey(LocalStorageKey.navbarCollapsed), }; } public async componentDidMount(): Promise<void> { window.addEventListener('resize', this._maybeResize.bind(this)); this._maybeResize(); async function fetchBuildInfo() { const buildInfo = await getBuildInfo(); const commitHash = buildInfo.apiServerCommitHash || buildInfo.frontendCommitHash || ''; return { commitHash: commitHash ? commitHash.substring(0, 7) : 'unknown', commitUrl: 'https://www.github.com/kubeflow/pipelines' + (commitHash ? `/commit/${commitHash}` : ''), date: buildInfo.buildDate ? new Date(buildInfo.buildDate).toLocaleDateString('en-US') : 'unknown', }; } const displayBuildInfo = await fetchBuildInfo().catch(err => { logger.error('Failed to retrieve build info', err); return undefined; }); this.setStateSafe({ displayBuildInfo }); } public componentWillUnmount(): void { this._isMounted = false; } public render(): JSX.Element { const page = this.props.page; const { collapsed, displayBuildInfo } = this.state; return ( <div id='sideNav' className={classes( css.root, commonCss.flexColumn, commonCss.noShrink, collapsed && css.collapsedRoot, )} > <div style={{ flexGrow: 1 }}> <div className={classes( css.indicator, !this._highlightArtifactsButton(page) && css.indicatorHidden, )} /> <Tooltip title={'Artifacts List'} enterDelay={300} placement={'right-start'} disableFocusListener={!collapsed} disableHoverListener={!collapsed} disableTouchListener={!collapsed} > <Link id='artifactsBtn' to={RoutePage.ARTIFACTS} className={commonCss.unstyled}> <Button className={classes( css.button, this._highlightArtifactsButton(page) && css.active, collapsed && css.collapsedButton, )} > <ArtifactsIcon /> <span className={classes(collapsed && css.collapsedLabel, css.label)}> Artifacts </span> </Button> </Link> </Tooltip> <div className={classes( css.indicator, !this._highlightExecutionsButton(page) && css.indicatorHidden, )} /> <Tooltip title={'Executions List'} enterDelay={300} placement={'right-start'} disableFocusListener={!collapsed} disableHoverListener={!collapsed} disableTouchListener={!collapsed} > <Link id='executionsBtn' to={RoutePage.EXECUTIONS} className={commonCss.unstyled}> <Button className={classes( css.button, this._highlightExecutionsButton(page) && css.active, collapsed && css.collapsedButton, )} > <ExecutionsIcon /> <span className={classes(collapsed && css.collapsedLabel, css.label)}> Executions </span> </Button> </Link> </Tooltip> <hr className={classes(css.separator, collapsed && css.collapsedSeparator)} /> <IconButton className={classes(css.chevron, collapsed && css.collapsedChevron)} onClick={this._toggleNavClicked.bind(this)} > <ChevronLeftIcon /> </IconButton> </div> <div className={collapsed ? css.infoHidden : css.infoVisible}> {displayBuildInfo && ( <Tooltip title={'Build date: ' + displayBuildInfo.date} enterDelay={300} placement={'top-start'} > <div className={css.envMetadata}> <span>Build commit: </span> <a href={displayBuildInfo.commitUrl} className={classes(css.link, commonCss.unstyled)} rel='noopener' target='_blank' > {displayBuildInfo.commitHash} </a> </div> </Tooltip> )} <Tooltip title='Report an Issue' enterDelay={300} placement={'top-start'}> <div className={css.envMetadata}> <a href='https://github.com/kubeflow/pipelines/issues/new?template=BUG_REPORT.md' className={classes(css.link, commonCss.unstyled)} rel='noopener' target='_blank' > Report an Issue </a> </div> </Tooltip> </div> </div> ); } private _highlightArtifactsButton(page: string): boolean { return page.startsWith(RoutePrefix.ARTIFACT); } private _highlightExecutionsButton(page: string): boolean { return page.startsWith(RoutePrefix.EXECUTION); } private _toggleNavClicked(): void { this.setStateSafe( { collapsed: !this.state.collapsed, manualCollapseState: true, }, () => LocalStorage.saveNavbarCollapsed(this.state.collapsed), ); this._toggleNavCollapsed(); } private _toggleNavCollapsed(shouldCollapse?: boolean): void { this.setStateSafe({ collapsed: shouldCollapse !== undefined ? shouldCollapse : !this.state.collapsed, }); } private _maybeResize(): void { if (!this.state.manualCollapseState) { this._toggleNavCollapsed(window.innerWidth < this._AUTO_COLLAPSE_WIDTH); } } private setStateSafe(newState: Partial<SideNavState>, cb?: () => void): void { if (this._isMounted) { this.setState(newState as any, cb); } } } export default SideNav;
the_stack
import RandExp from 'randexp'; import { config as dotenv } from 'dotenv'; import { Logger } from 'pino'; import { Page, Protocol, ElementHandle } from 'puppeteer'; // import { writeFileSync } from 'fs-extra'; import { getCookiesRaw, setPuppeteerCookies } from '../../src/common/request'; import { EPIC_CLIENT_ID, STORE_HOMEPAGE_EN } from '../../src/common/constants'; import { getHcaptchaCookies } from '../../src/puppet/hcaptcha'; import puppeteer, { toughCookieFileStoreToPuppeteerCookie, getDevtoolsUrl, launchArgs, } from '../../src/common/puppeteer'; import logger from '../../src/common/logger'; import Smtp4Dev from './smtp4dev'; import { LocalNotifier } from '../../src/notifiers'; dotenv(); const NOTIFICATION_TIMEOUT = 24 * 60 * 60 * 1000; export interface AccountManagerProps { username?: string; password?: string; totp?: string; country?: string; } export default class AccountManager { private smtp4dev: Smtp4Dev; public email: string; public username: string; public password: string; public country: string; public totp?: string; private addressHost = process.env.CREATION_EMAIL_HOST || ''; private L: Logger; constructor(props?: AccountManagerProps) { if (props?.username) { this.username = props?.username; } else { const randUser = new RandExp(/[0-9a-zA-Z]{8,16}/); this.username = randUser.gen(); } if (props?.password) { this.password = props?.password; } else { const randPass = new RandExp(/[a-zA-Z]{4,8}[0-9]{3,8}/); this.password = randPass.gen(); } this.country = props?.country || 'United States'; this.totp = props?.totp; this.smtp4dev = new Smtp4Dev({ apiBaseUrl: process.env.SMTP4DEV_URL || '', requestExtensions: { username: process.env.SMTP4DEV_USER, password: process.env.SMTP4DEV_PASSWORD, }, }); this.email = `${this.username}@${this.addressHost}`; this.L = logger.child({ username: this.username, }); } public logAccountDetails(): void { this.L.info({ email: this.email, password: this.password, totp: this.totp, }); } public async createAccount(): Promise<void> { this.L.info({ username: this.username, password: this.password, email: this.email }); const hCaptchaCookies = await getHcaptchaCookies(); const userCookies = await getCookiesRaw(this.email); const puppeteerCookies = toughCookieFileStoreToPuppeteerCookie(userCookies); this.L.debug('Logging in with puppeteer'); const browser = await puppeteer.launch(launchArgs); const page = await browser.newPage(); this.L.trace(getDevtoolsUrl(page)); const cdpClient = await page.target().createCDPSession(); await cdpClient.send('Network.setCookies', { cookies: [...puppeteerCookies, ...hCaptchaCookies], }); await page.setCookie(...puppeteerCookies, ...hCaptchaCookies); await page.goto( `https://www.epicgames.com/id/register/epic?redirect_uri=${STORE_HOMEPAGE_EN}&client_id=${EPIC_CLIENT_ID}`, { waitUntil: 'networkidle0' } ); await this.fillDOB(page); await this.fillSignUpForm(page); await this.handleCaptcha(page); await this.fillEmailVerificationForm(page); this.L.trace('Saving new cookies'); const currentUrlCookies = (await cdpClient.send('Network.getAllCookies')) as { cookies: Protocol.Network.Cookie[]; }; await browser.close(); setPuppeteerCookies(this.email, currentUrlCookies.cookies); this.L.info({ username: this.username, password: this.password, email: this.email }); } private async fillDOB(page: Page): Promise<void> { this.L.trace('Getting date fields'); const [monthInput, dayInput, yearInput] = await Promise.all([ page.waitForSelector(`#month`) as Promise<ElementHandle<HTMLDivElement>>, page.waitForSelector(`#day`) as Promise<ElementHandle<HTMLDivElement>>, page.waitForSelector(`#year`) as Promise<ElementHandle<HTMLInputElement>>, ]); await monthInput.click(); const month1 = (await page.waitForSelector( `ul.MuiList-root > li` )) as ElementHandle<HTMLLIElement>; await month1.click(); await page.waitForTimeout(500); // idk why this is required await dayInput.click(); const day1 = (await page.waitForSelector( `ul.MuiList-root > li` )) as ElementHandle<HTMLLIElement>; await day1.click(); await yearInput.type(this.getRandomInt(1970, 2002).toString()); const continueButton = (await page.waitForSelector( `#continue:not([disabled])` )) as ElementHandle<HTMLButtonElement>; await page.waitForTimeout(500); // idk why this is required this.L.trace('Clicking continueButton'); await continueButton.click({ delay: 100 }); } public async deleteAccount(): Promise<void> { this.L.info({ email: this.email }, 'Deleting account'); const hCaptchaCookies = await getHcaptchaCookies(); const userCookies = await getCookiesRaw(this.email); const puppeteerCookies = toughCookieFileStoreToPuppeteerCookie(userCookies); this.L.debug('Logging in with puppeteer'); const browser = await puppeteer.launch(launchArgs); const page = await browser.newPage(); this.L.trace(getDevtoolsUrl(page)); const cdpClient = await page.target().createCDPSession(); await cdpClient.send('Network.setCookies', { cookies: [...puppeteerCookies, ...hCaptchaCookies], }); await page.setCookie(...puppeteerCookies, ...hCaptchaCookies); await page.goto(`https://www.epicgames.com/account/personal`, { waitUntil: 'networkidle0' }); this.L.trace('Waiting for deleteButton'); const deleteButton = (await page.waitForXPath( `//button[contains(., 'Request Account Delete')]` )) as ElementHandle<HTMLButtonElement>; this.L.trace('Clicking deleteButton'); await deleteButton.click({ delay: 100 }); this.L.trace('Waiting for securityCodeInput'); const securityCodeInput = (await page.waitForSelector( `input[name='security-code']` )) as ElementHandle<HTMLInputElement>; const code = await this.getActionVerification(); this.L.trace('Filling securityCodeInput'); await securityCodeInput.type(code); this.L.trace('Waiting for confirmButton'); const confirmButton = (await page.waitForXPath( `//button[contains(., 'Confirm Delete Request')]` )) as ElementHandle<HTMLButtonElement>; this.L.trace('Clicking confirmButton'); await confirmButton.click({ delay: 100 }); this.L.trace('Waiting for skipSurveyButton'); const skipSurveyButton = (await page.waitForSelector( `button#deletion-reason-skip` )) as ElementHandle<HTMLButtonElement>; this.L.trace('Clicking skipSurveyButton'); await skipSurveyButton.click({ delay: 100 }); await page.waitForSelector(`div.account-deletion-request-success-modal`); this.L.debug('Account deletion successful'); this.L.trace('Saving new cookies'); const currentUrlCookies = (await cdpClient.send('Network.getAllCookies')) as { cookies: Protocol.Network.Cookie[]; }; await browser.close(); setPuppeteerCookies(this.email, currentUrlCookies.cookies); } private async fillSignUpForm(page: Page): Promise<void> { this.L.trace('Getting sign up fields'); const randName = new RandExp(/[a-zA-Z]{3,12}/); const [ countryInput, firstNameInput, lastNameInput, displayNameInput, emailInput, passwordInput, tosInput, ] = await Promise.all([ page.waitForSelector(`#country`) as Promise<ElementHandle<Element>>, page.waitForSelector(`#name`) as Promise<ElementHandle<HTMLInputElement>>, page.waitForSelector(`#lastName`) as Promise<ElementHandle<HTMLInputElement>>, page.waitForSelector(`#displayName`) as Promise<ElementHandle<HTMLInputElement>>, page.waitForSelector(`#email`) as Promise<ElementHandle<HTMLInputElement>>, page.waitForSelector(`#password`) as Promise<ElementHandle<HTMLInputElement>>, page.waitForSelector(`#tos`) as Promise<ElementHandle<HTMLInputElement>>, ]); await countryInput.type(this.country); await firstNameInput.type(randName.gen()); await lastNameInput.type(randName.gen()); await displayNameInput.type(this.username); await emailInput.type(this.email); await passwordInput.type(this.password); await tosInput.click(); const submitButton = (await page.waitForSelector( `#btn-submit:not([disabled])` )) as ElementHandle<HTMLButtonElement>; this.L.trace('Clicking submitButton'); await submitButton.click({ delay: 100 }); } private async waitForHCaptcha(page: Page): Promise<'captcha' | 'nav'> { try { const talonHandle = await page.$('iframe#talon_frame_registration_prod'); if (!talonHandle) throw new Error('Could not find talon_frame_registration_prod'); const talonFrame = await talonHandle.contentFrame(); if (!talonFrame) throw new Error('Could not find talonFrame contentFrame'); this.L.trace('Waiting for hcaptcha iframe'); await talonFrame.waitForSelector(`#challenge_container_hcaptcha > iframe[src*="hcaptcha"]`, { visible: true, }); return 'captcha'; } catch (err) { if (err.message.includes('timeout')) { throw err; } if (err.message.includes('detached')) { this.L.trace(err); } else { this.L.warn(err); } return 'nav'; } } private async handleCaptcha(page: Page): Promise<void> { const action = await this.waitForHCaptcha(page); if (action === 'nav') return; this.L.debug('Captcha detected'); const url = await page.openPortal(); this.L.info({ url }, 'Go to this URL and do something'); // eslint-disable-next-line @typescript-eslint/no-explicit-any new LocalNotifier(null as any).sendNotification(url); await page.waitForSelector(`input[name='code-input-0']`, { timeout: NOTIFICATION_TIMEOUT, }); await page.closePortal(); } private async fillEmailVerificationForm(page: Page): Promise<void> { this.L.trace('Working on email verification form'); const code = await this.getVerification(); this.L.trace('Waiting for codeInput'); const codeInput = (await page.waitForSelector( `input[name='code-input-0']` )) as ElementHandle<HTMLInputElement>; await codeInput.click({ delay: 100 }); await page.keyboard.type(code); this.L.trace('Waiting for continueButton'); const continueButton = (await page.waitForSelector( `#continue:not([disabled])` )) as ElementHandle<HTMLButtonElement>; this.L.trace('Clicking continueButton'); await continueButton.click(); await page.waitForNavigation({ waitUntil: 'networkidle2' }); } private async getVerification(): Promise<string> { this.L.debug('Waiting for creation verification email'); const message = await this.smtp4dev.findNewEmailTo(this.username); const emailSource = await this.smtp4dev.getMessageSource(message.id); // writeFileSync('email-source.eml', emailSource, 'utf8'); const codeRegexp = /\\t\\t([0-9]{6})\\n/g; const matches = codeRegexp.exec(emailSource); if (!matches) throw new Error('No code matches'); const code = matches[1].trim(); this.L.debug({ code }, 'Email code'); return code; } private async getActionVerification(): Promise<string> { this.L.debug('Waiting for action verification email'); const message = await this.smtp4dev.findNewEmailTo(this.username); const emailSource = await this.smtp4dev.getMessageSource(message.id); // writeFileSync('email-source.eml', emailSource, 'utf8'); const codeRegexp = / +([0-9]{6})<br\/><br\/>/g; const matches = codeRegexp.exec(emailSource); if (!matches) throw new Error('No code matches'); const code = matches[1].trim(); this.L.debug({ code }, 'Email code'); return code; } private getRandomInt(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1) + min); } }
the_stack
import * as fs from "fs"; import * as path from "path"; import * as readline from "readline"; import * as chalk from "chalk"; import { help, extractEntryPointKnownFile, isStdInArgs, extractFiles, extractArgs, loadUserSrc, tryLoadPackage, extractEntryPoint, extractConfig } from "./args_load"; import { ConfigRun, Package, parseURIPathGlob } from "./package_load"; import { PackageConfig, SymbolicActionMode } from "../compiler/mir_assembly"; import { workflowRunICPPFile } from "../tooling/icpp/transpiler/iccp_workflows"; import { generateStandardVOpts, workflowEvaluate } from "../tooling/checker/smt_workflows"; function processRunAction(args: string[]) { if(args.length === 0) { args.push("./package.json"); } if(path.extname(args[0]) === ".bsqapi") { const entryfile = args[0]; const entrypoint = extractEntryPointKnownFile(args, process.cwd(), entryfile); if(entrypoint === undefined) { process.stderr.write(chalk.red("Could not parse 'entrypoint' option\n")); help("run"); process.exit(1); } let fargs: any[] | undefined = undefined; if (!isStdInArgs(args)) { fargs = extractArgs(args); if (fargs === undefined) { process.stderr.write(chalk.red("Could not parse 'arguments' option\n")); help("run"); process.exit(1); } } const files = extractFiles(process.cwd(), args); if(files === undefined) { process.stderr.write(chalk.red("Could not parse 'files' option\n")); help("run"); process.exit(1); } const entryglob = parseURIPathGlob(path.resolve(process.cwd(), entryfile)); if(entryglob === undefined) { process.stderr.write(chalk.red("Could not parse 'entrypoint' option\n")); help("run"); process.exit(1); } const srcfiles = loadUserSrc(process.cwd(), [entryglob, ...files]); if(srcfiles === undefined) { process.stderr.write(chalk.red("Failed when loading source files\n")); process.exit(1); } const usersrcinfo = srcfiles.map((sf) => { return { srcpath: sf, filename: path.basename(sf), contents: fs.readFileSync(sf).toString() }; }); const userpackage = new PackageConfig([], usersrcinfo); if(fargs === undefined) { // bosque run|debug [package_path.json] [--entrypoint fname] [--config cname] let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question(">> ", (input) => { try { const jargs = JSON.parse(input); process.stdout.write(`Evaluating...\n`); workflowRunICPPFile(jargs, userpackage, args[0] === "debug", "test", false, args[0] === "debug", {}, entrypoint, (result: string | undefined) => { if (result !== undefined) { process.stdout.write(`${result}\n`); } else { process.stdout.write(`failure\n`); } process.exit(0); }); } catch (ex) { process.stderr.write(`Failure ${ex}\n`); process.exit(1); } }); } else { // bosque run|debug [package_path.json] [--entrypoint fname] [--config cname] --args "[...]" workflowRunICPPFile(fargs, userpackage, args[0] === "debug", "test", false, args[0] === "debug", {}, entrypoint, (result: string | undefined) => { if (result !== undefined) { process.stdout.write(`${result}\n`); } else { process.stdout.write(`failure\n`); } process.exit(0); }); } } else { let workingdir = process.cwd(); let pckg: Package | undefined = undefined; if(path.extname(args[0]) === ".json") { workingdir = path.dirname(path.resolve(args[0])); pckg = tryLoadPackage(path.resolve(args[0])); } else { const implicitpckg = path.resolve(workingdir, "package.json"); if(fs.existsSync(implicitpckg)) { pckg = tryLoadPackage(implicitpckg); } } if(pckg === undefined) { process.stderr.write(chalk.red("Could not parse 'package' option\n")); help("run"); process.exit(1); } const entrypoint = extractEntryPoint(args, workingdir, pckg.src.entrypoints); if(entrypoint === undefined) { process.stderr.write(chalk.red("Could not parse 'entrypoint' option\n")); help("run"); process.exit(1); } let fargs: any[] | undefined = undefined; if (!isStdInArgs(args)) { fargs = extractArgs(args); if (fargs === undefined) { process.stderr.write(chalk.red("Could not parse 'arguments' option\n")); help("run"); process.exit(1); } } const cfg = extractConfig<ConfigRun>(args, pckg, workingdir, "run"); if(cfg === undefined) { process.stderr.write(chalk.red("Could not parse 'config' option\n")); help("run"); process.exit(1); } const srcfiles = loadUserSrc(workingdir, [...pckg.src.entrypoints, ...pckg.src.bsqsource]); if(srcfiles === undefined) { process.stderr.write(chalk.red("Failed when loading source files\n")); process.exit(1); } const usersrcinfo = srcfiles.map((sf) => { return { srcpath: sf, filename: path.basename(sf), contents: fs.readFileSync(sf).toString() }; }); const userpackage = new PackageConfig([...cfg.macros, ...cfg.globalmacros], usersrcinfo); if(fargs === undefined) { // bosque run|debug [package_path.json] [--entrypoint fname] [--config cname] let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question(">> ", (input) => { try { const jargs = JSON.parse(input); process.stdout.write(`Evaluating...\n`); workflowRunICPPFile(jargs, userpackage, args[0] === "debug", cfg.buildlevel, false, args[0] === "debug", {}, entrypoint, (result: string | undefined) => { if (result !== undefined) { process.stdout.write(`${result}\n`); } else { process.stdout.write(`failure\n`); } process.exit(0); }); } catch (ex) { process.stderr.write(`Failure ${ex}\n`); process.exit(1); } }); } else { // bosque run|debug [package_path.json] [--entrypoint fname] [--config cname] --args "[...]" workflowRunICPPFile(fargs, userpackage, args[0] === "debug", cfg.buildlevel, false, args[0] === "debug", {}, entrypoint, (result: string | undefined) => { process.stdout.write(`${result}\n`); process.exit(0); }); } } } function processRunSymbolicAction(args: string[]) { const timeout = 10000; const eval_opts = generateStandardVOpts(SymbolicActionMode.EvaluateSymbolic); if(args.length === 0) { args.push("./package.json"); } let workingdir = process.cwd(); let pckg: Package | undefined = undefined; if (path.extname(args[0]) === ".json") { workingdir = path.dirname(path.resolve(args[0])); pckg = tryLoadPackage(path.resolve(args[0])); } else { const implicitpckg = path.resolve(workingdir, "package.json"); if (fs.existsSync(implicitpckg)) { pckg = tryLoadPackage(implicitpckg); } } if (pckg === undefined) { process.stderr.write(chalk.red("Could not parse 'package' option\n")); help("symrun"); process.exit(1); } const entrypoint = extractEntryPoint(args, workingdir, pckg.src.entrypoints); if (entrypoint === undefined) { process.stderr.write(chalk.red("Could not parse 'entrypoint' option\n")); help("symrun"); process.exit(1); } let fargs: any[] | undefined = undefined; if (!isStdInArgs(args)) { fargs = extractArgs(args); if (fargs === undefined) { process.stderr.write(chalk.red("Could not parse 'arguments' option\n")); help("symrun"); process.exit(1); } } const cfg = extractConfig<ConfigRun>(args, pckg, workingdir, "run"); if (cfg === undefined) { process.stderr.write(chalk.red("Could not parse 'config' option\n")); help("symrun"); process.exit(1); } const srcfiles = loadUserSrc(workingdir, [...pckg.src.entrypoints, ...pckg.src.bsqsource]); if (srcfiles === undefined) { process.stderr.write(chalk.red("Failed when loading source files\n")); process.exit(1); } const usersrcinfo = srcfiles.map((sf) => { return { srcpath: sf, filename: path.basename(sf), contents: fs.readFileSync(sf).toString() }; }); const userpackage = new PackageConfig([...cfg.macros, ...cfg.globalmacros], usersrcinfo); if(fargs === undefined) { // bosque runsym [package_path.json] [--entrypoint fname] [--config cname] let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question(">> ", (input) => { try { const jinput = JSON.parse(input) as any[]; workflowEvaluate(userpackage, "debug", false, timeout, eval_opts, entrypoint, jinput, (res: string) => { try { const jres = JSON.parse(res); if (jres["status"] === "unreachable") { process.stdout.write(`No valid (non error) result exists for this input!\n`); } else if (jres["status"] === "output") { process.stdout.write(`Generated output in ${jres["time"]} millis!\n`); process.stdout.write(JSON.stringify(jres["value"], undefined, 2) + "\n"); } else if (jres["status"] === "timeout") { process.stdout.write(`Solver timeout :(\n`); } else { process.stdout.write(`Failed with -- ${JSON.stringify(jres)}`); } process.exit(0); } catch (ex) { process.stderr.write(`Failure ${ex}\n`); process.exit(1); } }); } catch (ex) { process.stderr.write(`Failure ${ex}\n`); process.exit(1); } }); } else { // bosque runsym [package_path.json] [--entrypoint fname] [--config cname] --args "[...]" workflowEvaluate(userpackage, "debug", false, timeout, eval_opts, entrypoint, fargs, (res: string) => { try { const jres = JSON.parse(res); if (jres["status"] === "unreachable") { process.stdout.write(`No valid (non error) result exists for this input!\n`); } else if (jres["status"] === "output") { process.stdout.write(`Generated output in ${jres["time"]} millis!\n`); process.stdout.write(JSON.stringify(jres["value"], undefined, 2) + "\n"); } else if (jres["status"] === "timeout") { process.stdout.write(`Solver timeout :(\n`); } else { process.stdout.write(`Failed with -- ${JSON.stringify(jres)}`); } process.exit(0); } catch (ex) { process.stderr.write(`Failure ${ex}\n`); process.exit(1); } }); } } export { processRunAction, processRunSymbolicAction };
the_stack
import { Buffer } from 'buffer'; import * as crypto from 'crypto'; import * as qr from 'qr-image'; import { mergeMap, Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; import { decode, encode } from 'thirty-two'; import { OTPVerifyResult, QrCodeGenerateOptions, QrCodeGenerateValidatedOptions, U2FGenerateOptions, U2FGenerateValidatedData, U2FUriOptions, U2FUriValidatedData, U2FVerifyOptions, U2FVerifyValidatedData, } from '../schemas/interfaces'; import { TOTP } from './totp'; import { Validator } from '../schemas/validator'; /** * U2F class definition */ export class U2F { /** * Generates OTP key * * @param {boolean} asBuffer - Flag to know if we return key in Buffer or hexadecimal string * * @returns {Observable<Buffer | string>} - A random 20 bytes key in Buffer or hexadecimal string format */ static generateOTPKey = (asBuffer: boolean = false): Observable<Buffer | string> => of(crypto.randomBytes(20).toString('hex')) .pipe( map((key: string) => !!asBuffer ? Buffer.from(key, 'hex') : key) ); /** * Text-encode the key as base32 (in the style of Google Authenticator - same as Facebook, Microsoft, etc) * * @param {Buffer} buffer - Secret key in Buffer format * * @returns {Observable<string>} - Text-encode the key as base32 */ static encodeAuthKey = (buffer: Buffer): Observable<string> => of(buffer) .pipe( // 32 ascii characters without trailing '='s map(_ => (encode(_).toString() as string).replace(/=/g, '')), // uppercase with a space every 4 characters map(_ => _.replace(/(\w{4})/g, '$1 ').trim()) ); /** * Decodes base32 key (Google Authenticator, FB, M$, etc) * * @param {string} base32_key - The key from base32 * * @returns {Observable<Buffer>} - Binary-decode the key from base32 */ static decodeAuthKey = (base32_key: string): Observable<Buffer> => U2F._cleanBase32Key(base32_key) .pipe( map(_ => decode(_)) ); /** * Generates OTP key in base32 format (in the style of Google Authenticator - same as Facebook, Microsoft, etc) * * @returns {Observable<string>} - A random 20 bytes key as base32 */ static generateAuthKey = (): Observable<string> => U2F.generateOTPKey(true) .pipe( mergeMap((_: Buffer) => U2F.encodeAuthKey(_)) ); /** * Full OTPAUTH URI spec as explained at https://github.com/google/google-authenticator/wiki/Key-Uri-Format * * @param {string} secret - The secret in base32. This should be unique and secret for * every user as this is the seed that is used to calculate the HMAC. * @param {string} account_name - The user for this account * @param {string} issuer - The provider or service managing that account * @param {U2FUriOptions} options - Object options could contain: * * - {@code time} - The time step of the counter. This must be the same for * every request and is used to calculate C. - default `30` * * - {@code code_digits} - The number of digits in the OTP - default `6` * * - {@code algorithm} - The algorithm to create HMAC: 'SHA1' | 'SHA256' | 'SHA512' - default 'SHA512' * * @returns {Observable<string>} - OTPAUTH URI */ static generateTOTPUri = (secret: string, account_name: string, issuer: string, options: U2FUriOptions = {}): Observable<string> => U2F._cleanBase32Key(secret) .pipe( map(_ => Object.assign({}, options, { secret: _, account_name: account_name, issuer: issuer })), mergeMap((data: U2FUriValidatedData) => Validator.validateDataWithSchemaReference('/rx-otp/schemas/u2f-uri.json', data) ), map((_: U2FUriValidatedData) => // tslint:disable-next-line `otpauth://totp/${encodeURI(_.issuer)}:${encodeURI(_.account_name)}?secret=${_.secret}&issuer=${encodeURIComponent(_.issuer)}&algorithm=${_.algorithm}&digits=${_.code_digits}&period=${_.time}` ) ); /** * Generates an authenticator token * * @param {string} base32_key - The secret in base32. This should be unique and secret for * every user as this is the seed that is used to calculate the HMAC. * @param {U2FGenerateOptions} options - Object options could contain: * * - {@code time} - The time step of the counter. This must be the same for * every request and is used to calculate C. - default `30` * * - {@code timestamp} - OTP validity timestamp - default current datetime. * * - {@code code_digits} - The number of digits in the OTP, not including the checksum, if any - default `6` * * - {@code add_checksum} - A flag indicates if a checksum digit should be appended to the OTP - default `false` * * - {@code truncation_offset} - the offset into the MAC result to begin truncation - default `-1` * * - {@code algorithm} - The algorithm to create HMAC: 'SHA1' | 'SHA256' | 'SHA512' - default 'SHA512' * * @returns {Observable<string>} - A numeric string in base 10 includes code_digits plus the optional checksum digit if requested. */ static generateAuthToken = (base32_key: string, options: U2FGenerateOptions = {}): Observable<string> => U2F.decodeAuthKey(base32_key) .pipe( map((_: Buffer) => Object.assign({}, options, { key: _.toString('hex') })), mergeMap((data: U2FGenerateValidatedData) => Validator.validateDataWithSchemaReference('/rx-otp/schemas/u2f-generate.json', data) ), map((_: U2FGenerateValidatedData) => ({ key: _.key, options: { key_format: 'hex', time: _.time, timestamp: _.timestamp, code_digits: _.code_digits, add_checksum: _.add_checksum, truncation_offset: _.truncation_offset, algorithm: _.algorithm } }) ), mergeMap((_: any) => TOTP.generate(_.key, _.options) ) ); /** * Verifies an authenticator token * * @param {string} token - Passcode to validate * @param {string} base32_key - The secret in base32. This should be unique and secret for * every user as this is the seed that is used to calculate the HMAC. * @param {U2FVerifyOptions} options - Object options could contain: * * - {@code window} - The allowable margin, time steps in seconds since T0, for the counter. The function will check * 'W' codes in the future against the provided passcode. - default `1` * E.g. if W = 1, and T = 30, this function will check the passcode * against all One Time Passcodes between -30s and +30s. * * - {@code time} - The time step of the counter. This must be the same for * every request and is used to calculate C. - default `30` * * - {@code timestamp} - OTP validity timestamp - default current datetime. * * - {@code add_checksum} - A flag indicates if a checksum digit should be appended to the OTP - default `false` * * - {@code truncation_offset} - the offset into the MAC result to begin truncation - default `-1` * * - {@code algorithm} - The algorithm to create HMAC: 'SHA1' | 'SHA256' | 'SHA512' - default 'SHA512' * * @returns {Observable<OTPVerifyResult>} - an object {@code {delta: #, delta_format: 'int'} if the token is valid * else throw an exception */ static verifyAuthToken = (token: string, base32_key: string, options: U2FVerifyOptions = {}): Observable<OTPVerifyResult | {}> => U2F.decodeAuthKey(base32_key) .pipe( map((_: Buffer) => Object.assign({}, options, { token: token, key: _.toString('hex') })), mergeMap((data: U2FVerifyValidatedData) => Validator.validateDataWithSchemaReference('/rx-otp/schemas/u2f-verify.json', data) ), map((_: U2FVerifyValidatedData) => ({ token: _.token, key: _.key, options: { key_format: 'hex', window: _.window, time: _.time, timestamp: _.timestamp, add_checksum: _.add_checksum, truncation_offset: _.truncation_offset, algorithm: _.algorithm } }) ), mergeMap((_: any) => TOTP.verify(_.token, _.key, _.options) ) ); /** * Generates QR code * * @param {string} text - Text to encode * @param {QrCodeGenerateOptions} options - Object options could contain: * * - {@code ec_level} - Error correction level. One of L, M, Q, H - default `M` * * - {@code type} - Image type. Possible values png or svg - default `svg` * * - {@code size} - Size of one module in pixels. Default `5` for png and `undefined` for svg. * * @returns {Observable<string | Buffer>} - String with image data. (Buffer for png) */ static qrCode = (text: string, options: QrCodeGenerateOptions = {}): Observable<string | Buffer> => of( Object.assign({}, options, { text: text }) ) .pipe( mergeMap((data: QrCodeGenerateValidatedOptions) => Validator.validateDataWithSchemaReference('/rx-otp/schemas/u2f-qr.json', data) ), map((_: QrCodeGenerateValidatedOptions) => ({ text: _.text, options: { ec_level: _.ec_level, type: _.type, size: _.size } }) ), map(_ => !!_.options.size ? _ : ({ text: _.text, options: { ec_level: _.options.ec_level, type: _.options.type, } })), map((_: any) => qr.imageSync(_.text, _.options)) ); /** * Cleans base32 key to have only characters * * @param {string} base32_key - The key from base32 * * @returns {Observable<string>} - Text-encode the key as base32 with cleaning format * * @private * @internal */ private static _cleanBase32Key = (base32_key: string): Observable<string> => of(base32_key) .pipe( map(_ => _.replace(/[\s\.\_\-]+/g, '')) ); }
the_stack
import { Theme, ThemeRegistry } from '@aesthetic/system'; import { ClassName, Direction, Engine, FontFace, Import, Keyframes, RenderOptions, Rule, ThemeName, } from '@aesthetic/types'; import { arrayLoop, isDOM, objectLoop } from '@aesthetic/utils'; import { FeatureSheet } from './FeatureSheet'; import { renderComponent, renderTheme } from './renderers'; import { Sheet } from './Sheet'; import { AestheticOptions, ComponentSheet, ComponentSheetFactory, ElementSheetFactory, EventListener, EventType, InferKeys, InferKeysFromSheets, OnChangeDirection, OnChangeTheme, ResultGenerator, SheetParams, SheetRenderResult, ThemeSheet, ThemeSheetFactory, } from './types'; export class Aesthetic<Input extends object = Rule, Output = ClassName> { protected activeDirection?: Direction; protected activeTheme?: ThemeName; protected globalSheetRegistry = new Map<ThemeName, ThemeSheet<string, Input, Output>>(); protected listeners = new Map<EventType, Set<EventListener>>(); protected options: AestheticOptions = {}; protected styleEngine?: Engine<Input, Output>; protected themeRegistry = new ThemeRegistry<Input>(); constructor(options?: AestheticOptions) { if (options) { this.configure(options); } // Must be bound manually because of method overloading this.emit = this.emit.bind(this); this.subscribe = this.subscribe.bind(this); this.unsubscribe = this.unsubscribe.bind(this); } /** * Change the active direction. */ changeDirection = (direction: Direction, propagate: boolean = true): void => { if (direction === this.activeDirection) { return; } const engine = this.getEngine(); // Set the active direction this.activeDirection = direction; // Update engine direction engine.direction = direction; engine.setDirection(direction); // Let consumers know about the change if (propagate) { this.emit('change:direction', [direction]); } }; /** * Change the active theme. */ changeTheme = (name: ThemeName, propagate: boolean = true): void => { if (name === this.activeTheme) { return; } const theme = this.getTheme(name); const engine = this.getEngine(); // Set the active theme this.activeTheme = name; // Set root variables if (this.options.rootVariables) { engine.setRootVariables(theme.toVariables()); } // Render theme styles const results = this.renderThemeSheet(theme); // Update engine theme engine.setTheme(results); // Let consumers know about the change if (propagate) { this.emit('change:theme', [name, results]); } }; /** * Configure options unique to this instance. */ configure = (options: AestheticOptions): void => { Object.assign(this.options, options); // Configure the engine with itself to reapply options if (this.styleEngine) { this.configureEngine(this.styleEngine); } }; /** * Configuring which styling engine to use. */ configureEngine = (engine: Engine<Input, Output>): void => { const { options } = this; if (options.customProperties) { engine.customProperties = options.customProperties; } if (options.directionConverter) { engine.directionConverter = options.directionConverter; } if (options.defaultUnit) { engine.unitSuffixer = options.defaultUnit; } if (options.vendorPrefixer) { engine.vendorPrefixer = options.vendorPrefixer; } this.styleEngine = engine; }; /** * Create a style sheet that supports multiple elements, * for use within components. */ createStyleSheet = <T = unknown>( factory: ComponentSheetFactory<T, Input>, ): ComponentSheet<InferKeys<keyof T>, Input, Output> => new FeatureSheet<Input, Output, ComponentSheetFactory<T, Input>>(factory, renderComponent); /** * Create a style sheet scoped for a single element. */ createScopedStyleSheet = <K extends string = 'element'>( factory: ElementSheetFactory<Input> | Input, selector?: K, ) => this.createStyleSheet<Record<K, Input>>((utils) => ({ [selector ?? 'element']: typeof factory === 'function' ? factory(utils) : factory, })); /** * Create a global style sheet for root theme styles. */ createThemeSheet = <T = unknown>( factory: ThemeSheetFactory<T, Input>, ): ThemeSheet<InferKeys<keyof T>, Input, Output> => new Sheet(factory, renderTheme); /** * Emit all listeners by type, with the defined arguments. */ emit(type: 'change:direction', args: Parameters<OnChangeDirection>): void; emit(type: 'change:theme', args: Parameters<OnChangeTheme>): void; emit(type: EventType, args: unknown[]): void { this.getListeners(type).forEach((listener) => { listener(...args); }); } /** * Generate a list of results using the selectors of a style sheet. * If a set is provided, it will be used to check for variants. */ generateResults: ResultGenerator<string, Output> = (args, variants, renderResult) => { const output: Output[] = []; arrayLoop(args, (arg) => { if (!arg) { return; } // Custom results being passes if (Array.isArray(arg)) { output.push(...(arg as Output[]).filter(Boolean)); return; } const item = renderResult[arg]; if (item?.result) { output.push(item?.result); } arrayLoop(item?.variants, ({ types, result }) => { if (types.every((type) => variants.has(type))) { output.push(result); } }); }); return output; }; /** * Return the active direction for the entire application. If an active direction is undefined, * it will be detected from the browser's `dir` attribute. */ getActiveDirection = (): Direction => { if (this.activeDirection) { return this.activeDirection; } // Detect theme from engine const direction: Direction = this.getEngine().direction || 'ltr'; this.changeDirection(direction); return direction; }; /** * Return the currently active theme instance. If an active instance has not been defined, * one will be detected from the client's browser preferences. */ getActiveTheme = (): Theme<Input> => { if (this.activeTheme) { return this.getTheme(this.activeTheme); } // Detect theme from browser preferences const engine = this.getEngine(); const theme = this.themeRegistry.getPreferredTheme({ matchColorScheme: engine.prefersColorScheme, matchContrastLevel: engine.prefersContrastLevel, }); this.changeTheme(theme.name); return theme; }; /** * Return the current style engine. */ getEngine = (): Engine<Input, Output> => { const current = (typeof global !== 'undefined' && global.AESTHETIC_CUSTOM_ENGINE) || this.styleEngine; if (current) { return current; } throw new Error('No style engine defined. Have you configured one with `configureEngine()`?'); }; /** * Return a set of listeners, or create it if it does not exist. */ getListeners = <T extends Function>(type: EventType): Set<T> => { const set = this.listeners.get(type) ?? new Set(); this.listeners.set(type, set); return set as unknown as Set<T>; }; /** * Return a theme instance by name. */ getTheme = (name: ThemeName): Theme<Input> => this.themeRegistry.getTheme(name); /** * Merge multiple sheets into a single sheet and inherit all overrides. */ mergeStyleSheets = <T extends ComponentSheet<string, Input, Output>[]>( ...sheets: T ): ComponentSheet<InferKeysFromSheets<T>, Input, Output> => { if (sheets.length === 1) { return sheets[0]; } const mergedSheet = new FeatureSheet(sheets[0].factory, sheets[0].renderer); arrayLoop(sheets, (sheet, index) => { if (index > 0) { mergedSheet.addOverride(sheet.factory); } // @ts-expect-error Allow access arrayLoop(sheet.overrides, (override) => { mergedSheet.addOverride(override); }); // @ts-expect-error Allow access objectLoop(sheet.contrastOverrides, (overrides, contrast) => { arrayLoop(overrides, (override) => { mergedSheet.addContrastOverride(contrast, override); }); }); // @ts-expect-error Allow access objectLoop(sheet.schemeOverrides, (overrides, scheme) => { arrayLoop(overrides, (override) => { mergedSheet.addColorSchemeOverride(scheme, override); }); }); // @ts-expect-error Allow access objectLoop(sheet.themeOverrides, (overrides, theme) => { arrayLoop(overrides, (override) => { mergedSheet.addThemeOverride(theme, override); }); }); }); return mergedSheet; }; /** * Register a theme, with optional global theme styles. */ registerTheme = ( name: ThemeName, theme: Theme<Input>, sheet: ThemeSheet<string, Input, Output> | null = null, isDefault: boolean = false, ): void => { this.themeRegistry.register(name, theme, isDefault); if (sheet) { if (__DEV__ && !(sheet instanceof Sheet)) { throw new TypeError('Rendering theme styles require a `Sheet` instance.'); } this.globalSheetRegistry.set(name, sheet); } }; /** * Register a default light or dark theme, with optional global theme styles. */ registerDefaultTheme = ( name: ThemeName, theme: Theme<Input>, sheet: ThemeSheet<string, Input, Output> | null = null, ): void => { this.registerTheme(name, theme, sheet, true); }; /** * Render a `@font-face` to the global style sheet and return the font family name. */ renderFontFace = (fontFace: FontFace, fontFamily?: string, params?: RenderOptions): string => this.getEngine().renderFontFace( { fontFamily, ...fontFace, }, params, ); /** * Render an `@import` to the global style sheet and return the import path. */ renderImport = (path: Import | string, params?: RenderOptions): string => this.getEngine().renderImport(path, params); /** * Render a `@keyframes` to the global style sheet and return the animation name. */ renderKeyframes = ( keyframes: Keyframes, animationName?: string, params?: RenderOptions, ): string => this.getEngine().renderKeyframes(keyframes, animationName, params); /** * Render a style rule outside of the context of a style sheet. */ renderStyles = (rule: Input) => this.getEngine().renderRule(rule, this.getRenderOptions()); /** * Render a component style sheet to the document with the defined style query parameters. */ renderStyleSheet = <T = unknown>( sheet: ComponentSheet<T, Input, Output>, params: SheetParams = {}, ) => { if (__DEV__ && !(sheet instanceof Sheet)) { throw new TypeError('Rendering component styles require a `Sheet` instance.'); } return this.renderSheet<InferKeys<T>>( sheet, params.theme ? this.getTheme(params.theme) : this.getActiveTheme(), params, ); }; /** * Render a theme style sheet and return a result, if one was generated. */ renderThemeSheet = (theme: Theme<Input>, params: SheetParams = {}): Output[] => { const sheet = this.globalSheetRegistry.get(theme.name); const results: Output[] = []; // Render theme CSS variables if (isDOM()) { results.push( this.getEngine().renderRuleGrouped({ '@variables': theme.toVariables() } as Input, { type: 'global', }).result, ); } // Render theme styles if (sheet) { const result = this.renderSheet<'root'>(sheet, theme, params).root?.result; if (result) { results.push(result); } } return results; }; /** * Subscribe and listen to an event by name. */ subscribe(type: 'change:direction', listener: OnChangeDirection): () => void; subscribe(type: 'change:theme', listener: OnChangeTheme): () => void; subscribe(type: EventType, listener: Function): () => void { this.getListeners(type).add(listener); return () => { this.unsubscribe(type as 'change:theme', listener as OnChangeTheme); }; } /** * Unsubscribe from an event by name. */ unsubscribe(type: 'change:direction', listener: OnChangeDirection): void; unsubscribe(type: 'change:theme', listener: OnChangeTheme): void; unsubscribe(type: EventType, listener: Function): void { this.getListeners(type).delete(listener); } protected getRenderOptions(options?: RenderOptions) { return { deterministic: !!this.options.deterministicClasses, direction: this.getActiveDirection(), vendor: !!this.options.vendorPrefixer, ...options, }; } protected renderSheet<Keys>( sheet: ComponentSheet<string, Input, Output> | ThemeSheet<string, Input, Output>, theme: Theme<Input>, params: SheetParams, ): SheetRenderResult<Output, Keys> { return sheet.render( this.getEngine(), theme, this.getRenderOptions(params), ) as SheetRenderResult<Output, Keys>; } }
the_stack
import { EventEmitter } from "events" import fs from "fs" import path from "path" import kebabCase from "lodash/kebabCase" import mapKeys from "lodash/mapKeys" import { createCommand, HELP_CMD, PROG_CMD } from "../command" import { Command } from "../command" import { findCommand } from "../command/find" import { scanCommands } from "../command/scan" import { createConfigurator } from "../config" import { fatalError, UnknownOrUnspecifiedCommandError } from "../error" import { customizeHelp } from "../help" import { CustomizedHelpOpts } from "../help/types" import { logger, setLogger } from "../logger" import { addGlobalOption, createOption, disableGlobalOption, processGlobalOptions, showHelp, } from "../option" import { parseArgv } from "../parser" import { Action, Logger, Configurator, ParserResult, ParserTypes, ProgramConfig, CreateArgumentOpts, CreateOptionProgramOpts, CommandConfig, } from "../types" import { CaporalValidator } from "../types" import { detectVersion } from "../utils/version" const LOG_LEVEL_ENV_VAR = "CAPORAL_LOG_LEVEL" // const SUPPORTED_SHELL = ["bash", "zsh", "fish"] /** * Program class * * @noInheritDoc */ export class Program extends EventEmitter { private commands: Command[] = [] private _config: Configurator<ProgramConfig> private _version?: string private _name?: string private _description?: string private _programmaticMode = false /** * @internal */ public defaultCommand?: Command private _progCommand?: Command private _bin: string private _discoveryPath?: string private _discoveredCommands?: Command[] /** * Number validator. Check that the value looks like a numeric one * and cast the provided value to a javascript `Number`. */ readonly NUMBER = CaporalValidator.NUMBER /** * String validator. Mainly used to make sure the value is a string, * and prevent Caporal auto-casting of numerical values and boolean * strings like `true` or `false`. */ readonly STRING = CaporalValidator.STRING /** * Array validator. Convert any provided value to an array. If a string is provided, * this validator will try to split it by commas. */ readonly ARRAY = CaporalValidator.ARRAY /** * Boolean validator. Check that the value looks like a boolean. * It accepts values like `true`, `false`, `yes`, `no`, `0`, and `1` * and will auto-cast those values to `true` or `false`. */ readonly BOOLEAN = CaporalValidator.BOOLEAN /** * Program constructor. * - Detects the "bin" name from process argv * - Detects the version from package.json * - Set up the help command * @ignore */ constructor() { super() this._bin = path.basename(process.argv[1]) this._version = detectVersion() this._config = createConfigurator({ strictArgsCount: true, strictOptions: true, autoCast: true, logLevelEnvVar: LOG_LEVEL_ENV_VAR, }) this.setupHelpCommand() this.setupErrorHandlers() } /** * @internal */ private setupErrorHandlers(): void { process.once("unhandledRejection", (err) => { if (this._programmaticMode) { throw err } else { this.emit("error", err) } }) this.on("error", fatalError) } /** * The program-command is the command attached directly to the program, * meaning there is no command-keyword used to trigger it. * Mainly used for programs executing only one possible action. * * @internal */ get progCommand(): Command { if (this._progCommand === undefined) { this._progCommand = createCommand(this, PROG_CMD, "") } return this._progCommand } /** * Setup the help command */ private setupHelpCommand(): Command { return this.command(HELP_CMD, "Get help about a specific command") .argument( "[command]", "Command name to get help for. If the command does not exist, global help will be displayed.", ) .action(async (actionParams) => { const { args } = actionParams const command = args.command ? await findCommand(this, [args.command as string]) : undefined // eslint-disable-next-line no-console showHelp({ ...actionParams, command }) return -1 }) .hide() } /** * Customize program help. Can be called multiple times to add more paragraphs and/or sections. * * @param text Help contents * @param options Display options */ help(text: string, options: Partial<CustomizedHelpOpts> = {}): Program { customizeHelp(this, text, options) return this } /** * Toggle strict mode. * Shortcut to calling: `.configure({ strictArgsCount: strict, strictOptions: strict })`. * By default, the program is strict, so if you want to disable strict checking, * just call `.strict(false)`. This setting can be overridden at the command level. * * @param strict boolean enabled flag */ strict(strict = true): Program { return this.configure({ strictArgsCount: strict, strictOptions: strict, }) } /** * Configure some behavioral properties. * * @param props properties to set/update */ configure(props: Partial<ProgramConfig>): Program { this._config.set(props) return this } /** * Get a configuration property value. {@link ProgramConfig Possible keys}. * * @param key Property * @internal */ getConfigProperty<K extends keyof ProgramConfig>(key: K): ProgramConfig[K] { return this._config.get(key) } /** * Return a reformatted synopsis string * * @internal */ async getSynopsis(): Promise<string> { return ( this.getBin() + " " + ((await this.hasCommands()) ? "<command> " : "") + "[ARGUMENTS...] [OPTIONS...]" ).trim() } /** * Return the discovery path, if set * * @internal */ get discoveryPath(): string | undefined { return this._discoveryPath } /** * Return the program version * * @internal */ getVersion(): string | undefined { return this._version } /** * Set the version fo your program. * You won't likely use this method as Caporal tries to guess it from your package.json */ version(ver: string): Program { this._version = ver return this } /** * Set the program name. If not set, the filename minus the extension will be used. */ name(name: string): Program { this._name = name return this } /** * Return the program name. * * @internal */ getName(): string | undefined { return this._name } /** * Return the program description. * * @internal */ getDescription(): string | undefined { return this._description } /** * Set the program description displayed in help. */ description(desc: string): Program { this._description = desc return this } /** * Get the bin name (the name of your executable). * * @internal */ getBin(): string { return this._bin } /** * Sets the executable name. By default, it's auto-detected from the filename of your program. * * @param name Executable name * @example * ```ts * program.bin('myprog') * ``` */ bin(name: string): Program { this._bin = name return this } /** * Set a custom logger for your program. * Your logger should implement the {@link Logger} interface. */ logger(logger: Logger): Program { setLogger(logger) return this } /** * Disable a global option. Will warn if the global option * does not exist of has already been disabled. * * @param name Name, short, or long notation of the option to disable. */ disableGlobalOption(name: string): Program { const disabled = disableGlobalOption(name) if (!disabled) { logger.warn( "Cannot disable global option %s. Either the global option does not exist or has already been disabled.", ) } return this } /** * Returns the list of all commands registered * - By default, Caporal creates one: the "help" command * - When calling argument() or action() on the program instance, * Caporal also create what is called the "program command", which * is a command directly attach to the program, usually used * in mono-command programs. * @internal */ getCommands(): Command[] { return this.commands } /** * Add a command to the program. * * @param name Command name * @param description Command description * @example * ```ts * program.command('order', 'Order some food') * ``` */ command( name: string, description: string, config: Partial<CommandConfig> = {}, ): Command { const cmd = createCommand(this, name, description, config) this.commands.push(cmd) return cmd } /** * Check if the program has user-defined commands. * * @internal * @private */ async hasCommands(): Promise<boolean> { return (await this.getAllCommands()).length > 1 } /** * @internal */ async getAllCommands(): Promise<Command[]> { const discoveredCommands = await this.scanCommands() return [...this.commands, ...discoveredCommands] } /** * Return the log level override, if any is provided using * the right environment variable. * * @internal * @private */ public getLogLevelOverride(): string | undefined { return process.env[this.getConfigProperty("logLevelEnvVar")] } /** * Enable or disable auto casting of arguments & options at the program level. * * @param enabled */ cast(enabled: boolean): Program { return this.configure({ autoCast: enabled }) } /** * Sets a *unique* action for the *entire* program. * * @param {Function} action - Action to run */ action(action: Action): Program { this.progCommand.action(action) return this } /** * Add an argument to the *unique* command of the program. */ argument( synopsis: string, description: string, options: CreateArgumentOpts = {}, ): Command { return this.progCommand.argument(synopsis, description, options) } /** * Add an option to the *unique* command of the program, * or add a global option to the program when `options.global` * is set to `true`. * * @param synopsis Option synopsis like '-f, --force', or '-f, --file \<file\>', or '--with-openssl [path]' * @param description Option description * @param options Additional parameters */ option( synopsis: string, description: string, options: CreateOptionProgramOpts = {}, ): Program { if (options.global) { const opt = createOption(synopsis, description, options) addGlobalOption(opt, options.action) } else { this.progCommand.option(synopsis, description, options) } return this } /** * Discover commands from a specified path. * * Commands must be organized into files (one command per file) in a file tree like: * * ```sh * └── commands * ├── config * │ ├── set.ts * │ └── unset.ts * ├── create * │ ├── job.ts * │ └── service.ts * ├── create.ts * ├── describe.ts * └── get.ts * ``` * * The code above shows a short example of `kubectl` commands and subcommands. * In this case, Caporal will generate the following commands: * * - kubectl get [args...] [options...] * - kubectl config set [args...] [options...] * - kubectl config unset [args...] [options...] * - kubectl create [args...] [options...] * - kubectl create job [args...] [options...] * - kubectl create service [args...] [options...] * - kubectl describe [args...] [options...] * - kubectl get [args...] [options...] * * Notice how the `config` command has a mandatory subcommand associated, * hence cannot be called without a subcommand, contrary to the `create` command. * This is why there is no `config.ts` in the tree. * * @param path */ discover(dirPath: string): Program { let stat try { stat = fs.statSync(dirPath) // eslint-disable-next-line no-empty } catch (e) {} if (!stat || !stat.isDirectory()) { throw new Error( "Caporal setup error: parameter `dirPath` of discover() should be a directory", ) } this._discoveryPath = dirPath return this } /** * Do a full scan of the discovery path to get all existing commands * This should only be used to generate the full list of command, * as for help rendering * * @private */ private async scanCommands(): Promise<Command[]> { if (this._discoveryPath === undefined) { return [] } if (this._discoveredCommands) { return this._discoveredCommands } this._discoveredCommands = await scanCommands(this, this._discoveryPath) return this._discoveredCommands } /* istanbul ignore next */ /** * Reset all commands * * @internal */ public reset(): Program { this.commands = [] this._progCommand = undefined this.setupHelpCommand() return this } /** * Run the program by parsing command line arguments. * Caporal will automatically detect command line arguments from `process.argv` values, * but it can be overridden by providing the `argv` parameter. It returns a Promise * of the value returned by the *Action* triggered. * * ::: warning Be careful * This method returns a `Promise`. You'll usually ignore the returned promise and call run() like this: * * ```ts * [...] * program.action(...) * program.run() * ``` * * If you do add some `.catch()` handler to it, Caporal won't display any potential errors * that the promise could reject, and will let you the responsibility to do it. * ::: * * @param argv Command line arguments to parse, default to `process.argv.slice(2)`. */ async run(argv?: string[]): Promise<unknown> { if (!argv) { // used on web playground if (process.env.CAPORAL_CMD_LINE) { argv = process.env.CAPORAL_CMD_LINE.split(" ").slice(1) // defaut value for common usage } else { argv = process.argv.slice(2) } } /* Search for the command from args, then, if a default command exists, take it, otherwise take the command attached to the program, and lastly the help command/ */ const cmd = await this.findCommand(argv) // parse command line args const result = parseArgv(cmd?.getParserConfig(), argv) /* Run command with parsed args. We are forced to catch a potential error to prevent the rejected promise to propagate un in the stack. */ // eslint-disable-next-line @typescript-eslint/no-empty-function return this._run(result, cmd) /* .catch((e) => e) */ } /** * Try to find the executed command from argv * If command cannot be found from argv, return the default command if any, * then the program-command if any, or finally `undefined`. * If argv is empty, and there is no defaultCommand or progCommand * use the help command * * @param argv */ private async findCommand(argv: string[]): ReturnType<typeof findCommand> { return (await findCommand(this, argv)) || this.defaultCommand || this._progCommand } /** * Run a command, providing parsed data * * @param result * @param cmd * @internal */ private async _run(result: ParserResult, cmd?: Command): Promise<unknown> { // Override logger level via ENV if needed const loggerLevel = this.getLogLevelOverride() if (loggerLevel && Object.keys(logger.levels).includes(loggerLevel)) { logger.level = loggerLevel } // try to run the command // try { if (!cmd) { // we may not have any associated command, but some global options may have been passed // process them, if any // Process any global options const processedResult = { ...result, errors: [], args: {} } const shouldStop = await processGlobalOptions(processedResult, this) if (shouldStop) { this.emit("run") return -1 } // todo: use case: "git unknown-command some args" will display "unknown command 'git'" // but should display "unknown command 'git unknown-command'" throw new UnknownOrUnspecifiedCommandError(this, result.rawArgv[0]) } const ret = await cmd.run(result) this.emit("run", ret) return ret } /** * Programmatic usage. Execute input command with given arguments & options * * Not ideal regarding type casting etc. * * @param args argv array * @param options options object * @param ddash double dash array * @public */ async exec( args: string[], options: Record<string, ParserTypes> = {}, ddash: string[] = [], ): Promise<unknown> { this._programmaticMode = true const cmd = await this.findCommand(args) options = mapKeys(options, (v, key) => kebabCase(key)) return this._run( { args, options, line: args.join(" "), rawOptions: options, rawArgv: args, ddash, }, cmd, ) } }
the_stack
import { HexBuffer } from '../HexBuffer'; import { W3Buffer } from '../W3Buffer'; import { WarResult, JsonResult, angle } from '../CommonInterfaces' interface Unit { type: string; variation: number; position: number[]; rotation: angle; scale: number[]; hero: Hero; inventory: Inventory[]; abilities: Abilities[]; player: number; hitpoints: number; mana: number; gold: number; targetAcquisition: number; // (-1 = normal, -2 = camp), color: number; id: number; } interface Hero { level: number; str: number; agi: number; int: number; } interface Inventory { slot: number; // the int is 0-based, but json format wants 1-6 type: string; // Item ID } interface Abilities { ability: string; // Ability ID active: boolean; // autocast active? 0=no, 1=active level: number; } export abstract class UnitsTranslator { public static jsonToWar(unitsJson: Unit[]): WarResult { const outBufferToWar = new HexBuffer(); /* * Header */ outBufferToWar.addChars('W3do'); outBufferToWar.addInt(8); outBufferToWar.addInt(11); outBufferToWar.addInt(unitsJson.length); // number of units /* * Body */ unitsJson.forEach((unit) => { outBufferToWar.addChars(unit.type); // type outBufferToWar.addInt(unit.variation || 0); // variation outBufferToWar.addFloat(unit.position[0]); // position x outBufferToWar.addFloat(unit.position[1]); // position y outBufferToWar.addFloat(unit.position[2]); // position z outBufferToWar.addFloat(unit.rotation || 0); // rotation angle if (!unit.scale) unit.scale = [1, 1, 1]; outBufferToWar.addFloat(unit.scale[0] || 1); // scale x outBufferToWar.addFloat(unit.scale[1] || 1); // scale y outBufferToWar.addFloat(unit.scale[2] || 1); // scale z // Unit flags outBufferToWar.addByte(0); // UNSUPPORTED: flags outBufferToWar.addInt(0); // unknown outBufferToWar.addInt(unit.player); // player # outBufferToWar.addByte(0); // (byte unknown - 0) outBufferToWar.addByte(0); // (byte unknown - 0) outBufferToWar.addInt(unit.hitpoints); // hitpoints outBufferToWar.addInt(unit.mana || 0); // mana // if(unit.droppedItemSets.length === 0) { // needs to be -1 if no item sets outBufferToWar.addInt(-1); // } // else { // outBuffer.addInt(unit.droppedItemSets.length); // # item sets // } // UNSUPPORTED: dropped items outBufferToWar.addInt(0); // dropped item sets // Gold amount // Required if unit is a gold mine // Optional (set to zero) if unit is not a gold mine outBufferToWar.addInt(unit.gold); // outBufferToWar.addInt(unit.type === 'ngol' ? unit.gold : 0); outBufferToWar.addFloat(unit.targetAcquisition || 0); // target acquisition // Unit hero attributes // Can be left unspecified, but values can never be below 1 if (!unit.hero) unit.hero = { level: 1, str: 1, agi: 1, int: 1 }; outBufferToWar.addInt(unit.hero.level); outBufferToWar.addInt(unit.hero.str); outBufferToWar.addInt(unit.hero.agi); outBufferToWar.addInt(unit.hero.int); // Inventory - - - if (!unit.inventory) unit.inventory = []; outBufferToWar.addInt(unit.inventory.length); // # items in inventory unit.inventory.forEach((item) => { outBufferToWar.addInt(item.slot - 1); // zero-index item slot outBufferToWar.addChars(item.type); }); // Modified abilities - - - if (!unit.abilities) unit.abilities = []; outBufferToWar.addInt(unit.abilities.length); // # modified abilities unit.abilities.forEach((ability) => { outBufferToWar.addChars(ability.ability); // ability string outBufferToWar.addInt(+ability.active); // 0 = not active, 1 = active outBufferToWar.addInt(ability.level); }); outBufferToWar.addInt(0); outBufferToWar.addInt(1); outBufferToWar.addInt(unit.color || unit.player); // custom color, defaults to owning player outBufferToWar.addInt(0); // outBuffer.addInt(unit.waygate); // UNSUPPORTED - waygate outBufferToWar.addInt(unit.id); // id }); return { errors: [], buffer: outBufferToWar.getBuffer() }; } public static warToJson(buffer: Buffer): JsonResult<Unit[]> { const result = []; const outBufferToJSON = new W3Buffer(buffer); const fileId = outBufferToJSON.readChars(4), // W3do for doodad file fileVersion = outBufferToJSON.readInt(), // File version = 7 subVersion = outBufferToJSON.readInt(), // 0B 00 00 00 numUnits = outBufferToJSON.readInt(); // # of units for (let i = 0; i < numUnits; i++) { const unit: Unit = { type: '', variation: -1, position: [0, 0, 0], rotation: 0, scale: [0, 0, 0], hero: { level: 1, str: 1, agi: 1, int: 1 }, inventory: [], abilities: [], player: 0, hitpoints: -1, mana: -1, gold: 0, targetAcquisition: -1, color: -1, id: -1 }; unit.type = outBufferToJSON.readChars(4); // (iDNR = random item, uDNR = random unit) unit.variation = outBufferToJSON.readInt(); unit.position = [outBufferToJSON.readFloat(), outBufferToJSON.readFloat(), outBufferToJSON.readFloat()]; // X Y Z coords unit.rotation = outBufferToJSON.readFloat(); unit.scale = [outBufferToJSON.readFloat(), outBufferToJSON.readFloat(), outBufferToJSON.readFloat()]; // X Y Z scaling // UNSUPPORTED: flags const flags = outBufferToJSON.readByte(); outBufferToJSON.readInt(); // Unknown unit.player = outBufferToJSON.readInt(); // (player1 = 0, 16=neutral passive); note: wc3 patch now has 24 max players outBufferToJSON.readByte(); // unknown outBufferToJSON.readByte(); // unknown unit.hitpoints = outBufferToJSON.readInt(); // -1 = use default unit.mana = outBufferToJSON.readInt(); // -1 = use default, 0 = unit doesn't have mana const droppedItemSetPtr = outBufferToJSON.readInt(), numDroppedItemSets = outBufferToJSON.readInt(); for (let j = 0; j < numDroppedItemSets; j++) { const numDroppableItems = outBufferToJSON.readInt(); for (let k = 0; k < numDroppableItems; k++) { outBufferToJSON.readChars(4); // Item ID outBufferToJSON.readInt(); // % chance to drop } } unit.gold = outBufferToJSON.readInt(); unit.targetAcquisition = outBufferToJSON.readFloat(); // (-1 = normal, -2 = camp) unit.hero = { level: outBufferToJSON.readInt(), // non-hero units = 1 str: outBufferToJSON.readInt(), agi: outBufferToJSON.readInt(), int: outBufferToJSON.readInt() }; const numItemsInventory = outBufferToJSON.readInt(); for (let j = 0; j < numItemsInventory; j++) { unit.inventory.push({ slot: outBufferToJSON.readInt() + 1, // the int is 0-based, but json format wants 1-6 type: outBufferToJSON.readChars(4) // Item ID }); } const numModifiedAbil = outBufferToJSON.readInt(); for (let j = 0; j < numModifiedAbil; j++) { unit.abilities.push({ ability: outBufferToJSON.readChars(4), // Ability ID active: !!outBufferToJSON.readInt(), // autocast active? 0=no, 1=active level: outBufferToJSON.readInt() }); } const randFlag = outBufferToJSON.readInt(); // random unit/item flag "r" (for uDNR units and iDNR items) if (randFlag === 0) { // 0 = Any neutral passive building/item, in this case we have // byte[3]: level of the random unit/item,-1 = any (this is actually interpreted as a 24-bit number) // byte: item class of the random item, 0 = any, 1 = permanent ... (this is 0 for units) // r is also 0 for non random units/items so we have these 4 bytes anyway (even if the id wasnt uDNR or iDNR) outBufferToJSON.readByte(); outBufferToJSON.readByte(); outBufferToJSON.readByte(); outBufferToJSON.readByte(); } else if (randFlag === 1) { // 1 = random unit from random group (defined in the w3i), in this case we have // int: unit group number (which group from the global table) // int: position number (which column of this group) // the column should of course have the item flag set (in the w3i) if this is a random item outBufferToJSON.readInt(); outBufferToJSON.readInt(); } else if (randFlag === 2) { // 2 = random unit from custom table, in this case we have // int: number "n" of different available units // then we have n times a random unit structure const numDiffAvailUnits = outBufferToJSON.readInt(); for (let k = 0; k < numDiffAvailUnits; k++) { outBufferToJSON.readChars(4); // Unit ID outBufferToJSON.readInt(); // % chance } } unit.color = outBufferToJSON.readInt(); outBufferToJSON.readInt(); // UNSUPPORTED: waygate (-1 = deactivated, else its the creation number of the target rect as in war3map.w3r) unit.id = outBufferToJSON.readInt(); result.push(unit); } return { errors: [], json: result }; } }
the_stack
import { ServiceClientOptions } from "@azure/ms-rest-js"; import * as msRest from "@azure/ms-rest-js"; /** * Defines the query context that Bing used for the request. */ export interface QueryContext { /** * The query string as specified in the request. */ originalQuery: string; /** * The query string used by Bing to perform the query. Bing uses the altered query string if the * original query string contained spelling mistakes. For example, if the query string is "saling * downwind", the altered query string will be "sailing downwind". This field is included only if * the original query string contains a spelling mistake. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly alteredQuery?: string; /** * The query string to use to force Bing to use the original string. For example, if the query * string is "saling downwind", the override query string will be "+saling downwind". Remember to * encode the query string which results in "%2Bsaling+downwind". This field is included only if * the original query string contains a spelling mistake. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly alterationOverrideQuery?: string; /** * A Boolean value that indicates whether the specified query has adult intent. The value is true * if the query has adult intent; otherwise, false. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly adultIntent?: boolean; /** * A Boolean value that indicates whether Bing requires the user's location to provide accurate * results. If you specified the user's location by using the X-MSEdge-ClientIP and * X-Search-Location headers, you can ignore this field. For location aware queries, such as * "today's weather" or "restaurants near me" that need the user's location to provide accurate * results, this field is set to true. For location aware queries that include the location (for * example, "Seattle weather"), this field is set to false. This field is also set to false for * queries that are not location aware, such as "best sellers". * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly askUserForLocation?: boolean; } /** * Contains the possible cases for ResponseBase. */ export type ResponseBaseUnion = ResponseBase | IdentifiableUnion; /** * An interface representing ResponseBase. */ export interface ResponseBase { /** * Polymorphic Discriminator */ _type: "ResponseBase"; } /** * Contains the possible cases for Identifiable. */ export type IdentifiableUnion = Identifiable | ResponseUnion; /** * Defines the identity of a resource. */ export interface Identifiable { /** * Polymorphic Discriminator */ _type: "Identifiable"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; } /** * Contains the possible cases for Response. */ export type ResponseUnion = Response | ThingUnion | SearchResponse | AnswerUnion | ErrorResponse; /** * Defines a response. All schemas that could be returned at the root of a response should inherit * from this */ export interface Response { /** * Polymorphic Discriminator */ _type: "Response"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; } /** * Contains the possible cases for Thing. */ export type ThingUnion = Thing | PlaceUnion | Organization | CreativeWorkUnion | IntangibleUnion; /** * An interface representing Thing. */ export interface Thing { /** * Polymorphic Discriminator */ _type: "Thing"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; } /** * Contains the possible cases for CreativeWork. */ export type CreativeWorkUnion = CreativeWork | MediaObjectUnion | License; /** * An interface representing CreativeWork. */ export interface CreativeWork { /** * Polymorphic Discriminator */ _type: "CreativeWork"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The URL to a thumbnail of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbnailUrl?: string; /** * The source of the creative work. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: ThingUnion[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly text?: string; } /** * Contains the possible cases for MediaObject. */ export type MediaObjectUnion = MediaObject | ImageObject; /** * An interface representing MediaObject. */ export interface MediaObject { /** * Polymorphic Discriminator */ _type: "MediaObject"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The URL to a thumbnail of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbnailUrl?: string; /** * The source of the creative work. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: ThingUnion[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly text?: string; /** * Original URL to retrieve the source (file) for the media object (e.g the source URL for the * image). * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contentUrl?: string; /** * URL of the page that hosts the media object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hostPageUrl?: string; /** * The width of the source media object, in pixels. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly width?: number; /** * The height of the source media object, in pixels. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly height?: number; } /** * Defines an image */ export interface ImageObject { /** * Polymorphic Discriminator */ _type: "ImageObject"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The URL to a thumbnail of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbnailUrl?: string; /** * The source of the creative work. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: ThingUnion[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly text?: string; /** * Original URL to retrieve the source (file) for the media object (e.g the source URL for the * image). * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contentUrl?: string; /** * URL of the page that hosts the media object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hostPageUrl?: string; /** * The width of the source media object, in pixels. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly width?: number; /** * The height of the source media object, in pixels. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly height?: number; /** * The URL to a thumbnail of the image * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbnail?: ImageObject; } /** * Defines additional information about an entity such as type hints. */ export interface EntitiesEntityPresentationInfo { /** * The supported scenario. Possible values include: 'DominantEntity', 'DisambiguationItem', * 'ListItem'. Default value: 'DominantEntity'. */ entityScenario: EntityScenario; /** * A list of hints that indicate the entity's type. The list could contain a single hint such as * Movie or a list of hints such as Place, LocalBusiness, Restaurant. Each successive hint in the * array narrows the entity's type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityTypeHints?: EntityType[]; /** * A display version of the entity hint. For example, if entityTypeHints is Artist, this field * may be set to American Singer. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityTypeDisplayHint?: string; } /** * Contains the possible cases for Answer. */ export type AnswerUnion = Answer | SearchResultsAnswerUnion; /** * An interface representing Answer. */ export interface Answer { /** * Polymorphic Discriminator */ _type: "Answer"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; } /** * Contains the possible cases for SearchResultsAnswer. */ export type SearchResultsAnswerUnion = SearchResultsAnswer | Entities | Places; /** * An interface representing SearchResultsAnswer. */ export interface SearchResultsAnswer { /** * Polymorphic Discriminator */ _type: "SearchResultsAnswer"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly queryContext?: QueryContext; } /** * Defines an entity answer. */ export interface Entities { /** * Polymorphic Discriminator */ _type: "Entities"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly queryContext?: QueryContext; /** * The supported query scenario. This field is set to DominantEntity or DisambiguationItem. The * field is set to DominantEntity if Bing determines that only a single entity satisfies the * request. For example, a book, movie, person, or attraction. If multiple entities could satisfy * the request, the field is set to DisambiguationItem. For example, if the request uses the * generic title of a movie franchise, the entity's type would likely be DisambiguationItem. But, * if the request specifies a specific title from the franchise, the entity's type would likely * be DominantEntity. Possible values include: 'DominantEntity', * 'DominantEntityWithDisambiguation', 'Disambiguation', 'List', 'ListWithPivot' * **NOTE: This property will not be serialized. It can only be populated by the server.**. * Default value: 'DominantEntity'. */ readonly queryScenario?: EntityQueryScenario; /** * A list of entities. */ value: ThingUnion[]; } /** * Defines a local entity answer. */ export interface Places { /** * Polymorphic Discriminator */ _type: "Places"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly queryContext?: QueryContext; /** * A list of local entities, such as restaurants or hotels. */ value: ThingUnion[]; } /** * Defines the top-level object that the response includes when the request succeeds. */ export interface SearchResponse { /** * Polymorphic Discriminator */ _type: "SearchResponse"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * An object that contains the query string that Bing used for the request. This object contains * the query string as entered by the user. It may also contain an altered query string that Bing * used for the query if the query string contained a spelling mistake. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly queryContext?: QueryContext; /** * A list of entities that are relevant to the search query. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entities?: Entities; /** * A list of local entities such as restaurants or hotels that are relevant to the query. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly places?: Places; } /** * Contains the possible cases for ContractualRulesContractualRule. */ export type ContractualRulesContractualRuleUnion = ContractualRulesContractualRule | ContractualRulesAttributionUnion; /** * An interface representing ContractualRulesContractualRule. */ export interface ContractualRulesContractualRule { /** * Polymorphic Discriminator */ _type: "ContractualRules/ContractualRule"; /** * The name of the field that the rule applies to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetPropertyName?: string; } /** * Defines the error that occurred. */ export interface ErrorModel { /** * The error code that identifies the category of error. Possible values include: 'None', * 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization', * 'InsufficientAuthorization'. Default value: 'None'. */ code: ErrorCode; /** * The error code that further helps to identify the error. Possible values include: * 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing', * 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing', * 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subCode?: ErrorSubCode; /** * A description of the error. */ message: string; /** * A description that provides additional information about the error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly moreDetails?: string; /** * The parameter in the request that caused the error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly parameter?: string; /** * The parameter's value in the request that was not valid. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly value?: string; } /** * The top-level response that represents a failed request. */ export interface ErrorResponse { /** * Polymorphic Discriminator */ _type: "ErrorResponse"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * A list of errors that describe the reasons why the request failed. */ errors: ErrorModel[]; } /** * Contains the possible cases for Intangible. */ export type IntangibleUnion = Intangible | StructuredValueUnion; /** * An interface representing Intangible. */ export interface Intangible { /** * Polymorphic Discriminator */ _type: "Intangible"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; } /** * Contains the possible cases for StructuredValue. */ export type StructuredValueUnion = StructuredValue | PostalAddress; /** * An interface representing StructuredValue. */ export interface StructuredValue { /** * Polymorphic Discriminator */ _type: "StructuredValue"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; } /** * Defines a postal address. */ export interface PostalAddress { /** * Polymorphic Discriminator */ _type: "PostalAddress"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly streetAddress?: string; /** * The city where the street address is located. For example, Seattle. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly addressLocality?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly addressSubregion?: string; /** * The state or province code where the street address is located. This could be the two-letter * code. For example, WA, or the full name , Washington. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly addressRegion?: string; /** * The zip code or postal code where the street address is located. For example, 98052. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly postalCode?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly postOfficeBoxNumber?: string; /** * The country/region where the street address is located. This could be the two-letter ISO code. * For example, US, or the full name, United States. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly addressCountry?: string; /** * The two letter ISO code of this country. For example, US. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly countryIso?: string; /** * The neighborhood where the street address is located. For example, Westlake. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly neighborhood?: string; /** * Region Abbreviation. For example, WA. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly addressRegionAbbreviation?: string; /** * The complete address. For example, 2100 Westlake Ave N, Bellevue, WA 98052. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly text?: string; } /** * Contains the possible cases for Place. */ export type PlaceUnion = Place | CivicStructureUnion | LocalBusinessUnion | TouristAttraction; /** * Defines information about a local entity, such as a restaurant or hotel. */ export interface Place { /** * Polymorphic Discriminator */ _type: "Place"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; } /** * Defines an organization. */ export interface Organization { /** * Polymorphic Discriminator */ _type: "Organization"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; } /** * Contains the possible cases for LocalBusiness. */ export type LocalBusinessUnion = LocalBusiness | EntertainmentBusinessUnion | FoodEstablishmentUnion | LodgingBusinessUnion; /** * An interface representing LocalBusiness. */ export interface LocalBusiness { /** * Polymorphic Discriminator */ _type: "LocalBusiness"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; } /** * Contains the possible cases for EntertainmentBusiness. */ export type EntertainmentBusinessUnion = EntertainmentBusiness | MovieTheater; /** * An interface representing EntertainmentBusiness. */ export interface EntertainmentBusiness { /** * Polymorphic Discriminator */ _type: "EntertainmentBusiness"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; } /** * An interface representing MovieTheater. */ export interface MovieTheater { /** * Polymorphic Discriminator */ _type: "MovieTheater"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly screenCount?: number; } /** * Contains the possible cases for ContractualRulesAttribution. */ export type ContractualRulesAttributionUnion = ContractualRulesAttribution | ContractualRulesLicenseAttribution | ContractualRulesLinkAttribution | ContractualRulesMediaAttribution | ContractualRulesTextAttribution; /** * An interface representing ContractualRulesAttribution. */ export interface ContractualRulesAttribution { /** * Polymorphic Discriminator */ _type: "ContractualRules/Attribution"; /** * The name of the field that the rule applies to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetPropertyName?: string; /** * A Boolean value that determines whether the contents of the rule must be placed in close * proximity to the field that the rule applies to. If true, the contents must be placed in close * proximity. If false, or this field does not exist, the contents may be placed at the caller's * discretion. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly mustBeCloseToContent?: boolean; } /** * Contains the possible cases for CivicStructure. */ export type CivicStructureUnion = CivicStructure | Airport; /** * An interface representing CivicStructure. */ export interface CivicStructure { /** * Polymorphic Discriminator */ _type: "CivicStructure"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; } /** * An interface representing TouristAttraction. */ export interface TouristAttraction { /** * Polymorphic Discriminator */ _type: "TouristAttraction"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; } /** * An interface representing Airport. */ export interface Airport { /** * Polymorphic Discriminator */ _type: "Airport"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly iataCode?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly icaoCode?: string; } /** * Defines the license under which the text or photo may be used. */ export interface License { /** * Polymorphic Discriminator */ _type: "License"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The URL to a thumbnail of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbnailUrl?: string; /** * The source of the creative work. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: ThingUnion[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly text?: string; } /** * Defines a contractual rule for license attribution. */ export interface ContractualRulesLicenseAttribution { /** * Polymorphic Discriminator */ _type: "ContractualRules/LicenseAttribution"; /** * The name of the field that the rule applies to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetPropertyName?: string; /** * A Boolean value that determines whether the contents of the rule must be placed in close * proximity to the field that the rule applies to. If true, the contents must be placed in close * proximity. If false, or this field does not exist, the contents may be placed at the caller's * discretion. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly mustBeCloseToContent?: boolean; /** * The license under which the content may be used. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly license?: License; /** * The license to display next to the targeted field. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly licenseNotice?: string; } /** * Defines a contractual rule for link attribution. */ export interface ContractualRulesLinkAttribution { /** * Polymorphic Discriminator */ _type: "ContractualRules/LinkAttribution"; /** * The name of the field that the rule applies to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetPropertyName?: string; /** * A Boolean value that determines whether the contents of the rule must be placed in close * proximity to the field that the rule applies to. If true, the contents must be placed in close * proximity. If false, or this field does not exist, the contents may be placed at the caller's * discretion. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly mustBeCloseToContent?: boolean; /** * The attribution text. */ text: string; /** * The URL to the provider's website. Use text and URL to create the hyperlink. */ url: string; /** * Indicates whether this provider's attribution is optional. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly optionalForListDisplay?: boolean; } /** * Defines a contractual rule for media attribution. */ export interface ContractualRulesMediaAttribution { /** * Polymorphic Discriminator */ _type: "ContractualRules/MediaAttribution"; /** * The name of the field that the rule applies to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetPropertyName?: string; /** * A Boolean value that determines whether the contents of the rule must be placed in close * proximity to the field that the rule applies to. If true, the contents must be placed in close * proximity. If false, or this field does not exist, the contents may be placed at the caller's * discretion. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly mustBeCloseToContent?: boolean; /** * The URL that you use to create of hyperlink of the media content. For example, if the target * is an image, you would use the URL to make the image clickable. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; } /** * Defines a contractual rule for text attribution. */ export interface ContractualRulesTextAttribution { /** * Polymorphic Discriminator */ _type: "ContractualRules/TextAttribution"; /** * The name of the field that the rule applies to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetPropertyName?: string; /** * A Boolean value that determines whether the contents of the rule must be placed in close * proximity to the field that the rule applies to. If true, the contents must be placed in close * proximity. If false, or this field does not exist, the contents may be placed at the caller's * discretion. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly mustBeCloseToContent?: boolean; /** * The attribution text. Text attribution applies to the entity as a whole and should be * displayed immediately following the entity presentation. If there are multiple text or link * attribution rules that do not specify a target, you should concatenate them and display them * using a "Data from:" label. */ text: string; /** * Indicates whether this provider's attribution is optional. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly optionalForListDisplay?: boolean; } /** * Contains the possible cases for FoodEstablishment. */ export type FoodEstablishmentUnion = FoodEstablishment | Restaurant; /** * An interface representing FoodEstablishment. */ export interface FoodEstablishment { /** * Polymorphic Discriminator */ _type: "FoodEstablishment"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; } /** * Contains the possible cases for LodgingBusiness. */ export type LodgingBusinessUnion = LodgingBusiness | Hotel; /** * An interface representing LodgingBusiness. */ export interface LodgingBusiness { /** * Polymorphic Discriminator */ _type: "LodgingBusiness"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; } /** * An interface representing Restaurant. */ export interface Restaurant { /** * Polymorphic Discriminator */ _type: "Restaurant"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly acceptsReservations?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reservationUrl?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly servesCuisine?: string[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly menuUrl?: string; } /** * An interface representing Hotel. */ export interface Hotel { /** * Polymorphic Discriminator */ _type: "Hotel"; /** * A String identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * A list of rules that you must adhere to if you display the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly contractualRules?: ContractualRulesContractualRuleUnion[]; /** * The URL To Bing's search result for this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly webSearchUrl?: string; /** * The name of the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly image?: ImageObject; /** * A short description of the item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bingId?: string; /** * The postal address of where the entity is located * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly address?: PostalAddress; /** * The entity's telephone number * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly telephone?: string; /** * $$. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly priceRange?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly panoramas?: ImageObject[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isPermanentlyClosed?: boolean; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tagLine?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hotelClass?: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly amenities?: string[]; } /** * An interface representing EntitySearchClientOptions. */ export interface EntitySearchClientOptions extends ServiceClientOptions { /** * Supported Cognitive Services endpoints (protocol and hostname, for example: * "https://westus.api.cognitive.microsoft.com", "https://api.cognitive.microsoft.com"). Default * value: 'https://api.cognitive.microsoft.com'. */ endpoint?: string; } /** * Optional Parameters. */ export interface EntitiesSearchOptionalParams extends msRest.RequestOptionsBase { /** * A comma-delimited list of one or more languages to use for user interface strings. The list is * in decreasing order of preference. For additional information, including expected format, see * [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang * query parameter are mutually exclusive; do not specify both. If you set this header, you must * also specify the cc query parameter. Bing will use the first supported language it finds from * the list, and combine that language with the cc parameter value to determine the market to * return results for. If the list does not include a supported language, Bing will find the * closest language and market that supports the request, and may use an aggregated or default * market for the results instead of a specified one. You should use this header and the cc query * parameter only if you specify multiple languages; otherwise, you should use the mkt and * setLang query parameters. A user interface string is a string that's used as a label in a user * interface. There are very few user interface strings in the JSON response objects. Any links * in the response objects to Bing.com properties will apply the specified language. */ acceptLanguage?: string; /** * By default, Bing returns cached content, if available. To prevent Bing from returning cached * content, set the Pragma header to no-cache (for example, Pragma: no-cache). */ pragma?: string; /** * The user agent originating the request. Bing uses the user agent to provide mobile users with * an optimized experience. Although optional, you are strongly encouraged to always specify this * header. The user-agent should be the same string that any commonly used browser would send. * For information about user agents, see [RFC * 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). */ userAgent?: string; /** * Bing uses this header to provide users with consistent behavior across Bing API calls. Bing * often flights new features and improvements, and it uses the client ID as a key for assigning * traffic on different flights. If you do not use the same client ID for a user across multiple * requests, then Bing may assign the user to multiple conflicting flights. Being assigned to * multiple conflicting flights can lead to an inconsistent user experience. For example, if the * second request has a different flight assignment than the first, the experience may be * unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search * history, providing a richer experience for the user. Bing also uses this header to help * improve result rankings by analyzing the activity generated by a client ID. The relevance * improvements help with better quality of results delivered by Bing APIs and in turn enables * higher click-through rates for the API consumer. IMPORTANT: Although optional, you should * consider this header required. Persisting the client ID across multiple requests for the same * end user and device combination enables 1) the API consumer to receive a consistent user * experience, and 2) higher click-through rates via better quality of results from the Bing * APIs. Each user that uses your application on the device must have a unique, Bing generated * client ID. If you do not include this header in the request, Bing generates an ID and returns * it in the X-MSEdge-ClientID response header. The only time that you should NOT include this * header in a request is the first time the user uses your app on that device. Use the client ID * for each Bing API request that your app makes for this user on the device. Persist the client * ID. To persist the ID in a browser app, use a persistent HTTP cookie to ensure the ID is used * across all sessions. Do not use a session cookie. For other apps such as mobile apps, use the * device's persistent storage to persist the ID. The next time the user uses your app on that * device, get the client ID that you persisted. Bing responses may or may not include this * header. If the response includes this header, capture the client ID and use it for all * subsequent Bing requests for the user on that device. If you include the X-MSEdge-ClientID, * you must not include cookies in the request. */ clientId?: string; /** * The IPv4 or IPv6 address of the client device. The IP address is used to discover the user's * location. Bing uses the location information to determine safe search behavior. Although * optional, you are encouraged to always specify this header and the X-Search-Location header. * Do not obfuscate the address (for example, by changing the last octet to 0). Obfuscating the * address results in the location not being anywhere near the device's actual location, which * may result in Bing serving erroneous results. */ clientIp?: string; /** * A semicolon-delimited list of key/value pairs that describe the client's geographical * location. Bing uses the location information to determine safe search behavior and to return * relevant local content. Specify the key/value pair as <key>:<value>. The following are the * keys that you use to specify the user's location. lat (required): The latitude of the client's * location, in degrees. The latitude must be greater than or equal to -90.0 and less than or * equal to +90.0. Negative values indicate southern latitudes and positive values indicate * northern latitudes. long (required): The longitude of the client's location, in degrees. The * longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative * values indicate western longitudes and positive values indicate eastern longitudes. re * (required): The radius, in meters, which specifies the horizontal accuracy of the coordinates. * Pass the value returned by the device's location service. Typical values might be 22m for * GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts * (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp * is the number of seconds since January 1, 1970.) head (optional): The client's relative * heading or direction of travel. Specify the direction of travel as degrees from 0 through 360, * counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp * (optional): The horizontal velocity (speed), in meters per second, that the client device is * traveling. alt (optional): The altitude of the client device, in meters. are (optional): The * radius, in meters, that specifies the vertical accuracy of the coordinates. Specify this key * only if you specify the alt key. Although many of the keys are optional, the more information * that you provide, the more accurate the location results are. Although optional, you are * encouraged to always specify the user's geographical location. Providing the location is * especially important if the client's IP address does not accurately reflect the user's * physical location (for example, if the client uses VPN). For optimal results, you should * include this header and the X-MSEdge-ClientIP header, but at a minimum, you should include * this header. */ location?: string; /** * A 2-character country code of the country where the results come from. This API supports only * the United States market. If you specify this query parameter, it must be set to us. If you * set this parameter, you must also specify the Accept-Language header. Bing uses the first * supported language it finds from the languages list, and combine that language with the * country code that you specify to determine the market to return results for. If the languages * list does not include a supported language, Bing finds the closest language and market that * supports the request, or it may use an aggregated or default market for the results instead of * a specified one. You should use this query parameter and the Accept-Language query parameter * only if you specify multiple languages; otherwise, you should use the mkt and setLang query * parameters. This parameter and the mkt query parameter are mutually exclusive—do not specify * both. */ countryCode?: string; /** * The market where the results come from. You are strongly encouraged to always specify the * market, if known. Specifying the market helps Bing route the request and return an appropriate * and optimal response. This parameter and the cc query parameter are mutually exclusive—do not * specify both. Default value: 'en-us'. */ market?: string; /** * A comma-delimited list of answers to include in the response. If you do not specify this * parameter, the response includes all search answers for which there's relevant data. */ responseFilter?: AnswerType[]; /** * The media type to use for the response. The following are the possible case-insensitive * values: JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes * JSON-LD objects that contain the search results. */ responseFormat?: ResponseFormat[]; /** * A filter used to filter adult content. Off: Return webpages with adult text, images, or * videos. Moderate: Return webpages with adult text, but not adult images or videos. Strict: Do * not return webpages with adult text, images, or videos. The default is Moderate. If the * request comes from a market that Bing's adult policy requires that safeSearch is set to * Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: query * operator, there is the chance that the response may contain adult content regardless of what * the safeSearch query parameter is set to. Use site: only if you are aware of the content on * the site and your scenario supports the possibility of adult content. Possible values include: * 'Off', 'Moderate', 'Strict' */ safeSearch?: SafeSearch; /** * The language to use for user interface strings. Specify the language using the ISO 639-1 * 2-letter language code. For example, the language code for English is EN. The default is EN * (English). Although optional, you should always specify the language. Typically, you set * setLang to the same language specified by mkt unless the user wants the user interface strings * displayed in a different language. This parameter and the Accept-Language header are mutually * exclusive; do not specify both. A user interface string is a string that's used as a label in * a user interface. There are few user interface strings in the JSON response objects. Also, any * links to Bing.com properties in the response objects apply the specified language. */ setLang?: string; } /** * Defines values for EntityQueryScenario. * Possible values include: 'DominantEntity', 'DominantEntityWithDisambiguation', 'Disambiguation', * 'List', 'ListWithPivot' * @readonly * @enum {string} */ export type EntityQueryScenario = 'DominantEntity' | 'DominantEntityWithDisambiguation' | 'Disambiguation' | 'List' | 'ListWithPivot'; /** * Defines values for EntityScenario. * Possible values include: 'DominantEntity', 'DisambiguationItem', 'ListItem' * @readonly * @enum {string} */ export type EntityScenario = 'DominantEntity' | 'DisambiguationItem' | 'ListItem'; /** * Defines values for EntityType. * Possible values include: 'Generic', 'Person', 'Place', 'Media', 'Organization', 'LocalBusiness', * 'Restaurant', 'Hotel', 'TouristAttraction', 'Travel', 'City', 'Country', 'Attraction', 'House', * 'State', 'RadioStation', 'StreetAddress', 'Neighborhood', 'Locality', 'PostalCode', 'Region', * 'SubRegion', 'MinorRegion', 'Continent', 'PointOfInterest', 'Other', 'Movie', 'Book', * 'TelevisionShow', 'TelevisionSeason', 'VideoGame', 'MusicAlbum', 'MusicRecording', 'MusicGroup', * 'Composition', 'TheaterPlay', 'Event', 'Actor', 'Artist', 'Attorney', 'Speciality', * 'CollegeOrUniversity', 'School', 'Food', 'Drug', 'Animal', 'SportsTeam', 'Product', 'Car' * @readonly * @enum {string} */ export type EntityType = 'Generic' | 'Person' | 'Place' | 'Media' | 'Organization' | 'LocalBusiness' | 'Restaurant' | 'Hotel' | 'TouristAttraction' | 'Travel' | 'City' | 'Country' | 'Attraction' | 'House' | 'State' | 'RadioStation' | 'StreetAddress' | 'Neighborhood' | 'Locality' | 'PostalCode' | 'Region' | 'SubRegion' | 'MinorRegion' | 'Continent' | 'PointOfInterest' | 'Other' | 'Movie' | 'Book' | 'TelevisionShow' | 'TelevisionSeason' | 'VideoGame' | 'MusicAlbum' | 'MusicRecording' | 'MusicGroup' | 'Composition' | 'TheaterPlay' | 'Event' | 'Actor' | 'Artist' | 'Attorney' | 'Speciality' | 'CollegeOrUniversity' | 'School' | 'Food' | 'Drug' | 'Animal' | 'SportsTeam' | 'Product' | 'Car'; /** * Defines values for ErrorCode. * Possible values include: 'None', 'ServerError', 'InvalidRequest', 'RateLimitExceeded', * 'InvalidAuthorization', 'InsufficientAuthorization' * @readonly * @enum {string} */ export type ErrorCode = 'None' | 'ServerError' | 'InvalidRequest' | 'RateLimitExceeded' | 'InvalidAuthorization' | 'InsufficientAuthorization'; /** * Defines values for ErrorSubCode. * Possible values include: 'UnexpectedError', 'ResourceError', 'NotImplemented', * 'ParameterMissing', 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', * 'AuthorizationMissing', 'AuthorizationRedundancy', 'AuthorizationDisabled', * 'AuthorizationExpired' * @readonly * @enum {string} */ export type ErrorSubCode = 'UnexpectedError' | 'ResourceError' | 'NotImplemented' | 'ParameterMissing' | 'ParameterInvalidValue' | 'HttpNotAllowed' | 'Blocked' | 'AuthorizationMissing' | 'AuthorizationRedundancy' | 'AuthorizationDisabled' | 'AuthorizationExpired'; /** * Defines values for AnswerType. * Possible values include: 'Entities', 'Places' * @readonly * @enum {string} */ export type AnswerType = 'Entities' | 'Places'; /** * Defines values for ResponseFormat. * Possible values include: 'Json', 'JsonLd' * @readonly * @enum {string} */ export type ResponseFormat = 'Json' | 'JsonLd'; /** * Defines values for SafeSearch. * Possible values include: 'Off', 'Moderate', 'Strict' * @readonly * @enum {string} */ export type SafeSearch = 'Off' | 'Moderate' | 'Strict'; /** * Contains response data for the search operation. */ export type EntitiesSearchResponse = SearchResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SearchResponse; }; };
the_stack
import { EventSelector, PrebootOptions, PrebootAppData, PrebootData, DomEvent, PrebootWindow, ServerClientRoot, PrebootSelection, PrebootSelectionDirection, } from '../common/preboot.interfaces'; import {getNodeKeyForPreboot} from '../common/get-node-key'; /** * Called right away to initialize preboot * * @param opts All the preboot options * @param win */ export function initAll(opts: PrebootOptions, win?: PrebootWindow) { const theWindow = <PrebootWindow>(win || window); // Add the preboot options to the preboot data and then add the data to // the window so it can be used later by the client. // Only set new options if they're not already set - we may have multiple app roots // and each of them invokes the init function separately. const data = (theWindow.prebootData = <PrebootData>{ opts: opts, apps: [], listeners: [] }); return () => start(data, theWindow); } /** * Start up preboot by going through each app and assigning the appropriate * handlers. Normally this wouldn't be called directly, but we have set it up so * that it can for older versions of Universal. * * @param prebootData Global preboot data object that contains options and will * have events * @param win Optional param to pass in mock window for testing purposes */ export function start(prebootData: PrebootData, win?: PrebootWindow) { const theWindow = <PrebootWindow>(win || window); const _document = <Document>(theWindow.document || {}); // Remove the current script from the DOM so that child indexes match // between the client & the server. The script is already running so it // doesn't affect it. const currentScript = _document.currentScript || // Support: IE 9-11 only // IE doesn't support document.currentScript. Since the script is invoked // synchronously, though, the current running script is just the last one // currently in the document. [].slice.call(_document.getElementsByTagName('script'), -1)[0]; if (!currentScript) { console.error('Preboot initialization failed, no currentScript has been detected.'); return; } let serverNode = currentScript.parentNode; if (!serverNode) { console.error('Preboot initialization failed, the script is detached'); return; } serverNode.removeChild(currentScript); const opts = prebootData.opts || ({} as PrebootOptions); let eventSelectors = opts.eventSelectors || []; // get the root info const appRoot = prebootData.opts ? getAppRoot(_document, prebootData.opts, serverNode) : null; // we track all events for each app in the prebootData object which is on // the global scope; each `start` invocation adds data for one app only. const appData = <PrebootAppData>{ root: appRoot, events: [] }; if (prebootData.apps) { prebootData.apps.push(appData); } eventSelectors = eventSelectors.map(eventSelector => { if (!eventSelector.hasOwnProperty('replay')) { eventSelector.replay = true; } return eventSelector; }); // loop through all the eventSelectors and create event handlers eventSelectors.forEach(eventSelector => handleEvents(_document, prebootData, appData, eventSelector)); } /** * Create an overlay div and add it to the DOM so it can be used * if a freeze event occurs * * @param _document The global document object (passed in for testing purposes) * @returns Element The overlay node is returned */ export function createOverlay(_document: Document): HTMLElement | undefined { let overlay = _document.createElement('div'); overlay.setAttribute('id', 'prebootOverlay'); overlay.setAttribute( 'style', 'display:none;position:absolute;left:0;' + 'top:0;width:100%;height:100%;z-index:999999;background:black;opacity:.3' ); _document.documentElement.appendChild(overlay); return overlay; } /** * Get references to the current app root node based on input options. Users can * initialize preboot either by specifying appRoot which is just one or more * selectors for apps. This section option is useful for people that are doing their own * buffering (i.e. they have their own client and server view) * * @param _document The global document object used to attach the overlay * @param opts Options passed in by the user to init() * @param serverNode The server node serving as application root * @returns ServerClientRoot An array of root info for the current app */ export function getAppRoot( _document: Document, opts: PrebootOptions, serverNode: HTMLElement ): ServerClientRoot { const root: ServerClientRoot = {serverNode}; // if we are doing buffering, we need to create the buffer for the client // else the client root is the same as the server root.clientNode = opts.buffer ? createBuffer(root) : root.serverNode; // create an overlay if not disabled ,that can be used later if a freeze event occurs if (!opts.disableOverlay) { root.overlay = createOverlay(_document); } return root; } /** * Under given server root, for given selector, record events * * @param _document * @param prebootData * @param appData * @param eventSelector */ export function handleEvents(_document: Document, prebootData: PrebootData, appData: PrebootAppData, eventSelector: EventSelector) { const serverRoot = appData.root.serverNode; // don't do anything if no server root if (!serverRoot) { return; } // Attach delegated event listeners for each event selector. // We need to use delegated events as only the top level server node // exists at this point. eventSelector.events.forEach((eventName: string) => { // get the appropriate handler and add it as an event listener const handler = createListenHandler(_document, prebootData, eventSelector, appData); // attach the handler in the capture phase so that it fires even if // one of the handlers below calls stopPropagation() serverRoot.addEventListener(eventName, handler, true); // need to keep track of listeners so we can do node.removeEventListener() // when preboot done if (prebootData.listeners) { prebootData.listeners.push({ node: serverRoot, eventName, handler }); } }); } /** * Create handler for events that we will record */ export function createListenHandler( _document: Document, prebootData: PrebootData, eventSelector: EventSelector, appData: PrebootAppData ): EventListener { const CARET_EVENTS = ['keyup', 'keydown', 'focusin', 'mouseup', 'mousedown']; const CARET_NODES = ['INPUT', 'TEXTAREA']; // Support: IE 9-11 only // IE uses a prefixed `matches` version const matches = _document.documentElement.matches || (_document.documentElement as any).msMatchesSelector; const opts = prebootData.opts; return function(event: DomEvent) { const node: Element = event.target; // a delegated handlers on document is used so we need to check if // event target matches a desired selector if (!matches.call(node, eventSelector.selector)) { return; } const root = appData.root; const eventName = event.type; // if no node or no event name, just return if (!node || !eventName) { return; } // if key codes set for eventSelector, then don't do anything if event // doesn't include key const keyCodes = eventSelector.keyCodes; if (keyCodes && keyCodes.length) { const matchingKeyCodes = keyCodes.filter(keyCode => event.which === keyCode); // if there are not matches (i.e. key entered NOT one of the key codes) // then don't do anything if (!matchingKeyCodes.length) { return; } } // if for a given set of events we are preventing default, do that if (eventSelector.preventDefault) { event.preventDefault(); } // if an action handler passed in, use that if (eventSelector.action) { eventSelector.action(node, event); } // get the node key for a given node const nodeKey = getNodeKeyForPreboot({ root: root, node: node }); // record active node if (CARET_EVENTS.indexOf(eventName) >= 0) { // if it's an caret node, get the selection for the active node const isCaretNode = CARET_NODES.indexOf(node.tagName ? node.tagName : '') >= 0; prebootData.activeNode = { root: root, node: node, nodeKey: nodeKey, selection: isCaretNode ? getSelection(node as HTMLInputElement) : undefined }; } else if (eventName !== 'change' && eventName !== 'focusout') { prebootData.activeNode = undefined; } // if overlay is not disabled and we are freezing the UI if (opts && !opts.disableOverlay && eventSelector.freeze) { const overlay = root.overlay as HTMLElement; // show the overlay overlay.style.display = 'block'; // hide the overlay after 10 seconds just in case preboot.complete() never // called setTimeout(() => { overlay.style.display = 'none'; }, 10000); } // we will record events for later replay unless explicitly marked as // doNotReplay if (eventSelector.replay) { appData.events.push({ node, nodeKey, event, name: eventName }); } }; } /** * Get the selection data that is later used to set the cursor after client view * is active */ export function getSelection(node: HTMLInputElement): PrebootSelection { node = node || {} as HTMLInputElement; const nodeValue = node.value || ''; const selection: PrebootSelection = { start: nodeValue.length, end: nodeValue.length, direction: 'forward' }; // if browser support selectionStart on node (Chrome, FireFox, IE9+) try { if (node.selectionStart || node.selectionStart === 0) { selection.start = node.selectionStart; selection.end = node.selectionEnd ? node.selectionEnd : 0; selection.direction = node.selectionDirection ? node.selectionDirection as PrebootSelectionDirection : 'none'; } } catch (ex) {} return selection; } /** * Create buffer for a given node * * @param root All the data related to a particular app * @returns Returns the root client node. */ export function createBuffer(root: ServerClientRoot): HTMLElement { const serverNode = root.serverNode; // if no rootServerNode OR the selector is on the entire html doc or the body // OR no parentNode, don't buffer if (!serverNode || !serverNode.parentNode || serverNode === document.documentElement || serverNode === document.body) { return serverNode as HTMLElement; } // create shallow clone of server root const rootClientNode = serverNode.cloneNode(false) as HTMLElement; // we want the client to write to a hidden div until the time for switching // the buffers rootClientNode.style.display = 'none'; // insert the client node before the server and return it serverNode.parentNode.insertBefore(rootClientNode, serverNode); // mark server node as not to be touched by AngularJS - needed for ngUpgrade serverNode.setAttribute('ng-non-bindable', ''); // return the rootClientNode return rootClientNode; }
the_stack
import { obx, computed, globalContext, makeObservable } from '@alilc/lowcode-editor-core'; import { Node, ParentalNode } from './node'; import { TransformStage } from './transform-stage'; import { NodeData, isNodeSchema } from '@alilc/lowcode-types'; import { shallowEqual, compatStage } from '@alilc/lowcode-utils'; import { EventEmitter } from 'events'; import { foreachReverse } from '../../utils/tree'; import { NodeRemoveOptions } from '../../types'; export interface IOnChangeOptions { type: string; node: Node; } export class NodeChildren { @obx.shallow private children: Node[]; private emitter = new EventEmitter(); constructor(readonly owner: ParentalNode, data: NodeData | NodeData[], options: any = {}) { makeObservable(this); this.children = (Array.isArray(data) ? data : [data]).map((child) => { return this.owner.document.createNode(child, options.checkId); }); } internalInitParent() { this.children.forEach((child) => child.internalSetParent(this.owner)); } /** * 导出 schema */ export(stage: TransformStage = TransformStage.Save): NodeData[] { stage = compatStage(stage); return this.children.map((node) => { const data = node.export(stage); if (node.isLeaf() && TransformStage.Save === stage) { // FIXME: filter empty return data.children as NodeData; } return data; }); } import(data?: NodeData | NodeData[], checkId = false) { data = data ? (Array.isArray(data) ? data : [data]) : []; const originChildren = this.children.slice(); this.children.forEach((child) => child.internalSetParent(null)); const children = new Array<Node>(data.length); for (let i = 0, l = data.length; i < l; i++) { const child = originChildren[i]; const item = data[i]; let node: Node | undefined; if (isNodeSchema(item) && !checkId && child && child.componentName === item.componentName) { node = child; node.import(item); } else { node = this.owner.document.createNode(item, checkId); } children[i] = node; } this.children = children; this.internalInitParent(); if (!shallowEqual(children, originChildren)) { this.emitter.emit('change'); } } /** * @deprecated * @param nodes */ concat(nodes: Node[]) { return this.children.concat(nodes); } /** * 元素个数 */ @computed get size(): number { return this.children.length; } /** * 是否空 */ isEmpty() { return this.size < 1; } notEmpty() { return this.size > 0; } @computed get length(): number { return this.children.length; } private purged = false; /** * 回收销毁 */ purge(useMutator = true) { if (this.purged) { return; } this.purged = true; this.children.forEach((child) => { child.purge(useMutator); }); } unlinkChild(node: Node) { const i = this.children.indexOf(node); if (i < 0) { return false; } this.children.splice(i, 1); this.emitter.emit('change', { type: 'unlink', node, }); } /** * 删除一个节点 */ delete(node: Node, purge = false, useMutator = true, options: NodeRemoveOptions = {}): boolean { node.internalPurgeStart(); if (node.isParental()) { foreachReverse( node.children, (subNode: Node) => { subNode.remove(useMutator, purge, options); }, (iterable, idx) => (iterable as NodeChildren).get(idx), ); foreachReverse( node.slots, (slotNode: Node) => { slotNode.remove(useMutator, purge); }, (iterable, idx) => (iterable as [])[idx], ); } // 需要在从 children 中删除 node 前记录下 index,internalSetParent 中会执行删除(unlink)操作 const i = this.children.indexOf(node); if (purge) { // should set parent null node.internalSetParent(null, useMutator); try { node.purge(); } catch (err) { console.error(err); } } const { document } = node; if (globalContext.has('editor')) { globalContext.get('editor').emit('node.remove', { node, index: i }); } document.unlinkNode(node); document.selection.remove(node.id); document.destroyNode(node); this.emitter.emit('change', { type: 'delete', node, }); if (useMutator) { this.reportModified(node, this.owner, { type: 'remove', propagated: false, isSubDeleting: this.owner.isPurging, removeIndex: i, removeNode: node, }); } // purge 为 true 时,已在 internalSetParent 中删除了子节点 if (i > -1 && !purge) { this.children.splice(i, 1); } return false; } /** * 插入一个节点,返回新长度 */ insert(node: Node, at?: number | null, useMutator = true): void { const { children } = this; let index = at == null || at === -1 ? children.length : at; const i = children.indexOf(node); if (node.parent) { globalContext.has('editor') && globalContext.get('editor').emit('node.remove.topLevel', { node, index: node.index, }); } if (i < 0) { if (index < children.length) { children.splice(index, 0, node); } else { children.push(node); } node.internalSetParent(this.owner, useMutator); } else { if (index > i) { index -= 1; } if (index === i) { return; } children.splice(i, 1); children.splice(index, 0, node); } this.emitter.emit('change', { type: 'insert', node, }); this.emitter.emit('insert', node); if (globalContext.has('editor')) { globalContext.get('editor').emit('node.add', { node }); } if (useMutator) { this.reportModified(node, this.owner, { type: 'insert' }); } // check condition group if (node.conditionGroup) { if ( !( // just sort at condition group ( (node.prevSibling && node.prevSibling.conditionGroup === node.conditionGroup) || (node.nextSibling && node.nextSibling.conditionGroup === node.conditionGroup) ) ) ) { node.setConditionGroup(null); } } if (node.prevSibling && node.nextSibling) { const { conditionGroup } = node.prevSibling; // insert at condition group if (conditionGroup && conditionGroup === node.nextSibling.conditionGroup) { node.setConditionGroup(conditionGroup); } } } /** * 取得节点索引编号 */ indexOf(node: Node): number { return this.children.indexOf(node); } /** * */ splice(start: number, deleteCount: number, node?: Node): Node[] { if (node) { return this.children.splice(start, deleteCount, node); } return this.children.splice(start, deleteCount); } /** * 根据索引获得节点 */ get(index: number): Node | null { return this.children.length > index ? this.children[index] : null; } /** * 是否存在节点 */ has(node: Node) { return this.indexOf(node) > -1; } /** * 迭代器 */ [Symbol.iterator](): { next(): { value: Node } } { let index = 0; const { children } = this; const length = children.length || 0; return { next() { if (index < length) { return { value: children[index++], done: false, }; } return { value: undefined as any, done: true, }; }, }; } /** * 遍历 */ forEach(fn: (item: Node, index: number) => void): void { this.children.forEach((child, index) => { return fn(child, index); }); } /** * 遍历 */ map<T>(fn: (item: Node, index: number) => T): T[] | null { return this.children.map((child, index) => { return fn(child, index); }); } every(fn: (item: Node, index: number) => any): boolean { return this.children.every((child, index) => fn(child, index)); } some(fn: (item: Node, index: number) => any): boolean { return this.children.some((child, index) => fn(child, index)); } filter(fn: (item: Node, index: number) => any) { return this.children.filter(fn); } find(fn: (item: Node, index: number) => boolean) { return this.children.find(fn); } reduce(fn: (acc: any, cur: Node) => any, initialValue: any) { return this.children.reduce(fn, initialValue); } mergeChildren( remover: (node: Node, idx: number) => boolean, adder: (children: Node[]) => NodeData[] | null, sorter: (firstNode: Node, secondNode: Node) => number, ) { let changed = false; if (remover) { const willRemove = this.children.filter(remover); if (willRemove.length > 0) { willRemove.forEach((node) => { const i = this.children.indexOf(node); if (i > -1) { this.children.splice(i, 1); node.remove(false); } }); changed = true; } } if (adder) { const items = adder(this.children); if (items && items.length > 0) { items.forEach((child: NodeData) => { const node = this.owner.document.createNode(child); this.children.push(node); node.internalSetParent(this.owner); }); changed = true; } } if (sorter) { this.children = this.children.sort(sorter); changed = true; } if (changed) { this.emitter.emit('change'); } } onChange(fn: (info?: IOnChangeOptions) => void): () => void { this.emitter.on('change', fn); return () => { this.emitter.removeListener('change', fn); }; } onInsert(fn: (node: Node) => void) { this.emitter.on('insert', fn); return () => { this.emitter.removeListener('insert', fn); }; } get [Symbol.toStringTag]() { // 保证向前兼容性 return 'Array'; } private reportModified(node: Node, owner: Node, options = {}) { if (!node) { return; } if (node.isRoot()) { return; } const callbacks = owner.componentMeta.getMetadata().configure.advanced?.callbacks; if (callbacks?.onSubtreeModified) { try { callbacks?.onSubtreeModified.call( node.internalToShellNode(), owner.internalToShellNode(), options, ); } catch (e) { console.error('error when execute advanced.callbacks.onSubtreeModified', e); } } if (owner.parent && !owner.parent.isRoot()) { this.reportModified(node, owner.parent, { ...options, propagated: true }); } } }
the_stack
import { Color, RGBAColor, HSVAColor } from './color' import { isNumber, isString } from './types' import { clamp, Position, getMousePosition } from './utils' type ColorPickerOptions = { window?: Window el?: HTMLElement | string background?: string | number widthUnits?: string heightUnits?: string width?: number height?: number color?: string | number } export class ColorPicker { private _window: Window private _document: Document private _widthUnits: string = 'px' private _heightUnits: string = 'px' private _huePosition: number = 0 private _hueHeight: number = 0 private _maxHue: number = 0 public _inputIsNumber: boolean = false private _saturationWidth: number = 0 private _isChoosing: boolean = false private _callbacks: Function[] = [] public width: number = 0 public height: number = 0 public hue: number = 0 public position: Position = { x: 0, y: 0 } public color: Color = new Color(0) public backgroundColor: Color = new Color(0) public hueColor: Color = new Color(0) public $el: HTMLElement public $saturation: HTMLElement public $hue: HTMLElement public $sbSelector: HTMLElement public $hSelector: HTMLElement constructor(options: ColorPickerOptions = {}) { // Register window and document references in case this is instantiated inside of an iframe this._window = options.window || window this._document = this._window.document // Create DOM this.$el = this._document.createElement('div') this.$el.className = 'Scp' this.$el.innerHTML = ` <div class="Scp-saturation"> <div class="Scp-brightness"></div> <div class="Scp-sbSelector"></div> </div> <div class="Scp-hue"> <div class="Scp-hSelector"></div> </div> ` // DOM accessors this.$saturation = this.$el.querySelector('.Scp-saturation') this.$hue = this.$el.querySelector('.Scp-hue') this.$sbSelector = this.$el.querySelector('.Scp-sbSelector') this.$hSelector = this.$el.querySelector('.Scp-hSelector') // Event listeners this.$saturation.addEventListener('mousedown', this._onSaturationMouseDown) this.$saturation.addEventListener('touchstart', this._onSaturationMouseDown) this.$hue.addEventListener('mousedown', this._onHueMouseDown) this.$hue.addEventListener('touchstart', this._onHueMouseDown) // Some styling and DOMing from options if (options.el) { this.appendTo(options.el) } if (options.background) { this.setBackgroundColor(options.background) } if (options.widthUnits) { this._widthUnits = options.widthUnits } if (options.heightUnits) { this._heightUnits = options.heightUnits } this.setSize(options.width || 175, options.height || 150) this.setColor(options.color) } /** * Add the ColorPicker instance to a DOM element. * @param {HTMLElement} el * @return {ColorPicker} Returns itself for chaining purpose */ public appendTo(el: HTMLElement | string): ColorPicker { if (isString(el)) { document.querySelector(el as string).appendChild(this.$el) } else { ;(el as HTMLElement).appendChild(this.$el) } return this } /** * Removes picker from its parent and kill all listeners. * Call this method for proper destroy. */ public remove() { this._callbacks = [] this._onSaturationMouseUp() this._onHueMouseUp() this.$saturation.removeEventListener( 'mousedown', this._onSaturationMouseDown ) this.$saturation.removeEventListener( 'touchstart', this._onSaturationMouseDown ) this.$hue.removeEventListener('mousedown', this._onHueMouseDown) this.$hue.removeEventListener('touchstart', this._onHueMouseDown) // this.off() if (this.$el.parentNode) { this.$el.parentNode.removeChild(this.$el) } } /** * Manually set the current color of the picker. This is the method * used on instantiation to convert `color` option to actual color for * the picker. Param can be a hexadecimal number or an hex String. * @param {String|Number} color hex color desired * @return {ColorPicker} Returns itself for chaining purpose */ public setColor(color: string | number): ColorPicker { this._inputIsNumber = isNumber(color) this.color.fromHex(color) const { h, s, v } = this.color.hsv if (!isNaN(h)) { this.hue = h } this._moveSelectorTo(this._saturationWidth * s, (1 - v) * this._hueHeight) this._moveHueTo((1 - this.hue) * this._hueHeight) this._updateHue() return this } /** * Set size of the color picker for a given width and height. Note that * a padding of 5px will be added if you chose to use the background option * of the constructor. * @param {Number} width * @param {Number} height * @return {ColorPicker} Returns itself for chaining purpose */ public setSize(width: number, height: number): ColorPicker { this.width = width this.height = height this.$el.style.width = this.width + this._widthUnits this.$el.style.height = this.height + this._heightUnits this._saturationWidth = this.width - 25 this.$saturation.style.width = this._saturationWidth + 'px' this._hueHeight = this.height this._maxHue = this._hueHeight - 2 return this } /** * Set the background color of the picker. It also adds a 5px padding * for design purpose. * @param {String|Number} color hex color desired for background * @return {ColorPicker} Returns itself for chaining purpose */ public setBackgroundColor(color: string | number): ColorPicker { this.backgroundColor.fromHex(color) this.$el.style.padding = '5px' this.$el.style.background = this.backgroundColor.hexString return this } /** * Removes background of the picker if previously set. It's no use * calling this method if you didn't set the background option on start * or if you didn't call setBackgroundColor previously. */ public setNoBackground(): ColorPicker { this.$el.style.padding = '0px' this.$el.style.background = 'none' return this } /** * Registers callback to the update event of the picker. * picker inherits from [component/emitter](https://github.com/component/emitter) * so you could do the same thing by calling `colorPicker.on('update');` * @param {Function} callback * @return {ColorPicker} Returns itself for chaining purpose */ public onChange(callback: Function): ColorPicker { if (this._callbacks.indexOf(callback) < 0) { this._callbacks.push(callback) callback(this.getHexString()) } return this } /** * Is true when mouse is down and user is currently choosing a color. */ public get isChoosing(): boolean { return this._isChoosing } /* ============================================================================= Color getters ============================================================================= */ /** * Main color getter, will return a formatted color string depending on input * or a number depending on the last setColor call. * @return {Number|String} */ public getColor(): number | string { if (this._inputIsNumber) { return this.getHexNumber() } return this.getHexString() } /** * Returns color as css hex string (ex: '#FF0000'). * @return {String} */ public getHexString(): string { return this.color.hexString.toUpperCase() } /** * Returns color as number (ex: 0xFF0000). * @return {Number} */ public getHexNumber(): number { return this.color.hex } /** * Returns color as {r: 1, g: 0, b: 0} object. * @return {Object} */ public getRGB(): RGBAColor { return this.color.rgb } /** * Returns color as {h: 100, s: 1, v: 1} object. * @return {Object} */ public getHSV(): HSVAColor { return this.color.hsv } /** * Returns true if color is perceived as dark * @return {Boolean} */ public isDark(): boolean { return this.color.isDark } /** * Returns true if color is perceived as light * @return {Boolean} */ public isLight(): boolean { return this.color.isLight } /* ============================================================================= Private methods ============================================================================= */ private _moveSelectorTo(x: number, y: number): void { this.position.x = clamp(x, 0, this._saturationWidth) this.position.y = clamp(y, 0, this._hueHeight) this.$sbSelector.style.transform = `translate(${this.position.x}px, ${this.position.y}px)` } private _updateColorFromPosition(): void { this.color.fromHsv({ h: this.hue, s: this.position.x / this._saturationWidth, v: 1 - this.position.y / this._hueHeight }) this._updateColor() } private _moveHueTo(y: number): void { this._huePosition = clamp(y, 0, this._maxHue) this.$hSelector.style.transform = `translateY(${this._huePosition}px)` } private _updateHueFromPosition(): void { const hsvColor = this.getHSV() this.hue = 1 - this._huePosition / this._maxHue this.color.fromHsv({ h: this.hue, s: hsvColor.s, v: hsvColor.v }) this._updateHue() } private _updateHue(): void { this.hueColor.fromHsv({ h: this.hue, s: 1, v: 1 }) this.$saturation.style.background = `linear-gradient(to right, #fff, ${this.hueColor.hexString})` this._updateColor() } private _updateColor(): void { this.$sbSelector.style.background = this.getHexString() this.$sbSelector.style.borderColor = this.isDark() ? '#fff' : '#000' this._triggerChange() } private _triggerChange(): void { this._callbacks.forEach(callback => callback(this.getHexString())) } /* ============================================================================= Events handlers ============================================================================= */ private _onSaturationMouseDown = (e: MouseEvent | TouchEvent): void => { const sbOffset = this.$saturation.getBoundingClientRect() const { x, y } = getMousePosition(e) this._isChoosing = true this._moveSelectorTo(x - sbOffset.left, y - sbOffset.top) this._updateColorFromPosition() this._window.addEventListener('mouseup', this._onSaturationMouseUp) this._window.addEventListener('touchend', this._onSaturationMouseUp) this._window.addEventListener('mousemove', this._onSaturationMouseMove) this._window.addEventListener('touchmove', this._onSaturationMouseMove) e.preventDefault() } private _onSaturationMouseMove = (e: MouseEvent | TouchEvent): void => { const sbOffset = this.$saturation.getBoundingClientRect() const { x, y } = getMousePosition(e) this._moveSelectorTo(x - sbOffset.left, y - sbOffset.top) this._updateColorFromPosition() } private _onSaturationMouseUp = () => { this._isChoosing = false this._window.removeEventListener('mouseup', this._onSaturationMouseUp) this._window.removeEventListener('touchend', this._onSaturationMouseUp) this._window.removeEventListener('mousemove', this._onSaturationMouseMove) this._window.removeEventListener('touchmove', this._onSaturationMouseMove) } private _onHueMouseDown = (e: MouseEvent | TouchEvent): void => { const hOffset = this.$hue.getBoundingClientRect() const { y } = getMousePosition(e) this._isChoosing = true this._moveHueTo(y - hOffset.top) this._updateHueFromPosition() this._window.addEventListener('mouseup', this._onHueMouseUp) this._window.addEventListener('touchend', this._onHueMouseUp) this._window.addEventListener('mousemove', this._onHueMouseMove) this._window.addEventListener('touchmove', this._onHueMouseMove) e.preventDefault() } private _onHueMouseMove = e => { const hOffset = this.$hue.getBoundingClientRect() const { y } = getMousePosition(e) this._moveHueTo(y - hOffset.top) this._updateHueFromPosition() } private _onHueMouseUp = () => { this._isChoosing = false this._window.removeEventListener('mouseup', this._onHueMouseUp) this._window.removeEventListener('touchend', this._onHueMouseUp) this._window.removeEventListener('mousemove', this._onHueMouseMove) this._window.removeEventListener('touchmove', this._onHueMouseMove) } }
the_stack
import {Component, ViewChild} from '@angular/core'; import {Paginator} from "../../paginator"; import {Space, SpaceFilter} from "../../models"; import {Location} from "@angular/common"; import {MatDialog} from "@angular/material/dialog"; import {SpaceService} from "./space.service"; import {Helpers} from "../../helpers"; import {SpaceAddDialogComponent} from "./space-add-dialog"; import {MatTableDataSource} from "@angular/material/table"; import {MatPaginator} from "@angular/material/paginator"; import {MatSort} from "@angular/material/sort"; import {SpaceRunDialogComponent} from "./space-run-dialog"; import {COMMA, ENTER} from "@angular/cdk/keycodes"; import {MatChipInputEvent} from "@angular/material/chips"; import {MatAutocompleteSelectedEvent} from "@angular/material/autocomplete"; import {MatIconRegistry} from "@angular/material/icon"; import {DomSanitizer} from "@angular/platform-browser"; @Component({ selector: 'app-space', templateUrl: './space.component.html', styleUrls: ['./space.component.css'] }) export class SpaceComponent extends Paginator<Space> { displayed_columns: string[] = [ 'name', 'created', 'changed', 'tags' ]; filter_hidden: boolean = true; filter_applied_text: string = ''; name: string; selected: Space; relation_dataSource: MatTableDataSource<Space> = new MatTableDataSource(); relation_total: number = 0; @ViewChild('relation_paginator') relation_paginator: MatPaginator; @ViewChild('relation_sort') relation_sort: MatSort; relation_selected: Space; relation_filter_hidden: boolean = true; relation_filter_applied_text: string = ''; relation_name: string; separatorKeysCodes: number[] = [ENTER, COMMA]; tags: string[] = []; chosen_spaces = []; names: string[] = []; filter_tags: string[] = []; filter_all_tags: string[] = []; filter_tags_related: string[] = []; filter_all_tags_related: string[] = []; constructor( protected service: SpaceService, protected location: Location, public dialog: MatDialog, iconRegistry: MatIconRegistry, sanitizer: DomSanitizer ) { super(service, location); this.id_column = 'name'; iconRegistry.addSvgIcon('delete', sanitizer.bypassSecurityTrustResourceUrl( 'assets/img/delete.svg')); iconRegistry.addSvgIcon('pin', sanitizer.bypassSecurityTrustResourceUrl( 'assets/img/pin.svg')); } get chosen_spaces_or() { let res = []; for (let s of this.chosen_spaces) { if (s.type == 'tmp' || s.logic == 'or') { res.push(s); } } return res; } get chosen_spaces_and() { let res = []; for (let s of this.chosen_spaces) { if (s.type == 'tmp' || s.logic == 'and') { res.push(s); } } return res; } filter_remove_tag(tag) { let index = this.filter_tags.indexOf(tag); this.filter_tags.splice(index, 1); this.change.emit(); } filter_remove_tag_related(tag) { let index = this.filter_tags_related.indexOf(tag); this.filter_tags_related.splice(index, 1); this.relation_changed(); } filter_tag_add(event: MatChipInputEvent) { const input = event.input; let value = event.value; // Add our fruit if ((value || '').trim()) { value = value.trim(); this.filter_tags.push(value); } // Reset the input value if (input) { input.value = ''; } this.change.emit(); } filter_tag_add_related(event: MatChipInputEvent) { const input = event.input; let value = event.value; // Add our fruit if ((value || '').trim()) { value = value.trim(); this.filter_tags_related.push(value); } // Reset the input value if (input) { input.value = ''; } this.relation_changed(); } filter_tag_selected(event: MatAutocompleteSelectedEvent) { this.filter_tags.push(event.option.viewValue); this.change.emit(); } filter_tag_selected_related(event: MatAutocompleteSelectedEvent) { this.filter_tags_related.push(event.option.viewValue); this.relation_changed(); } chosen_remove_space(space) { let index = this.chosen_spaces.indexOf(space); this.chosen_spaces.splice(index, 1); } chosen_fix_space(logic) { for (let space of this.chosen_spaces) { if (space.type == 'tmp') { space.type = 'const'; space.logic = logic; } } } chosen_space_add(event: MatChipInputEvent) { const input = event.input; let value = event.value; if ((value || '').trim()) { value = value.trim(); this.chosen_spaces.push({ 'value': value, 'type': 'const', 'logic': 'or' }); } if (input) { input.value = ''; } } chosen_space_selected(event: MatAutocompleteSelectedEvent) { this.chosen_spaces.push({ 'value': event.option.viewValue, 'type': 'const', 'logic': 'or' }); } onchange() { this.change.emit(); let count = 0; if (this.name) count += 1; this.filter_applied_text = count > 0 ? `(${count} applied)` : ''; } get_filter(): any { let res = new SpaceFilter(); res.paginator = super.get_filter(); res.name = this.name; res.tags = this.filter_tags; return res; } protected _ngOnInit() { super._ngOnInit(); this.relation_paginator.page.subscribe(x => { this.relation_changed() }); this.relation_sort.sortChange.subscribe(x => { this.relation_changed() }); } update_tags(event = null) { let name = ''; if (event) { name = event.target.value; } this.service.tags({'name': name}).subscribe(x => { this.tags = x.tags; }) } update_names(event = null) { let name = ''; if (event) { name = event.target.value; } this.service.names({'name': name}).subscribe(x => { this.names = x.names; }) } update_filter_all_tags(event = null) { let name = ''; if (event) { name = event.target.value; } this.service.tags({'name': name}).subscribe(x => { this.filter_all_tags = x.tags; }) } update_filter_all_tags_related(event = null) { let name = ''; if (event) { name = event.target.value; } this.service.tags({'name': name}).subscribe(x => { this.filter_all_tags_related = x.tags; }) } run() { this.dialog.open(SpaceRunDialogComponent, { width: '2000px', height: '900px', data: {'spaces': this.chosen_spaces} }); } add() { const dialogRef = this.dialog.open(SpaceAddDialogComponent, { width: '1000px', height: '700px', data: {method: 'add', space: {'name': ''}} }); dialogRef.afterClosed().subscribe(result => { this.change.emit(); }); } edit() { const dialogRef = this.dialog.open(SpaceAddDialogComponent, { width: '1000px', height: '700px', data: {method: 'edit', space: Helpers.clone(this.selected)} }); dialogRef.afterClosed().subscribe(result => { this.change.emit(); }); } copy() { const dialogRef = this.dialog.open(SpaceAddDialogComponent, { width: '800px', height: '700px', data: { method: 'copy', space: Helpers.clone(this.selected), 'old_space': this.selected.name } }); dialogRef.afterClosed().subscribe(result => { this.change.emit(); }); } remove() { this.service.remove(this.selected.name).subscribe(result => { this.selected = null; this.relation_selected = null; this.relation_dataSource.data = []; this.relation_paginator.pageIndex = 0; this.change.emit(); }); } relation_changed() { if (!this.selected) { this.relation_dataSource.data = []; this.relation_total = 0; return; } let filter = { 'parent': this.selected.name, 'paginator': { 'page_number': this.relation_paginator.pageIndex, 'page_size': this.relation_paginator.pageSize, 'sort_column': this.relation_sort.active ? this.relation_sort.active : '', 'sort_descending': this.relation_sort.direction ? this.relation_sort.direction == 'desc' : true }, 'name': this.relation_name, 'tags': this.filter_tags_related }; this.service.get_paginator<Space>(filter).subscribe(res => { this.relation_dataSource.data = res.data; this.relation_total = res.total; }) } onSelected(row: Space, event: MouseEvent) { let spaces = [row]; if (event.shiftKey && this.selected) { let selected_index = this.dataSource.data.indexOf(this.selected); let row_index = this.dataSource.data.indexOf(row); if (selected_index >= 0 && row_index >= 0) { for (let i = selected_index + 1; i < row_index + 1; i++) { spaces.push(this.dataSource.data[i]); } } event.stopPropagation(); } for (let space of spaces) { if (this.chosen_spaces.length > 0 && !event.ctrlKey && !event.shiftKey) { let last_index = this.chosen_spaces.length - 1; if (this.chosen_spaces[last_index].type == 'tmp') { this.chosen_spaces.splice(last_index, 1); } } let found = false; for (let s of this.chosen_spaces) { if (s.value == space.name) { found = true; break } } if (!found) { this.chosen_spaces.push({ 'value': space.name, 'type': 'tmp', 'logic': 'or' }); } this.selected = space; this.relation_selected = null; this.relation_paginator.pageIndex = 0; } if (event.ctrlKey || event.shiftKey) { this.selected = null; } this.relation_changed(); } relation_append() { this.service.relation_append(this.selected.name, this.relation_selected.name).subscribe(res => { this.relation_changed() }); } relation_remove() { this.service.relation_remove(this.selected.name, this.relation_selected.name).subscribe(res => { this.relation_changed() }); } remove_tag(space: Space, tag: string) { this.service.tag_remove(space.name, tag).subscribe(res => { this.change.emit(); }); this.relation_changed(); } tag_add(space: Space, event: MatChipInputEvent) { const input = event.input; let value = event.value; // Add our fruit if ((value || '').trim()) { value = value.trim(); space.tags.push(value); this.service.tag_add(space.name, value).subscribe(res => { }); } // Reset the input value if (input) { input.value = ''; } this.relation_changed(); } tag_selected(space: Space, event: MatAutocompleteSelectedEvent) { this.service.tag_add(space.name, event.option.viewValue).subscribe(res => { }); space.tags.push(event.option.viewValue); this.relation_changed(); } }
the_stack
import { traverse } from "ast-monkey-traverse"; import matcher from "matcher"; import objectPath from "object-path"; import { arrayiffy } from "arrayiffy-if-string"; import { strFindHeadsTails } from "string-find-heads-tails"; import { getByKey } from "ast-get-values-by-key"; import { Ranges } from "ranges-push"; import { rApply } from "ranges-apply"; import { remDup } from "string-remove-duplicate-heads-tails"; import { matchLeftIncl, matchRightIncl } from "string-match-left-right"; import { version as v } from "../package.json"; const version: string = v; const has = Object.prototype.hasOwnProperty; interface Obj { [key: string]: any; } interface Opts { heads: string; tails: string; headsNoWrap: string; tailsNoWrap: string; lookForDataContainers: boolean; dataContainerIdentifierTails: string; wrapHeadsWith: string | string[]; wrapTailsWith: string | string[]; dontWrapVars: string[]; preventDoubleWrapping: boolean; wrapGlobalFlipSwitch: boolean; noSingleMarkers: boolean; resolveToBoolIfAnyValuesContainBool: boolean; resolveToFalseIfAnyValuesContainBool: boolean; throwWhenNonStringInsertedInString: boolean; allowUnresolved: boolean; } const defaults: Opts = { heads: "%%_", tails: "_%%", headsNoWrap: "%%-", tailsNoWrap: "-%%", lookForDataContainers: true, dataContainerIdentifierTails: "_data", wrapHeadsWith: "", wrapTailsWith: "", dontWrapVars: [], preventDoubleWrapping: true, wrapGlobalFlipSwitch: true, // is wrap function on? noSingleMarkers: false, // if value has only and exactly heads or tails, // don't throw mismatched marker error. resolveToBoolIfAnyValuesContainBool: true, // if variable is resolved into // anything that contains or is equal to Boolean false, set the whole thing to false resolveToFalseIfAnyValuesContainBool: true, // resolve whole value to false, // even if some values contain Boolean true. Otherwise, the whole value will // resolve to the first encountered Boolean. throwWhenNonStringInsertedInString: false, allowUnresolved: false, // Allow value to not have a resolved variable }; // ----------------------------------------------------------------------------- // H E L P E R F U N C T I O N S // ----------------------------------------------------------------------------- function isStr(something: any): boolean { return typeof something === "string"; } function isNum(something: any): boolean { return typeof something === "number"; } function isBool(something: any): boolean { return typeof something === "boolean"; } function isNull(something: any): boolean { return something === null; } function isObj(something: any): boolean { return ( something && typeof something === "object" && !Array.isArray(something) ); } function existy(x: any): boolean { return x != null; } // TS overloading function trimIfString(something: string): string; function trimIfString(something: any): any { return isStr(something) ? something.trim() : something; } function getTopmostKey(str: string): string { if (typeof str === "string" && str.length > 0 && str.indexOf(".") !== -1) { for (let i = 0, len = str.length; i < len; i++) { if (str[i] === ".") { return str.slice(0, i); } } } return str; } function withoutTopmostKey(str: string): string { if (typeof str === "string" && str.length > 0 && str.indexOf(".") !== -1) { for (let i = 0, len = str.length; i < len; i++) { if (str[i] === ".") { return str.slice(i + 1); } } } return str; } function goLevelUp(str: string): string { if (typeof str === "string" && str.length > 0 && str.indexOf(".") !== -1) { for (let i = str.length; i--; ) { if (str[i] === ".") { return str.slice(0, i); } } } return str; } function getLastKey(str: string): string { if (typeof str === "string" && str.length > 0 && str.indexOf(".") !== -1) { for (let i = str.length; i--; ) { if (str[i] === ".") { return str.slice(i + 1); } } } return str; } function containsHeadsOrTails(str: string, opts: Opts): boolean { if (typeof str !== "string" || !str.trim()) { return false; } if ( str.includes(opts.heads) || str.includes(opts.tails) || (isStr(opts.headsNoWrap) && opts.headsNoWrap.length > 0 && str.includes(opts.headsNoWrap)) || (isStr(opts.tailsNoWrap) && opts.tailsNoWrap.length > 0 && str.includes(opts.tailsNoWrap)) ) { return true; } return false; } function removeWrappingHeadsAndTails( str: string, heads: string | string[], tails: string | string[] ) { let tempFrom; let tempTo; if ( typeof str === "string" && str.length > 0 && matchRightIncl(str, 0, heads, { trimBeforeMatching: true, cb: (_c, _t, index) => { tempFrom = index; return true; }, }) && matchLeftIncl(str, str.length - 1, tails, { trimBeforeMatching: true, cb: (_c, _t, index) => { tempTo = (index as any) + 1; return true; }, }) ) { return str.slice(tempFrom, tempTo); } return str; } function wrap( placementValue: string, opts: Opts, dontWrapTheseVars = false, breadCrumbPath: string[], newPath: string, oldVarName: string ) { console.log( `191 >>>>>>>>>> WRAP(): placementValue = ${JSON.stringify( placementValue, null, 4 )}` ); console.log( `198 >>>>>>>>>> WRAP(): breadCrumbPath = ${JSON.stringify( breadCrumbPath, null, 4 )}` ); console.log( `205 >>>>>>>>>> WRAP(): newPath = ${JSON.stringify(newPath, null, 4)}` ); console.log( `208 >>>>>>>>>> WRAP(): oldVarName = ${JSON.stringify( oldVarName, null, 4 )}\n` ); // opts validation if (!opts.wrapHeadsWith) { // eslint-disable-next-line no-param-reassign opts.wrapHeadsWith = ""; } if (!opts.wrapTailsWith) { // eslint-disable-next-line no-param-reassign opts.wrapTailsWith = ""; } // main opts if ( isStr(placementValue) && !dontWrapTheseVars && opts.wrapGlobalFlipSwitch && !opts.dontWrapVars.some((val) => matcher.isMatch(oldVarName, val)) && // considering double-wrapping prevention setting: (!opts.preventDoubleWrapping || (opts.preventDoubleWrapping && isStr(placementValue) && !placementValue.includes(opts.wrapHeadsWith as string) && !placementValue.includes(opts.wrapTailsWith as string))) ) { console.log("238 +++ WE GONNA WRAP THIS!"); return opts.wrapHeadsWith + placementValue + opts.wrapTailsWith; } if (dontWrapTheseVars) { console.log("\n\n\n242 💥💥💥💥💥💥 !!! dontWrapTheseVars is ON!!!\n\n\n"); console.log( `244 placementValue = ${JSON.stringify(placementValue, null, 4)}` ); console.log( `247 opts.wrapHeadsWith = ${JSON.stringify(opts.wrapHeadsWith, null, 4)}` ); console.log( `250 opts.wrapTailsWith = ${JSON.stringify(opts.wrapTailsWith, null, 4)}` ); console.log( `254 about to return:\n${JSON.stringify( remDup(placementValue, { heads: opts.wrapHeadsWith, tails: opts.wrapTailsWith, }), null, 4 )}` ); console.log( `264 \u001b[${36}m placementValue = ${JSON.stringify( placementValue, null, 4 )}\u001b[${39}m` ); if (!isStr(placementValue)) { console.log(`271 Returning placementValue = ${placementValue}`); return placementValue; } const tempValue = remDup(placementValue, { heads: opts.wrapHeadsWith, tails: opts.wrapTailsWith, }); if (!isStr(tempValue)) { return tempValue; } return removeWrappingHeadsAndTails( tempValue, opts.wrapHeadsWith, opts.wrapTailsWith ); } console.log("287 +++ NO WRAP"); return placementValue; } function findValues(input: any, varName: string, path: string, opts: Opts) { console.log( `292 findValues(): looking for varName = ${JSON.stringify( varName, null, 4 )}` ); console.log(`298 path = ${JSON.stringify(path, null, 4)}\n\n`); let resolveValue; // 1.1. first, traverse up to root level, looking for key right at that level // or within data store, respecting the config if (path.indexOf(".") !== -1) { let currentPath = path; // traverse upwards: let handBrakeOff = true; // first, check the current level's datastore: if ( opts.lookForDataContainers && typeof opts.dataContainerIdentifierTails === "string" && opts.dataContainerIdentifierTails.length > 0 && !currentPath.endsWith(opts.dataContainerIdentifierTails) ) { // 1.1.1. first check data store console.log("315: 1.1.0."); console.log( `\n256 * datastore = ${JSON.stringify( currentPath + opts.dataContainerIdentifierTails, null, 4 )}` ); const gotPath = objectPath.get( input, currentPath + opts.dataContainerIdentifierTails ); console.log(`327 * gotPath = ${JSON.stringify(gotPath, null, 4)}`); if (isObj(gotPath) && objectPath.get(gotPath, varName)) { console.log(`329 FOUND!\n${gotPath[varName]}`); resolveValue = objectPath.get(gotPath, varName); handBrakeOff = false; } } // then, start traversing up: while (handBrakeOff && currentPath.indexOf(".") !== -1) { currentPath = goLevelUp(currentPath); if (getLastKey(currentPath) === varName) { throw new Error( `json-variables/findValues(): [THROW_ID_20] While trying to resolve: "${varName}" at path "${path}", we encountered a closed loop. The parent key "${getLastKey( currentPath )}" is called the same as the variable "${varName}" we're looking for.` ); } console.log(`345 traversing up. Currently at: ${currentPath}`); // first, check the current level's datastore: if ( opts.lookForDataContainers && typeof opts.dataContainerIdentifierTails === "string" && opts.dataContainerIdentifierTails.length > 0 && !currentPath.endsWith(opts.dataContainerIdentifierTails) ) { // 1.1.1. first check data store console.log("355: 1.1.1."); console.log( `\n296 * datastore = ${JSON.stringify( currentPath + opts.dataContainerIdentifierTails, null, 4 )}` ); const gotPath = objectPath.get( input, currentPath + opts.dataContainerIdentifierTails ); console.log(`367 * gotPath = ${JSON.stringify(gotPath, null, 4)}`); if (isObj(gotPath) && objectPath.get(gotPath, varName)) { console.log(`369 FOUND!\n${gotPath[varName]}`); resolveValue = objectPath.get(gotPath, varName); handBrakeOff = false; } } if (resolveValue === undefined) { console.log("376 1.1.2."); // 1.1.2. second check for key straight in parent level const gotPath = objectPath.get(input, currentPath); console.log(`379 gotPath = ${JSON.stringify(gotPath, null, 4)}`); if (isObj(gotPath) && objectPath.get(gotPath, varName)) { console.log( `382 SUCCESS! currentPath = ${JSON.stringify( currentPath, null, 4 )} has key ${varName}` ); resolveValue = objectPath.get(gotPath, varName); handBrakeOff = false; } } } } // 1.2. Reading this point means that maybe we were already at the root level, // maybe we traversed up to root and couldn't resolve anything. // Either way, let's check keys and data store at the root level: if (resolveValue === undefined) { console.log("398 check the root"); const gotPath = objectPath.get(input, varName); console.log(`400 ROOT's gotPath = ${JSON.stringify(gotPath, null, 4)}`); if (gotPath !== undefined) { console.log(`402 SET resolveValue = ${JSON.stringify(gotPath, null, 4)}`); resolveValue = gotPath; } } // 1.3. Last resort, just look for key ANYWHERE, as long as it's named as // our variable name's topmost key (if it's a path with dots) or equal to key entirely (no dots) if (resolveValue === undefined) { console.log(`409 search for key: ${getTopmostKey(varName)}`); // 1.3.1. It depends, does the varName we're looking for have dot or not. // - Because if it does, it's a path and we'll have to split the search into two // parts: first find topmost key, then query it's children path part via // object-path. // - If it does not have a dot, it's straightforward, pick first string // finding out of getByKey(). // it's not a path (does not contain dots) if (varName.indexOf(".") === -1) { const gotPathArr = getByKey(input, varName); console.log( `422 *** gotPathArr = ${JSON.stringify(gotPathArr, null, 4)}` ); if (gotPathArr.length > 0) { for (let y = 0, len2 = gotPathArr.length; y < len2; y++) { if ( isStr(gotPathArr[y].val) || isBool(gotPathArr[y].val) || isNull(gotPathArr[y].val) ) { resolveValue = gotPathArr[y].val; console.log( `433 resolveValue = ${JSON.stringify(resolveValue, null, 4)}` ); break; } else if (isNum(gotPathArr[y].val)) { resolveValue = String(gotPathArr[y].val); console.log( `439 resolveValue = ${JSON.stringify(resolveValue, null, 4)}` ); break; } else if (Array.isArray(gotPathArr[y].val)) { resolveValue = gotPathArr[y].val.join(""); console.log( `445 resolveValue = ${JSON.stringify(resolveValue, null, 4)}` ); break; } else { throw new Error( `json-variables/findValues(): [THROW_ID_21] While trying to resolve: "${varName}" at path "${path}", we actually found the key named ${varName}, but it was not equal to a string but to:\n${JSON.stringify( gotPathArr[y], null, 4 )}\nWe can't resolve a string with that! It should be a string.` ); } } } } else { // it's a path (contains dots) const gotPath = getByKey(input, getTopmostKey(varName)); console.log(`462 *** gotPath = ${JSON.stringify(gotPath, null, 4)}`); if (gotPath.length > 0) { for (let y = 0, len2 = gotPath.length; y < len2; y++) { const temp = objectPath.get( gotPath[y].val, withoutTopmostKey(varName) ); if (temp && isStr(temp)) { resolveValue = temp; } } } } } console.log(`476 findValues(): FINAL RETURN: ${resolveValue}\n`); return resolveValue; } // Explanation of the resolveString() function's inputs. // Heads or tails were detected in the "string", which is located in the "path" // within "input" (JSON object normally, an AST). All the settings are in "opts". // Since this function will be called recursively, we have to keep a breadCrumbPath - // all keys visited so far and always check, was the current key not been // traversed already (present in breadCrumbPath). Otherwise, we might get into a // closed loop. function resolveString( input: any, string: string, path: string, opts: Opts, incomingBreadCrumbPath: string[] = [] ) { console.log( `\u001b[${33}m${`\n\n429 CALLED resolveString() on "${string}". Path = "${path}"`}\u001b[${39}m` ); console.log( `499 incomingBreadCrumbPath = ${JSON.stringify( incomingBreadCrumbPath, null, 4 )}` ); // precautions from recursion if (incomingBreadCrumbPath.includes(path)) { let extra = ""; if (incomingBreadCrumbPath.length > 1) { // extra = ` Here's the path we travelled up until we hit the recursion: ${incomingBreadCrumbPath.join(' - ')}.` const separator = " →\n"; extra = incomingBreadCrumbPath.reduce( (accum, curr, idx) => accum + (idx === 0 ? "" : separator) + (curr === path ? "💥 " : " ") + curr, " Here's the path we travelled up until we hit the recursion:\n\n" ); extra += `${separator}💥 ${path}`; } throw new Error( `json-variables/resolveString(): [THROW_ID_19] While trying to resolve: "${string}" at path "${path}", we encountered a closed loop, the key is referencing itself."${extra}` ); } // The Secret Data Stash, a way to cache previously resolved values and reuse the // values, saving resources. It can't be on the root because it would get retained // between different calls on the library, potentially giving wrong results (from // the previous resolved variable, from the previous function call). const secretResolvedVarsStash: Obj = {}; console.log( `=============================\n468 string = ${JSON.stringify( string, null, 4 )}` ); // 0. Add current path into breadCrumbPath // ======================================= const breadCrumbPath = Array.from(incomingBreadCrumbPath); breadCrumbPath.push(path); // 1. First, extract all vars // ========================== const finalRangesArr = new Ranges(); function processHeadsAndTails( arr: Obj[], dontWrapTheseVars: boolean, wholeValueIsVariable: boolean ) { for (let i = 0, len = arr.length; i < len; i++) { const obj = arr[i]; console.log( `\u001b[${33}m${`490 obj = ${JSON.stringify( obj, null, 4 )}`}\u001b[${39}m` ); const varName = string.slice(obj.headsEndAt, obj.tailsStartAt); console.log( `569 ${`\u001b[${33}m${`varName`}\u001b[${39}m`} = ${JSON.stringify( varName, null, 4 )}` ); if (varName.length === 0) { finalRangesArr.push( obj.headsStartAt, // replace from index obj.tailsEndAt // replace upto index - no third argument, just deletion of heads/tails ); } else if ( has.call(secretResolvedVarsStash, varName) && isStr(secretResolvedVarsStash[varName]) ) { // check, maybe the value was already resolved before and present in secret stash: console.log("585 Yay! Value taken from stash!"); finalRangesArr.push( obj.headsStartAt, // replace from index obj.tailsEndAt, // replace upto index secretResolvedVarsStash[varName] // replacement value ); } else { // it's not in the stash unfortunately, so let's search for it then: let resolvedValue = findValues( input, // input varName.trim(), // varName path, // path opts // opts ); if (resolvedValue === undefined) { if (opts.allowUnresolved === true) { resolvedValue = ""; } else if (typeof opts.allowUnresolved === "string") { resolvedValue = opts.allowUnresolved; } else { throw new Error( `json-variables/processHeadsAndTails(): [THROW_ID_18] We couldn't find the value to resolve the variable ${string.slice( obj.headsEndAt, obj.tailsStartAt )}. We're at path: "${path}".` ); } } if ( !wholeValueIsVariable && opts.throwWhenNonStringInsertedInString && !isStr(resolvedValue) ) { throw new Error( `json-variables/processHeadsAndTails(): [THROW_ID_23] While resolving the variable ${string.slice( obj.headsEndAt, obj.tailsStartAt )} at path ${path}, it resolved into a non-string value, ${JSON.stringify( resolvedValue, null, 4 )}. This is happening because options setting "throwWhenNonStringInsertedInString" is active (set to "true").` ); } if (isBool(resolvedValue)) { if (opts.resolveToBoolIfAnyValuesContainBool) { finalRangesArr.wipe(); if (!opts.resolveToFalseIfAnyValuesContainBool) { return resolvedValue; } return false; } resolvedValue = ""; } else if (isNull(resolvedValue) && wholeValueIsVariable) { finalRangesArr.wipe(); return resolvedValue; } else if (Array.isArray(resolvedValue)) { resolvedValue = String(resolvedValue.join("")); } else if (isNull(resolvedValue)) { resolvedValue = ""; } else { resolvedValue = String(resolvedValue); } console.log( `* 574 resolvedValue = ${JSON.stringify(resolvedValue, null, 4)}` ); console.log(`* 576 path = ${JSON.stringify(path, null, 4)}`); console.log(`* 577 varName = ${JSON.stringify(varName, null, 4)}`); const newPath = path.includes(".") ? `${goLevelUp(path)}.${varName}` : varName; console.log(`* 582 newPath = ${JSON.stringify(newPath, null, 4)}`); if (containsHeadsOrTails(resolvedValue, opts)) { const replacementVal = wrap( resolveString( // replacement value <--------- R E C U R S I O N input, resolvedValue, newPath, opts, breadCrumbPath ), opts, dontWrapTheseVars, breadCrumbPath, newPath, varName.trim() ); if (isStr(replacementVal)) { finalRangesArr.push( obj.headsStartAt, // replace from index obj.tailsEndAt, // replace upto index replacementVal ); } } else { // 1. store it in the stash for the future secretResolvedVarsStash[varName] = resolvedValue; const replacementVal = wrap( resolvedValue, opts, dontWrapTheseVars, breadCrumbPath, newPath, varName.trim() ); // replacement value if (isStr(replacementVal)) { // 2. submit to be replaced finalRangesArr.push( obj.headsStartAt, // replace from index obj.tailsEndAt, // replace upto index replacementVal ); } } } } return undefined; } let foundHeadsAndTails; // reusing same var as container for both wrapping- and non-wrapping types // 1. normal (possibly wrapping-type) heads and tails try { // strFindHeadsTails() can throw as well if there's mismatch in heads and tails, // for example, so it needs to be contained: foundHeadsAndTails = strFindHeadsTails(string, opts.heads, opts.tails, { source: "", throwWhenSomethingWrongIsDetected: false, }); } catch (error) { throw new Error( `json-variables/resolveString(): [THROW_ID_17] While trying to resolve string: "${string}" at path ${path}, something wrong with heads and tails was detected! Here's the internal error message:\n${error}` ); } console.log( `${`\u001b[${36}m${"694 foundHeadsAndTails = "}\u001b[${39}m`} ${JSON.stringify( foundHeadsAndTails, null, 4 )}` ); console.log( `\u001b[${36}m${`654 string.length = ${string.length}`}\u001b[${39}m` ); // if heads and tails array has only one range inside and it spans whole string's // length, this means key is equal to a whole variable, like {a: '%%_b_%%'}. // In those cases, there are extra considerations when value is null, because // null among string characters is resolved to empty string, but null as a whole // value is retained as null. This means, we need to pass this as a flag to // processHeadsAndTails() so it can resolve properly... let wholeValueIsVariable = false; // we'll reuse it for non-wrap heads/tails too if ( foundHeadsAndTails.length === 1 && rApply(string, [ [foundHeadsAndTails[0].headsStartAt, foundHeadsAndTails[0].tailsEndAt], ]).trim() === "" ) { wholeValueIsVariable = true; } const temp1 = processHeadsAndTails( foundHeadsAndTails, false, wholeValueIsVariable ); if (isBool(temp1)) { return temp1; } if (isNull(temp1)) { return temp1; } // 2. Process opts.headsNoWrap, opts.tailsNoWrap as well try { // strFindHeadsTails() can throw as well if there's mismatch in heads and tails, // for example, so it needs to be contained: foundHeadsAndTails = strFindHeadsTails( string, opts.headsNoWrap, opts.tailsNoWrap, { source: "", throwWhenSomethingWrongIsDetected: false, } ); } catch (error) { throw new Error( `json-variables/resolveString(): [THROW_ID_22] While trying to resolve string: "${string}" at path ${path}, something wrong with no-wrap heads and no-wrap tails was detected! Here's the internal error message:\n${error}` ); } if ( foundHeadsAndTails.length === 1 && rApply(string, [ [foundHeadsAndTails[0].headsStartAt, foundHeadsAndTails[0].tailsEndAt], ]).trim() === "" ) { wholeValueIsVariable = true; } const temp2 = processHeadsAndTails( foundHeadsAndTails, true, wholeValueIsVariable ); if (isBool(temp2)) { return temp2; } if (isNull(temp2)) { return temp2; } console.log(`804 temp2 = ${JSON.stringify(temp2, null, 4)}`); // 3. Then, work the finalRangesArr list // ================================ console.log( `\u001b[${33}m${`\n729 END OF rApply: finalRangesArr.current() = ${JSON.stringify( finalRangesArr.current(), null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${33}m${`\n736 string was = ${JSON.stringify( string, null, 4 )}`}\u001b[${39}m` ); if (finalRangesArr && finalRangesArr.current()) { return rApply(string, finalRangesArr.current()); } return string; } // ----------------------------------------------------------------------------- // M A I N F U N C T I O N // ----------------------------------------------------------------------------- /** * Resolves custom-marked, cross-referenced paths in parsed JSON */ function jVar(input: Obj, originalOpts?: Partial<Opts>): Obj { if (!arguments.length) { throw new Error( "json-variables/jVar(): [THROW_ID_01] Alas! Inputs are missing!" ); } if (!isObj(input)) { throw new TypeError( `json-variables/jVar(): [THROW_ID_02] Alas! The input must be a plain object! Currently it's: ${ Array.isArray(input) ? "array" : typeof input }` ); } if (originalOpts && !isObj(originalOpts)) { throw new TypeError( `json-variables/jVar(): [THROW_ID_03] Alas! An Optional Options Object must be a plain object! Currently it's: ${ Array.isArray(originalOpts) ? "array" : typeof originalOpts }` ); } const opts: Opts = { ...defaults, ...originalOpts }; if (!opts.dontWrapVars) { opts.dontWrapVars = []; } else if (!Array.isArray(opts.dontWrapVars)) { opts.dontWrapVars = arrayiffy(opts.dontWrapVars); } let culpritVal; let culpritIndex; if ( opts.dontWrapVars.length > 0 && !opts.dontWrapVars.every((el, idx) => { if (!isStr(el)) { culpritVal = el; culpritIndex = idx; return false; } return true; }) ) { throw new Error( `json-variables/jVar(): [THROW_ID_05] Alas! All variable names set in opts.dontWrapVars should be of a string type. Computer detected a value "${culpritVal}" at index ${culpritIndex}, which is not string but ${ Array.isArray(culpritVal) ? "array" : typeof culpritVal }!` ); } if (opts.heads === "") { throw new Error( "json-variables/jVar(): [THROW_ID_06] Alas! opts.heads are empty!" ); } if (opts.tails === "") { throw new Error( "json-variables/jVar(): [THROW_ID_07] Alas! opts.tails are empty!" ); } if (opts.lookForDataContainers && opts.dataContainerIdentifierTails === "") { throw new Error( "json-variables/jVar(): [THROW_ID_08] Alas! opts.dataContainerIdentifierTails is empty!" ); } if (opts.heads === opts.tails) { throw new Error( "json-variables/jVar(): [THROW_ID_09] Alas! opts.heads and opts.tails can't be equal!" ); } if (opts.heads === opts.headsNoWrap) { throw new Error( "json-variables/jVar(): [THROW_ID_10] Alas! opts.heads and opts.headsNoWrap can't be equal!" ); } if (opts.tails === opts.tailsNoWrap) { throw new Error( "json-variables/jVar(): [THROW_ID_11] Alas! opts.tails and opts.tailsNoWrap can't be equal!" ); } if (opts.headsNoWrap === "") { throw new Error( "json-variables/jVar(): [THROW_ID_12] Alas! opts.headsNoWrap is an empty string!" ); } if (opts.tailsNoWrap === "") { throw new Error( "json-variables/jVar(): [THROW_ID_13] Alas! opts.tailsNoWrap is an empty string!" ); } if (opts.headsNoWrap === opts.tailsNoWrap) { throw new Error( "json-variables/jVar(): [THROW_ID_14] Alas! opts.headsNoWrap and opts.tailsNoWrap can't be equal!" ); } let current; console.log("======== JSON VARIABLES START ========"); console.log(`input = ${JSON.stringify(input, null, 4)}`); console.log(`opts = ${JSON.stringify(opts, null, 4)}`); console.log("======== JSON VARIABLES END ========"); // // =============================================== // 1. // Let's compile the list of all the vars to resolve // =============================================== // // we return the result of the traversal: return traverse(input, (key, val, innerObj) => { console.log("\n========================================"); if (existy(val) && containsHeadsOrTails(key, opts)) { throw new Error( `json-variables/jVar(): [THROW_ID_15] Alas! Object keys can't contain variables!\nPlease check the following key: ${key}` ); } // * * * // Get the current values which are being traversed by ast-monkey: // If it's an array, val will not exist, only key. if (val !== undefined) { // if it's object currently being traversed, we'll get both key and value current = val; } else { // if it's an array being traversed currently, we'll get only key current = key; } // * * * // In short, ast-monkey works in such way, that what we return will get written // over the current element, which is at the moment "current". If we don't want // to mutate it, we return "current". If we want to mutate it, we return a new // value (which will get written onto that node, previously equal to "current"). console.log(`969 current = ${JSON.stringify(current, null, 4)}`); // * // Instantly skip empty strings: if (current === "") { return current; } // * // If the "current" that monkey brought us is equal to whole heads or tails: if ( (opts.heads.length !== 0 && trimIfString(current) === trimIfString(opts.heads)) || (opts.tails.length !== 0 && trimIfString(current) === trimIfString(opts.tails)) || (opts.headsNoWrap.length !== 0 && trimIfString(current) === trimIfString(opts.headsNoWrap)) || (opts.tailsNoWrap.length !== 0 && trimIfString(current) === trimIfString(opts.tailsNoWrap)) ) { if (!opts.noSingleMarkers) { return current; } throw new Error( `json-variables/jVar(): [THROW_ID_16] Alas! While processing the input, we stumbled upon ${trimIfString( current )} which is equal to ${ trimIfString(current) === trimIfString(opts.heads) ? "heads" : "" }${trimIfString(current) === trimIfString(opts.tails) ? "tails" : ""}${ isStr(opts.headsNoWrap) && trimIfString(current) === trimIfString(opts.headsNoWrap) ? "headsNoWrap" : "" }${ isStr(opts.tailsNoWrap) && trimIfString(current) === trimIfString(opts.tailsNoWrap) ? "tailsNoWrap" : "" }. If you wouldn't have set opts.noSingleMarkers to "true" this error would not happen and computer would have left the current element (${trimIfString( current )}) alone` ); } console.log(`\n953 current = ${JSON.stringify(current, null, 4)}`); // * // Process the current node if it's a string and it contains heads / tails / // headsNoWrap / tailsNoWrap: if (isStr(current) && containsHeadsOrTails(current, opts)) { // breadCrumbPath, the fifth argument is not passed as there're no previous paths return resolveString(input, current, innerObj.path, opts); } // otherwise, just return as it is. We're not going to touch plain objects/arrays,numbers/bools etc. return current; // END OF MONKEY'S TRAVERSE // ------------------------------------------------------------------------- }); } export { jVar, defaults, version };
the_stack
import type { DeckDeclaration } from "../src/Deck"; import { Deck } from "../src/Deck"; import type { ShapeRenderable } from "kittik-shape-basic"; import { Shape } from "kittik-shape-basic"; import type { Animationable } from "kittik-animation-basic"; import { Canvas } from "terminal-canvas"; import { Print } from "kittik-animation-print"; import { Slide } from "kittik-slide"; const DECK_DECLARATION: DeckDeclaration = { shapes: [ { name: "Global Shape", type: "Text", options: { text: "Hello, World!", }, }, ], animations: [ { name: "Global Animation", type: "Print", options: { duration: 1, }, }, ], slides: [ { name: "Global Animation", shapes: [], order: [ { shape: "Global Shape", animations: ["Global Animation"], }, ], }, { name: "Global Animation 2", shapes: [], order: [ { shape: "Global Shape", animations: ["Global Animation"], }, ], }, ], }; describe("deck", () => { it("should properly handle the key press for previous slide", async () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck(DECK_DECLARATION, canvas); const renderSpy = jest.spyOn(deck, "render").mockResolvedValue(true); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); await deck.nextSlide(); process.stdin.emit("keypress", "p"); expect(renderSpy).toHaveBeenCalledTimes(2); expect(renderSpy).toHaveBeenCalledWith(1); expect(renderSpy).toHaveBeenCalledWith(0); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly handle the key press for next slide", () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck(DECK_DECLARATION, canvas); const renderSpy = jest.spyOn(deck, "render").mockResolvedValue(true); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); process.stdin.emit("keypress", "n"); expect(renderSpy).toHaveBeenCalledTimes(1); expect(renderSpy).toHaveBeenCalledWith(1); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly handle the key press for exit", () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck(DECK_DECLARATION, canvas); const exitSpy = jest.spyOn(deck, "exit").mockImplementationOnce(() => true); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); process.stdin.emit("keypress", "q"); expect(exitSpy).toHaveBeenCalledTimes(1); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should do nothing when unknown key has been pressed", () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck(DECK_DECLARATION, canvas); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); expect(process.stdin.emit("keypress", "?")).toBe(true); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly render next and previous slides", async () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck(DECK_DECLARATION, canvas); const renderSpy = jest.spyOn(deck, "render").mockResolvedValue(true); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); await deck.nextSlide(); await deck.previousSlide(); expect(renderSpy).toHaveBeenCalledTimes(2); expect(renderSpy).toHaveBeenCalledWith(1); expect(renderSpy).toHaveBeenCalledWith(0); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly render slides without custom canvas", async () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck({ ...DECK_DECLARATION }, canvas); const renderSpy = jest.spyOn(deck, "render").mockResolvedValue(true); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); await deck.nextSlide(); await deck.previousSlide(); expect(renderSpy).toHaveBeenCalledTimes(2); expect(renderSpy).toHaveBeenCalledWith(1); expect(renderSpy).toHaveBeenCalledWith(0); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly render minimal slide without global shapes/animations", async () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck( { slides: [ { name: "Test", shapes: [], order: [], }, { name: "Test 2", shapes: [], order: [], animations: [], }, ], }, canvas ); const renderSpy = jest.spyOn(deck, "render").mockResolvedValue(true); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); await deck.nextSlide(); await deck.previousSlide(); expect(renderSpy).toHaveBeenCalledTimes(2); expect(renderSpy).toHaveBeenCalledWith(1); expect(renderSpy).toHaveBeenCalledWith(0); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should not call slide renderer many times if slide is already rendering", () => { expect.hasAssertions(); const canvas = Canvas.create(); const deck = new Deck( { slides: [{ name: "Test", shapes: [], order: [] }], }, canvas ); /* * Though, slides is a private property, I need to access it anyway in sake of the tests * This is done to test if slides render() behaves as expected */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error const renderSpy = jest.spyOn(deck.slides[0], "render"); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); deck.render(); // eslint-disable-line @typescript-eslint/no-floating-promises deck.render(); // eslint-disable-line @typescript-eslint/no-floating-promises deck.render(); // eslint-disable-line @typescript-eslint/no-floating-promises deck.render(); // eslint-disable-line @typescript-eslint/no-floating-promises expect(renderSpy).toHaveBeenCalledTimes(1); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(0); }); it("should properly add a shape to all the slides in the deck", () => { expect.hasAssertions(); const canvas = Canvas.create(); const shape: ShapeRenderable = new Shape(); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); const deck = new Deck( { slides: [ { name: "Test", shapes: [{ name: "Shape", type: "Text" as const, options: {} }], order: [], }, ], }, canvas ); deck.addShape("Shape 2", shape); // I am accessing the private property to check if there is actually a new shape exists // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error expect(deck.slides[0].shapes.size).toBe(2); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly throw an error if shape already exists in other slides", () => { expect.hasAssertions(); const canvas = Canvas.create(); const shape: ShapeRenderable = new Shape(); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); const deck = new Deck( { slides: [ { name: "Test", shapes: [{ name: "Shape", type: "Text" as const, options: {} }], order: [], }, ], }, canvas ); expect(() => { deck.addShape("Shape", shape); }).toThrow( 'You are trying to add a shape with the name "Shape" into the deck. ' + "When adding a shape into the deck, actually it adds the shape to all the slides in the deck. " + 'That is why we can not add the shape "Shape" to the deck, some of the slides already have it. ' + "Remove the shape from the slides [Test] or rename the shape." ); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly add an animation to all the slides in the deck", () => { expect.hasAssertions(); const canvas = Canvas.create(); const animation: Animationable = new Print(); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); const deck = new Deck( { slides: [ { name: "Test", shapes: [], order: [], animations: [ { name: "Animation", type: "Print" as const, options: {} }, ], }, ], }, canvas ); deck.addAnimation("Animation 2", animation); // I am accessing the private property to check if there is actually a new animation exists // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error expect(deck.slides[0].animations.size).toBe(2); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly throw an error if animation already exists in other slides", () => { expect.hasAssertions(); const canvas = Canvas.create(); const animation: Animationable = new Print(); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); const deck = new Deck( { slides: [ { name: "Test", shapes: [], order: [], animations: [ { name: "Animation", type: "Print" as const, options: {} }, ], }, ], }, canvas ); expect(() => { deck.addAnimation("Animation", animation); }).toThrow( 'You are trying to add an animation with the name "Animation" into the deck. ' + "When adding an animation into the deck, actually it adds the animation to all the slides in the deck. " + 'That is why we can not add the animation "Animation" to the deck, some of the slides already have it. ' + "Remove the animations from the slides [Test] or rename the animation." ); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); it("should properly throw an error if name of the slide already exists in the deck", () => { expect.hasAssertions(); const canvas = Canvas.create(); const resetSpy = jest.spyOn(canvas, "reset").mockReturnThis(); const deck = new Deck( { slides: [ { name: "Slide #1", shapes: [], order: [], }, ], }, canvas ); const slide = new Slide(); slide.name = "Slide #1"; expect(() => { deck.addSlide(slide); }).toThrow( 'You are trying to add a slide with the name "Slide #1" into the deck. ' + "But the slide with the same name already exists there. " + 'Remove the slide "Slide #1" from the deck or rename the slide you tried to add.' ); deck.exit(); expect(resetSpy).toHaveBeenCalledTimes(1); }); });
the_stack
import insertText, { SelectionRange } from './insertText'; interface StyleArgs { prefix: string; suffix: string; blockPrefix: string; blockSuffix: string; multiline: boolean; replaceNext: string; prefixSpace: boolean; scanFor: string; surroundWithNewlines: boolean; orderedList: boolean; unorderedList: boolean; trimFirst: boolean; } const defaults: StyleArgs = { prefix: '', suffix: '', blockPrefix: '', blockSuffix: '', multiline: false, replaceNext: '', prefixSpace: false, scanFor: '', surroundWithNewlines: false, orderedList: false, unorderedList: false, trimFirst: false, }; export default function styleSelectedText(textarea: HTMLTextAreaElement, styleArgs: StyleArgs) { // Next 2 lines are added textarea.focus(); styleArgs = Object.assign({}, defaults, styleArgs); // Prev 2 lines are added const text = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd); let result; if (styleArgs.orderedList || styleArgs.unorderedList) { result = listStyle(textarea, styleArgs); } else if (styleArgs.multiline && isMultipleLines(text)) { result = multilineStyle(textarea, styleArgs); } else { result = blockStyle(textarea, styleArgs); } insertText(textarea, result); } function isMultipleLines(string: string): boolean { return string.trim().split('\n').length > 1; } function repeat(string: string, n: number): string { return Array(n + 1).join(string); } function wordSelectionStart(text: string, i: number): number { let index = i; while (text[index] && text[index - 1] != null && !text[index - 1].match(/\s/)) { index--; } return index; } function wordSelectionEnd(text: string, i: number, multiline: boolean): number { let index = i; const breakpoint = multiline ? /\n/ : /\s/; while (text[index] && !text[index].match(breakpoint)) { index++; } return index; } function expandSelectionToLine(textarea: HTMLTextAreaElement) { const lines = textarea.value.split('\n'); let counter = 0; for (let index = 0; index < lines.length; index++) { const lineLength = lines[index].length + 1; if (textarea.selectionStart >= counter && textarea.selectionStart < counter + lineLength) { textarea.selectionStart = counter; } if (textarea.selectionEnd >= counter && textarea.selectionEnd < counter + lineLength) { textarea.selectionEnd = counter + lineLength - 1; } counter += lineLength; } } function expandSelectedText(textarea: HTMLTextAreaElement, prefixToUse: string, suffixToUse: string, multiline = false): string { if (textarea.selectionStart === textarea.selectionEnd) { textarea.selectionStart = wordSelectionStart(textarea.value, textarea.selectionStart); textarea.selectionEnd = wordSelectionEnd(textarea.value, textarea.selectionEnd, multiline); } else { const expandedSelectionStart = textarea.selectionStart - prefixToUse.length; const expandedSelectionEnd = textarea.selectionEnd + suffixToUse.length; const beginsWithPrefix = textarea.value.slice(expandedSelectionStart, textarea.selectionStart) === prefixToUse; const endsWithSuffix = textarea.value.slice(textarea.selectionEnd, expandedSelectionEnd) === suffixToUse; if (beginsWithPrefix && endsWithSuffix) { textarea.selectionStart = expandedSelectionStart; textarea.selectionEnd = expandedSelectionEnd; } } return textarea.value.slice(textarea.selectionStart, textarea.selectionEnd); } interface Newlines { newlinesToAppend: string; newlinesToPrepend: string; } function newlinesToSurroundSelectedText(textarea: HTMLTextAreaElement): Newlines { const beforeSelection = textarea.value.slice(0, textarea.selectionStart); const afterSelection = textarea.value.slice(textarea.selectionEnd); const breaksBefore = beforeSelection.match(/\n*$/); const breaksAfter = afterSelection.match(/^\n*/); const newlinesBeforeSelection = breaksBefore ? breaksBefore[0].length : 0; const newlinesAfterSelection = breaksAfter ? breaksAfter[0].length : 0; let newlinesToAppend; let newlinesToPrepend; if (beforeSelection.match(/\S/) && newlinesBeforeSelection < 2) { newlinesToAppend = repeat('\n', 2 - newlinesBeforeSelection); } if (afterSelection.match(/\S/) && newlinesAfterSelection < 2) { newlinesToPrepend = repeat('\n', 2 - newlinesAfterSelection); } if (newlinesToAppend == null) { newlinesToAppend = ''; } if (newlinesToPrepend == null) { newlinesToPrepend = ''; } return { newlinesToAppend, newlinesToPrepend }; } function blockStyle(textarea: HTMLTextAreaElement, arg: StyleArgs): SelectionRange { let newlinesToAppend; let newlinesToPrepend; const { prefix, suffix, blockPrefix, blockSuffix, replaceNext, prefixSpace, scanFor, surroundWithNewlines } = arg; const originalSelectionStart = textarea.selectionStart; const originalSelectionEnd = textarea.selectionEnd; let selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd); let prefixToUse = isMultipleLines(selectedText) && blockPrefix.length > 0 ? `${blockPrefix}\n` : prefix; // CHANGED let suffixToUse = isMultipleLines(selectedText) && blockSuffix.length > 0 ? `\n${blockSuffix}` : prefixToUse === prefix ? suffix : ''; // END CHANGED if (prefixSpace) { const beforeSelection = textarea.value[textarea.selectionStart - 1]; if (textarea.selectionStart !== 0 && beforeSelection != null && !beforeSelection.match(/\s/)) { prefixToUse = ` ${prefixToUse}`; } } selectedText = expandSelectedText(textarea, prefixToUse, suffixToUse, arg.multiline); let selectionStart = textarea.selectionStart; let selectionEnd = textarea.selectionEnd; const hasReplaceNext = replaceNext.length > 0 && suffixToUse.indexOf(replaceNext) > -1 && selectedText.length > 0; if (surroundWithNewlines) { const ref = newlinesToSurroundSelectedText(textarea); newlinesToAppend = ref.newlinesToAppend; newlinesToPrepend = ref.newlinesToPrepend; prefixToUse = newlinesToAppend + prefix; suffixToUse += newlinesToPrepend; } if (selectedText.startsWith(prefixToUse) && selectedText.endsWith(suffixToUse)) { const replacementText = selectedText.slice(prefixToUse.length, selectedText.length - suffixToUse.length); if (originalSelectionStart === originalSelectionEnd) { let position = originalSelectionStart - prefixToUse.length; position = Math.max(position, selectionStart); position = Math.min(position, selectionStart + replacementText.length); selectionStart = selectionEnd = position; } else { selectionEnd = selectionStart + replacementText.length; } return { text: replacementText, selectionStart, selectionEnd }; } else if (!hasReplaceNext) { let replacementText = prefixToUse + selectedText + suffixToUse; selectionStart = originalSelectionStart + prefixToUse.length; selectionEnd = originalSelectionEnd + prefixToUse.length; const whitespaceEdges = selectedText.match(/^\s*|\s*$/g); if (arg.trimFirst && whitespaceEdges) { const leadingWhitespace = whitespaceEdges[0] || ''; const trailingWhitespace = whitespaceEdges[1] || ''; replacementText = leadingWhitespace + prefixToUse + selectedText.trim() + suffixToUse + trailingWhitespace; selectionStart += leadingWhitespace.length; selectionEnd -= trailingWhitespace.length; } return { text: replacementText, selectionStart, selectionEnd }; } else if (scanFor.length > 0 && selectedText.match(scanFor)) { suffixToUse = suffixToUse.replace(replaceNext, selectedText); const replacementText = prefixToUse + suffixToUse; selectionStart = selectionEnd = selectionStart + prefixToUse.length; return { text: replacementText, selectionStart, selectionEnd }; } else { const replacementText = prefixToUse + selectedText + suffixToUse; selectionStart = selectionStart + prefixToUse.length + selectedText.length + suffixToUse.indexOf(replaceNext); selectionEnd = selectionStart + replaceNext.length; return { text: replacementText, selectionStart, selectionEnd }; } } function multilineStyle(textarea: HTMLTextAreaElement, arg: StyleArgs) { const { prefix, suffix, blockPrefix, blockSuffix, surroundWithNewlines } = arg; let text = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd); let selectionStart = textarea.selectionStart; let selectionEnd = textarea.selectionEnd; const lines = text.split('\n'); // CHANGED let prefixToUse = blockPrefix.length > 0 ? blockPrefix : prefix; let suffixToUse = blockSuffix.length > 0 ? blockSuffix : prefixToUse == prefix ? suffix : ''; const undoStyle = lines.every((line) => line.startsWith(prefixToUse) && line.endsWith(suffixToUse)); // END CHANGED if (undoStyle) { text = lines.map((line) => line.slice(prefixToUse.length, line.length - suffixToUse.length)).join('\n'); selectionEnd = selectionStart + text.length; } else { // CHANGED text = lines.map((line) => prefixToUse + line + suffixToUse).join('\n'); if (surroundWithNewlines || suffixToUse === '') { // END CHANGED const { newlinesToAppend, newlinesToPrepend } = newlinesToSurroundSelectedText(textarea); selectionStart += newlinesToAppend.length; selectionEnd = selectionStart + text.length; text = newlinesToAppend + text + newlinesToPrepend; } } return { text, selectionStart, selectionEnd }; } interface UndoResult { text: string; processed: boolean; } function undoOrderedListStyle(text: string): UndoResult { const lines = text.split('\n'); const orderedListRegex = /^\d+\.\s+/; const shouldUndoOrderedList = lines.every((line) => orderedListRegex.test(line)); let result = lines; if (shouldUndoOrderedList) { result = lines.map((line) => line.replace(orderedListRegex, '')); } return { text: result.join('\n'), processed: shouldUndoOrderedList, }; } function undoUnorderedListStyle(text: string): UndoResult { const lines = text.split('\n'); const unorderedListPrefix = '- '; const shouldUndoUnorderedList = lines.every((line) => line.startsWith(unorderedListPrefix)); let result = lines; if (shouldUndoUnorderedList) { result = lines.map((line) => line.slice(unorderedListPrefix.length, line.length)); } return { text: result.join('\n'), processed: shouldUndoUnorderedList, }; } function makePrefix(index: number, unorderedList: boolean): string { if (unorderedList) { return '- '; } else { return `${index + 1}. `; } } function clearExistingListStyle(style: StyleArgs, selectedText: string): [UndoResult, UndoResult, string] { let undoResultOpositeList: UndoResult; let undoResult: UndoResult; let pristineText; if (style.orderedList) { undoResult = undoOrderedListStyle(selectedText); undoResultOpositeList = undoUnorderedListStyle(undoResult.text); pristineText = undoResultOpositeList.text; } else { undoResult = undoUnorderedListStyle(selectedText); undoResultOpositeList = undoOrderedListStyle(undoResult.text); pristineText = undoResultOpositeList.text; } return [undoResult, undoResultOpositeList, pristineText]; } function listStyle(textarea: HTMLTextAreaElement, style: StyleArgs): SelectionRange { const noInitialSelection = textarea.selectionStart === textarea.selectionEnd; let selectionStart = textarea.selectionStart; let selectionEnd = textarea.selectionEnd; // Select whole line expandSelectionToLine(textarea); const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd); // If the user intent was to do an undo, we will stop after this. // Otherwise, we will still undo to other list type to prevent list stacking const [undoResult, undoResultOpositeList, pristineText] = clearExistingListStyle(style, selectedText); const prefixedLines = pristineText.split('\n').map((value, index) => { return `${makePrefix(index, style.unorderedList)}${value}`; }); const totalPrefixLength = prefixedLines.reduce((previousValue, _currentValue, currentIndex) => { return previousValue + makePrefix(currentIndex, style.unorderedList).length; }, 0); const totalPrefixLengthOpositeList = prefixedLines.reduce((previousValue, _currentValue, currentIndex) => { return previousValue + makePrefix(currentIndex, !style.unorderedList).length; }, 0); if (undoResult.processed) { if (noInitialSelection) { selectionStart = Math.max(selectionStart - makePrefix(0, style.unorderedList).length, 0); selectionEnd = selectionStart; } else { selectionStart = textarea.selectionStart; selectionEnd = textarea.selectionEnd - totalPrefixLength; } return { text: pristineText, selectionStart, selectionEnd }; } const { newlinesToAppend, newlinesToPrepend } = newlinesToSurroundSelectedText(textarea); const text = newlinesToAppend + prefixedLines.join('\n') + newlinesToPrepend; if (noInitialSelection) { selectionStart = Math.max(selectionStart + makePrefix(0, style.unorderedList).length + newlinesToAppend.length, 0); selectionEnd = selectionStart; } else { if (undoResultOpositeList.processed) { selectionStart = Math.max(textarea.selectionStart + newlinesToAppend.length, 0); selectionEnd = textarea.selectionEnd + newlinesToAppend.length + totalPrefixLength - totalPrefixLengthOpositeList; } else { selectionStart = Math.max(textarea.selectionStart + newlinesToAppend.length, 0); selectionEnd = textarea.selectionEnd + newlinesToAppend.length + totalPrefixLength; } } return { text, selectionStart, selectionEnd }; }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * ManagementGroups * __NOTE__: An instance of this class is automatically created for an * instance of the ManagementGroupsAPI. */ export interface ManagementGroups { /** * List management groups for the authenticated user. * * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {string} [options.skiptoken] Page continuation token is only used if * a previous operation returned a partial result. * If a previous response contains a nextLink element, the value of the * nextLink element will include a token parameter that specifies a starting * point to use for subsequent calls. * * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { cacheControl? : string, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupListResult>>; /** * List management groups for the authenticated user. * * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {string} [options.skiptoken] Page continuation token is only used if * a previous operation returned a partial result. * If a previous response contains a nextLink element, the value of the * nextLink element will include a token parameter that specifies a starting * point to use for subsequent calls. * * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupListResult} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { cacheControl? : string, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupListResult>; list(callback: ServiceCallback<models.ManagementGroupListResult>): void; list(options: { cacheControl? : string, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupListResult>): void; /** * Get the details of the management group. * * * @param {string} groupId Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] The $expand=children query string parameter * allows clients to request inclusion of children in the response payload. * Possible values include: 'children' * * @param {boolean} [options.recurse] The $recurse=true query string parameter * allows clients to request inclusion of entire hierarchy in the response * payload. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroup>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(groupId: string, options?: { expand? : string, recurse? : boolean, cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroup>>; /** * Get the details of the management group. * * * @param {string} groupId Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] The $expand=children query string parameter * allows clients to request inclusion of children in the response payload. * Possible values include: 'children' * * @param {boolean} [options.recurse] The $recurse=true query string parameter * allows clients to request inclusion of entire hierarchy in the response * payload. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroup} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroup} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroup} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(groupId: string, options?: { expand? : string, recurse? : boolean, cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroup>; get(groupId: string, callback: ServiceCallback<models.ManagementGroup>): void; get(groupId: string, options: { expand? : string, recurse? : boolean, cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroup>): void; /** * Create or update a management group. * If a management group is already created and a subsequent create request is * issued with different properties, the management group properties will be * updated. * * * @param {string} groupId Management Group ID. * * @param {object} createManagementGroupRequest Management group creation * parameters. * * @param {string} [createManagementGroupRequest.displayName] The friendly name * of the management group. * * @param {string} [createManagementGroupRequest.parentId] (Optional) The fully * qualified ID for the parent management group. For example, * /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroup>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroup>>; /** * Create or update a management group. * If a management group is already created and a subsequent create request is * issued with different properties, the management group properties will be * updated. * * * @param {string} groupId Management Group ID. * * @param {object} createManagementGroupRequest Management group creation * parameters. * * @param {string} [createManagementGroupRequest.displayName] The friendly name * of the management group. * * @param {string} [createManagementGroupRequest.parentId] (Optional) The fully * qualified ID for the parent management group. For example, * /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroup} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroup} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroup} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroup>; createOrUpdate(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, callback: ServiceCallback<models.ManagementGroup>): void; createOrUpdate(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, options: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroup>): void; /** * Update a management group. * * * @param {string} groupId Management Group ID. * * @param {object} createManagementGroupRequest Management group creation * parameters. * * @param {string} [createManagementGroupRequest.displayName] The friendly name * of the management group. * * @param {string} [createManagementGroupRequest.parentId] (Optional) The fully * qualified ID for the parent management group. For example, * /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroup>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroup>>; /** * Update a management group. * * * @param {string} groupId Management Group ID. * * @param {object} createManagementGroupRequest Management group creation * parameters. * * @param {string} [createManagementGroupRequest.displayName] The friendly name * of the management group. * * @param {string} [createManagementGroupRequest.parentId] (Optional) The fully * qualified ID for the parent management group. For example, * /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroup} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroup} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroup} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroup>; update(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, callback: ServiceCallback<models.ManagementGroup>): void; update(groupId: string, createManagementGroupRequest: models.CreateManagementGroupRequest, options: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroup>): void; /** * Delete management group. * If a management group contains child resources, the request will fail. * * * @param {string} groupId Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(groupId: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete management group. * If a management group contains child resources, the request will fail. * * * @param {string} groupId Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(groupId: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(groupId: string, callback: ServiceCallback<void>): void; deleteMethod(groupId: string, options: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List management groups for the authenticated user. * * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupListResult>>; /** * List management groups for the authenticated user. * * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupListResult} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.ManagementGroupListResult>): void; listNext(nextPageLink: string, options: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupListResult>): void; } /** * @class * ManagementGroupSubscriptions * __NOTE__: An instance of this class is automatically created for an * instance of the ManagementGroupsAPI. */ export interface ManagementGroupSubscriptions { /** * Associates existing subscription with the management group. * * * @param {string} groupId Management Group ID. * * @param {string} subscriptionId Subscription ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(groupId: string, subscriptionId: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Associates existing subscription with the management group. * * * @param {string} groupId Management Group ID. * * @param {string} subscriptionId Subscription ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(groupId: string, subscriptionId: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<void>; create(groupId: string, subscriptionId: string, callback: ServiceCallback<void>): void; create(groupId: string, subscriptionId: string, options: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * De-associates subscription from the management group. * * * @param {string} groupId Management Group ID. * * @param {string} subscriptionId Subscription ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(groupId: string, subscriptionId: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * De-associates subscription from the management group. * * * @param {string} groupId Management Group ID. * * @param {string} subscriptionId Subscription ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.cacheControl] Indicates that the request shouldn't * utilize any caches. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(groupId: string, subscriptionId: string, options?: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(groupId: string, subscriptionId: string, callback: ServiceCallback<void>): void; deleteMethod(groupId: string, subscriptionId: string, options: { cacheControl? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the ManagementGroupsAPI. */ export interface Operations { /** * Lists all of the available Management REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available Management REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available Management REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available Management REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; }
the_stack
import { toQueryString } from "../../utils"; import { SdkClient } from "../common/sdk-client"; import { IdentityManagementModels } from "./identity-models"; /** * The Identity Management API provides a means form managing users, groups and OAuth clients. * The user and group management is based on SCIM (System for Cross-domain Identity Management). * * Note: Unless stated otherwise the Identity Management APIs allow each caller only to act within the context of the tenant to which the caller belong's to. * * Note2: UIAM stands for User Identity Access Management, since users and providers are separated in system. Therefore this API documentation is related to users generally. * * @export * @class TimeSeriesClient * @extends {SdkClient} */ export class IdentityManagementClient extends SdkClient { private _baseUrl: string = "/api/identitymanagement/v3"; /** * * *uiam user - API for Managing Users in a Tenant * * List of users of a tenant. * Please note, in order to request only the list of users (without the information to which group a user belongs) * it is recommended to make use of the "attributes" query parameter as follows /Users?attributes=userName,name,meta * (this will significantly improve the performance over simply calling /Users). * @summary List of users of a tenant. * @param {{ * filter?: string, * atributes?: string, * sortBy?: string, * sortOrder?: string, * count?: number, * startIndex?: number, * subtenant?: string * }} [params] * * @param {string} [params.filter] SCIM filter for searching see [here](http://www.simplecloud.info/specs/draft-scim-api-01.html). * The available filter attributes are: id, username, email or emails.value, givenname, familyname, active, phonenumber, verified, origin, created or meta. * created, lastmodified or meta.lastmodified, version or meta.version, groups.display. * Note: parameter cannot be used in complex filter expression and only eq operator is allowed eg. * ilter=groups.display eq "MyGroupName" * @param {string} [params.attributes] Comma separated list of attribute names to be returned, e.g., userName, name, meta. The attributes parameters does not support the parameter \&quot;subtenants\&quot;. * @param {string} [params.sortBy] Sorting field name, like email or id * @param {string} [params.sortOrder] Sort order, ascending/descending (defaults to ascending) * @param {number} [params.count] Number of objects to be returned (defaults to 100) * @param {number} [params.startIndex] The starting index of the search results when paginated. Index starts with 1 (defaults to 1). * @param {string} [params.subtenant] Filter for subtenant users * @throws {RequiredError} * @returns {Promise<IdentityManagementModels.ScimUserResponseSearchResults>} * * @memberOf IdentityManagementClient */ public async GetUsers(params?: { filter?: string; attributes?: string; sortBy?: string; sortOrder?: string; count?: number; startIndex?: number; subtenant?: string; }): Promise<IdentityManagementModels.ScimUserResponseSearchResults> { const qs = toQueryString(params); return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Users?${qs}`, message: "GetUsers", })) as IdentityManagementModels.ScimUserResponseSearchResults; } /** * *uiam user - API for Managing Users in a Tenant * * Get details of user * * @param {string} id * @returns {Promise<IdentityManagementModels.ScimUserResponse>} * * @memberOf IdentityManagementClient */ public async GetUser(id: string): Promise<IdentityManagementModels.ScimUserResponse> { return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Users/${id}`, message: "GET", })) as IdentityManagementModels.ScimUserResponse; } /** * *uiam user - API for Managing Users in a Tenant * * Create a new user in a tenant. * Note: The ‘subtenants’ field is optional. If it is present, the user is considered to be a subtenant user. * * @param {IdentityManagementModels.ScimUserPost} user * @returns {Promise<IdentityManagementModels.ScimUserPostResponse>} * * @memberOf IdentityManagementClient */ public async PostUser( user: IdentityManagementModels.ScimUserPost ): Promise<IdentityManagementModels.ScimUserPostResponse> { return (await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Users`, message: "PostUser", body: user, })) as IdentityManagementModels.ScimUserPostResponse; } /** * *uiam user - API for Managing Users in a Tenant * * Update User * * @param {string} id * @param {IdentityManagementModels.ScimUserPost} user * @returns {Promise<IdentityManagementModels.ScimUserResponse>} * * @memberOf IdentityManagementClient */ public async PutUser( id: string, user: IdentityManagementModels.ScimUserPut ): Promise<IdentityManagementModels.ScimUserResponse> { return (await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Users/${id}`, message: "PutUser", body: user, })) as IdentityManagementModels.ScimUserResponse; } /** * *uiam user - API for Managing Users in a Tenant * * Delete user of tenant. * Note that tenant can have user if it purchased at least the simple offering. * Example path /api/identitymanagement/v3/Users/2f95913-d3d9-4a4a-951a-c21184080cf3 * * @param {string} id * @returns {Promise<IdentityManagementModels.ScimUserResponse>} * * @memberOf IdentityManagementClient */ public async DeleteUser(id: string): Promise<IdentityManagementModels.ScimUserResponse> { return (await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Users/${id}`, message: "DeleteUser", })) as IdentityManagementModels.ScimUserResponse; } /** * * *uiam user - API for Managing Users in a Tenant * * Get list of groups starting with the prefix "mdsp:" in which the user is a member. * * @returns {Promise<IdentityManagementModels.Group>} * * @memberOf IdentityManagementClient */ public async GetUsersMe(): Promise<IdentityManagementModels.Group> { return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Users/me`, message: "GetUsersMe", })) as IdentityManagementModels.Group; } /** * * *uiam group - API for Managing Groups in a Tenant * * List of groups of a tenant. @summary List of groups of a tenant. * @param {{ * filter?: string, * count?: number, * startIndex?: number, * }} [params] * * @param {string} [params.filter] SCIM filter for searching see [here](http://www.simplecloud.info/specs/draft-scim-api-01.html). * The available filter attributes are: id, groupname, email or emails.value, givenname, familyname, active, phonenumber, verified, origin, created or meta. * created, lastmodified or meta.lastmodified, version or meta.version, groups.display. * Note: parameter cannot be used in complex filter expression and only eq operator is allowed eg. * ilter=groups.display eq "MyGroupName" * @param {number} [params.count] Number of objects to be returned (defaults to 100) * @param {number} [params.startIndex] The starting index of the search results when paginated. Index starts with 1 (defaults to 1). * @throws {RequiredError} * @returns {Promise<IdentityManagementModels.ScimGroupSearchResults>} * * @memberOf IdentityManagementClient */ public async GetGroups(params?: { filter?: string; count?: number; startIndex?: number; }): Promise<IdentityManagementModels.ScimGroupSearchResults> { const qs = toQueryString(params); return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups?${qs}`, message: "GetGroups", })) as IdentityManagementModels.ScimGroupSearchResults; } /** * *uiam group - API for Managing Groups in a Tenant * * Get details of group * * @param {string} id * @returns {Promise<IdentityManagementModels.ScimGroup>} * * @memberOf IdentityManagementClient */ public async GetGroup(id: string): Promise<IdentityManagementModels.ScimGroup> { return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups/${id}`, message: "GET", })) as IdentityManagementModels.ScimGroup; } /** * *uiam group - API for Managing Groups in a Tenant * * Create a new group in a tenant. * Note: The ‘subtenants’ field is optional. If it is present, the group is considered to be a subtenant group. * * @param {IdentityManagementModels.ScimGroupPost} group * @returns {Promise<IdentityManagementModels.ScimGroup>} * * @memberOf IdentityManagementClient */ public async PostGroup(group: IdentityManagementModels.ScimGroupPost): Promise<IdentityManagementModels.ScimGroup> { return (await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups`, message: "PostGroup", body: group, })) as IdentityManagementModels.ScimGroup; } /** * *uiam group - API for Managing Groups in a Tenant * * Update Group * * @param {string} id * @param {IdentityManagementModels.ScimGroupPost} group * @returns {Promise<IdentityManagementModels.ScimGroup>} * * @memberOf IdentityManagementClient */ public async PutGroup( id: string, group: IdentityManagementModels.ScimGroupPost ): Promise<IdentityManagementModels.ScimGroup> { return (await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups/${id}`, message: "PutGroup", body: group, })) as IdentityManagementModels.ScimGroup; } /** * *uiam group - API for Managing Groups in a Tenant * * Delete group and every connection to that group, too. * Example path /api/identitymanagement/v3/Groups/68af46d-e9b8-4t04-5a20-7d557f5da8d * * @param {string} id * @returns {Promise<IdentityManagementModels.ScimGroup>} * * @memberOf IdentityManagementClient */ public async DeleteGroup(id: string): Promise<IdentityManagementModels.ScimGroup> { return (await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups/${id}`, message: "DeleteGroup", })) as IdentityManagementModels.ScimGroup; } /** * *uiam group - API for Managing Groups in a Tenant * * @param {string} id * @returns {Promise<IdentityManagementModels.ScimGroupMemberList>} * * @memberOf IdentityManagementClient */ public async GetGroupMembers(id: string): Promise<IdentityManagementModels.ScimGroupMemberList> { return (await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups/${id}/members`, message: "GetGroupMemberList", })) as IdentityManagementModels.ScimGroupMemberList; } /** * *uiam group - API for Managing Groups in a Tenant * * Add new member (either user or group) to an existing group. * Example path /api/identitymanagement/v3/Groups/68af46d-e9b8-4t04-5a20-7d557f5da8d/members. * * @param {IdentityManagementModels.ScimGroupMemberPost} group * @returns {Promise<IdentityManagementModels.ScimGroupMember>} * * @memberOf IdentityManagementClient */ public async PostGroupMember( id: string, member: IdentityManagementModels.ScimGroupMember ): Promise<IdentityManagementModels.ScimGroupMember> { return (await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups/${id}/members`, message: "PostGroupMember", body: member, })) as IdentityManagementModels.ScimGroupMember; } /** * *uiam group - API for Managing Groups in a Tenant * * Delete member (either user or group) from a group. * Example path /api/identitymanagement/v3/Groups/68af46d-e9b8-4t04-5a20-7d557f5da8d/members/e74ff46d-8bb8-4d04-b420-7d557fe86a8d * * @param {string} id * @param {string} memberId * @returns {Promise<IdentityManagementModels.ScimGroupMember>} * * @memberOf IdentityManagementClient */ public async DeleteGroupMember(id: string, memberId: string): Promise<IdentityManagementModels.ScimGroupMember> { return (await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/Groups/${id}/members/${memberId}`, message: "DeleteGroupMember", })) as IdentityManagementModels.ScimGroupMember; } }
the_stack
namespace angularSuperGallery { // modal component options export interface IOptionsModal { header?: { enabled?: boolean; dynamic?: boolean; buttons: Array<string>; }; help?: boolean; caption?: { disabled?: boolean; visible?: boolean; position?: string; download?: boolean; }; placeholder?: string; transition?: string; transitionSpeed? : number; title?: string; subtitle?: string; titleFromImage? : boolean; subtitleFromImage? : boolean; arrows?: { preload?: boolean; enabled?: boolean; }; size?: string; thumbnail?: IOptionsThumbnail; marginTop?: number; marginBottom?: number; click?: { close: boolean; }; keycodes?: { exit?: Array<number>; playpause?: Array<number>; forward?: Array<number>; backward?: Array<number>; first?: Array<number>; last?: Array<number>; fullscreen?: Array<number>; menu?: Array<number>; caption?: Array<number>; help?: Array<number>; size?: Array<number>; transition?: Array<number>; }; } // panel component options export interface IOptionsPanel { visible?: boolean; items?: { class?: string; }, item?: { class?: string; caption: boolean; index: boolean; }; hover?: { preload: boolean; select: boolean; }; click?: { select: boolean; modal: boolean; }; } // thumbnail component options export interface IOptionsThumbnail { height?: number; index?: boolean; enabled?: boolean; dynamic?: boolean; autohide: boolean; click?: { select: boolean; modal: boolean; }; hover?: { preload: boolean; select: boolean; }; loaded?: boolean; initialized?: boolean; } // info component options export interface IOptionsInfo { } // image component options export interface IOptionsImage { transition?: string; transitionSpeed? : number; size?: string; arrows?: { preload?: boolean; enabled?: boolean; }; click?: { modal: boolean; }; height?: number; heightMin?: number; heightAuto?: { initial?: boolean; onresize?: boolean; }; placeholder: string; } // gallery options export interface IOptions { debug?: boolean; baseUrl?: string; hashUrl?: boolean; duplicates?: boolean; selected?: number; fields?: { source?: { modal?: string; panel?: string; image?: string; placeholder?: string; } title?: string; subtitle?: string; description?: string; thumbnail?: string; video?: string; }; autoplay?: { enabled?: boolean; delay?: number; }; theme?: string; preload?: Array<number>; preloadNext?: boolean; preloadDelay?: number; loadingImage?: string; modal?: IOptionsModal; panel?: IOptionsPanel; image?: IOptionsImage; thumbnail?: IOptionsThumbnail; } // image source export interface ISource { modal: string; // original, required panel?: string; image?: string; color?: string; placeholder?: string; } // image file export interface IFile { source: ISource; title?: string; subtitle?: string; name?: string; extension?: string; description?: string; video?: { vimeoId: string; youtubeId: string; htmlId: string; autoplay: boolean; paused: boolean; visible: boolean; playing: boolean; player: any }; download?: string; loaded?: { modal?: boolean; panel?: boolean; image?: boolean; }; width?: number; height?: number; } export interface IOver { modalImage: boolean; panel: boolean; } export interface IEdit { id: number; delete?: number; add?: Array<IFile>; update?: Array<IFile>; refresh?: boolean; selected?: number; options?: IOptions; delayThumbnails?: number; delayRefresh?: number; } export interface IScope extends ng.IScope { forward: () => void; backward: () => void; } // service controller interface export interface IServiceController { modalVisible: boolean; panelVisible: boolean; modalAvailable: boolean; modalInitialized: boolean; transitions: Array<string>; themes: Array<string>; classes: string; options: IOptions; items: Array<IFile>; selected: number; file: IFile; files: Array<IFile>; sizes: Array<string>; id: string; isSingle: boolean; events: { CONFIG_LOAD: string; AUTOPLAY_START: string; AUTOPLAY_STOP: string; PARSE_IMAGES: string; LOAD_IMAGE: string; FIRST_IMAGE: string; CHANGE_IMAGE: string; DOUBLE_IMAGE: string; MODAL_OPEN: string; MODAL_CLOSE: string; GALLERY_UPDATED: string; GALLERY_EDIT: string; LAST_THUMBNAIL: string; }; getInstance(component: any): IServiceController; setDefaults(): void; setOptions(options: IOptions): IOptions; setItems(items: Array<IFile>, force?: boolean): void; preload(wait?: number): void; normalize(index: number): number; setFocus(): void; setSelected(index: number); modalOpen(index: number): void; modalClose(): void; modalClick($event?: UIEvent): void; thumbnailsMove(delay?: number): void; toBackward(stop?: boolean): void; toForward(stop?: boolean): void; toFirst(stop?: boolean): void; toLast(stop?: boolean): void; loadImage(index?: number): void; loadImages(indexes: Array<number>): void; hoverPreload(index: number): void; autoPlayToggle(): void; toggle(element: string): void; setHash(): void; downloadLink(): string; el(selector): NodeList; log(event: string, data?: any): void; event(event: string, data?: any); } // service controller export class ServiceController { public version = "2.1.11"; public slug = 'asg'; public id: string; public items: Array<IFile> = []; public files: Array<IFile> = []; public direction: string; public modalAvailable = false; public modalInitialized = false; private instances: {} = {}; private _selected: number; private _visible = false; private autoplay: angular.IPromise<any>; private first = false; private editing = false; public options: IOptions = null; public optionsLoaded = false; public defaults: IOptions = { debug: false, // image load, autoplay, etc. info in console.log hashUrl: true, // enable/disable hash usage in url (#asg-nature-4) baseUrl: '', // url prefix duplicates: false, // enable or disable same images (url) in gallery selected: 0, // selected image on init fields: { source: { modal: 'url', // required, image url for modal component (large size) panel: 'url', // image url for panel component (thumbnail size) image: 'url', // image url for image (medium or custom size) placeholder: null // image url for preload lowres image }, title: 'title', // title field name subtitle: 'subtitle', // subtitle field name description: 'description', // description field name video: 'video', // video field name }, autoplay: { enabled: false, // slideshow play enabled/disabled delay: 4100 // autoplay delay in millisecond }, theme: 'default', // css style [default, darkblue, darkred, whitegold] preloadNext: false, // preload next image (forward/backward) preloadDelay: 770, // preload delay for preloadNext loadingImage: 'preload.svg', // loader image preload: [], // preload images by index number modal: { title: '', // modal window title subtitle: '', // modal window subtitle titleFromImage: false, // force update the gallery title by image title subtitleFromImage: false, // force update the gallery subtitle by image description placeholder: 'panel', // set image placeholder source type (thumbnail) or full url (http...) caption: { disabled: false, // disable image caption visible: true, // show/hide image caption position: 'top', // caption position [top, bottom] download: false // show/hide download link }, header: { enabled: true, // enable/disable modal menu dynamic: false, // show/hide modal menu on mouseover buttons: ['playstop', 'index', 'prev', 'next', 'pin', 'size', 'transition', 'thumbnails', 'fullscreen', 'help', 'close'], }, help: false, // show/hide help arrows: { enabled: true, // show/hide arrows preload: true, // preload image on mouseover }, click: { close: true // when click on the image close the modal }, thumbnail: { height: 50, // thumbnail image height in pixel index: false, // show index number on thumbnail enabled: true, // enable/disable thumbnails dynamic: false, // if true thumbnails visible only when mouseover autohide: true, // hide thumbnail component when single image click: { select: true, // set selected image when true modal: false // open modal when true }, hover: { preload: true, // preload image on mouseover select: false // set selected image on mouseover when true }, }, transition: 'slideLR', // transition effect transitionSpeed: 0.7, // transition speed 0.7s size: 'cover', // contain, cover, auto, stretch keycodes: { exit: [27], // esc playpause: [80], // p forward: [32, 39], // space, right arrow backward: [37], // left arrow first: [38, 36], // up arrow, home last: [40, 35], // down arrow, end fullscreen: [13], // enter menu: [77], // m caption: [67], // c help: [72], // h size: [83], // s transition: [84] // t } }, thumbnail: { height: 50, // thumbnail image height in pixel index: false, // show index number on thumbnail dynamic: false, // if true thumbnails visible only when mouseover autohide: false, // hide thumbnail component when single image click: { select: true, // set selected image when true modal: false // open modal when true }, hover: { preload: true, // preload image on mouseover select: false // set selected image on mouseover when true }, }, panel: { visible: true, items: { class: 'row', // items class }, item: { class: 'col-md-3', // item class caption: false, // show/hide image caption index: false, // show/hide image index }, hover: { preload: true, // preload image on mouseover select: false // set selected image on mouseover when true }, click: { select: false, // set selected image when true modal: true // open modal when true }, }, image: { transition: 'slideLR', // transition effect transitionSpeed: 0.7, // transition speed 0.7s size: 'cover', // contain, cover, auto, stretch arrows: { enabled: true, // show/hide arrows preload: true, // preload image on mouseover }, click: { modal: true // when click on the image open the modal window }, height: null, // height in pixel heightMin: null, // min height in pixel heightAuto: { initial: true, // calculate div height by first image onresize: false // calculate div height on window resize }, placeholder: 'panel' // set image placeholder source type (thumbnail) or full url (http...) } }; // available image sizes public sizes: Array<string> = [ 'contain', 'cover', 'auto', 'stretch' ]; // available themes public themes: Array<string> = [ 'default', 'darkblue', 'whitegold' ]; // available transitions public transitions: Array<string> = [ 'no', 'fadeInOut', 'zoomIn', 'zoomOut', 'zoomInOut', 'rotateLR', 'rotateTB', 'rotateZY', 'slideLR', 'slideTB', 'zlideLR', 'zlideTB', 'flipX', 'flipY' ]; public events = { CONFIG_LOAD: 'ASG-config-load-', AUTOPLAY_START: 'ASG-autoplay-start-', AUTOPLAY_STOP: 'ASG-autoplay-stop-', PARSE_IMAGES: 'ASG-parse-images-', LOAD_IMAGE: 'ASG-load-image-', FIRST_IMAGE: 'ASG-first-image-', CHANGE_IMAGE: 'ASG-change-image-', DOUBLE_IMAGE: 'ASG-double-image-', MODAL_OPEN: 'ASG-modal-open-', MODAL_CLOSE: 'ASG-modal-close-', THUMBNAIL_MOVE: 'ASG-thumbnail-move-', GALLERY_UPDATED: 'ASG-gallery-updated-', LAST_THUMBNAIL: 'ASG-last-thumbnail-', GALLERY_EDIT: 'ASG-gallery-edit', }; constructor(private timeout: ng.ITimeoutService, private interval: ng.IIntervalService, private location: ng.ILocationService, private $rootScope: ng.IRootScopeService, private $window: ng.IWindowService, private $sce: ng.ISCEService) { angular.element($window).bind('resize', (event) => { this.thumbnailsMove(200); }); // update images when edit event $rootScope.$on(this.events.GALLERY_EDIT, (event, data) => { if (this.instances[data.id]) { this.instances[data.id].editGallery(data); } }); } private parseHash() { if (!this.id) { return; } if (!this.options.hashUrl) { return; } let hash = this.location.hash(); let parts = hash ? hash.split('-') : null; if (parts === null) { return; } if (parts[0] !== this.slug) { return; } if (parts.length !== 3) { return; } if (parts[1] !== this.id) { return; } let index = parseInt(parts[2], 10); if (!angular.isNumber(index)) { return; } this.timeout(() => { index--; this.selected = index; this.modalOpen(index); }, 20); } // calculate object hash id public objectHashId(object: any): string { let string = JSON.stringify(object); if (!string) { return null; } let abc = string.replace(/[^a-zA-Z0-9]+/g, ''); let code = 0; for (let i = 0, n = abc.length; i < n; i++) { let charcode = abc.charCodeAt(i); code += (charcode * i); } return 'id' + code.toString(21); } // get service instance for current gallery by component id public getInstance(component: any) { if (!component.id) { // get parent asg component id if (component.$scope && component.$scope.$parent && component.$scope.$parent.$parent && component.$scope.$parent.$parent.$ctrl) { component.id = component.$scope.$parent.$parent.$ctrl.id; } else { component.id = this.objectHashId(component.options); } } const id = component.id; let instance = this.instances[id]; // new instance and set options and items if (instance === undefined) { instance = new ServiceController(this.timeout, this.interval, this.location, this.$rootScope, this.$window, this.$sce); instance.id = id; } if (component.baseUrl) { component.options.baseUrl = component.baseUrl; } instance.setOptions(component.options); instance.setItems(component.items); instance.selected = component.selected ? component.selected : instance.options.selected; instance.parseHash(); if (instance.options) { instance.loadImages(instance.options.preload); if (instance.options.autoplay && instance.options.autoplay.enabled && !instance.autoplay) { instance.autoPlayStart(); } } this.instances[id] = instance; return instance; } // prepare images array public setItems(items: Array<IFile>) { this.items = items ? items : []; this.prepareItems(); } // options setup public setOptions(options: IOptions) { // if options already setup if (this.optionsLoaded) { return; } if (options) { this.options = angular.copy(this.defaults); angular.merge(this.options, options); if (options.modal && options.modal.header && options.modal.header.buttons) { this.options.modal.header.buttons = options.modal.header.buttons; // remove duplicates from buttons this.options.modal.header.buttons = this.options.modal.header.buttons.filter(function (x, i, a) { return a.indexOf(x) === i; }); } this.optionsLoaded = true; } else { this.options = angular.copy(this.defaults); } // if !this.$window.screenfull if (!this.$window.screenfull) { this.options.modal.header.buttons = this.options.modal.header.buttons.filter(function (x, i, a) { return x !== 'fullscreen'; }); } // important! options = this.options; this.event(this.events.CONFIG_LOAD, this.options); return this.options; } // set selected image public set selected(v: number) { v = this.normalize(v); let prev = this._selected; if (prev != v && this.file && this.file.video && this.file.video.playing) { this.file.video.player.pause(); this.file.video.paused = true; } this._selected = v; this.loadImage(this._selected); this.preload(); if (this.file) { if (this.options.modal.titleFromImage && this.file.title) { this.options.modal.title = this.file.title; } if (this.options.modal.subtitleFromImage && this.file.description) { this.options.modal.subtitle = this.file.description; } if (this.file.video && this.file.video.paused) { this.file.video.player.play(); this.file.video.paused = false; } } if (prev !== this._selected) { this.thumbnailsMove(); this.event(this.events.CHANGE_IMAGE, { index: v, file: this.file }); } this.options.selected = this._selected; } // get selected image public get selected() { return this._selected; } // force select image public forceSelect(index) { index = this.normalize(index); this._selected = index; this.loadImage(this._selected); this.preload(); this.event(this.events.CHANGE_IMAGE, { index: index, file: this.file }); } public setSelected(index: number) { this.autoPlayStop(); this.direction = index > this.selected ? 'forward' : 'backward'; this.selected = index; this.setHash(); } // go to backward public toBackward(stop?: boolean) { if (stop) { this.autoPlayStop(); } this.direction = 'backward'; this.selected--; this.setHash(); } // go to forward public toForward(stop?: boolean) { if (stop) { this.autoPlayStop(); } this.direction = 'forward'; this.selected++; this.setHash(); } // go to first public toFirst(stop?: boolean) { if (stop) { this.autoPlayStop(); } this.direction = 'backward'; this.selected = 0; this.setHash(); } // go to last public toLast(stop?: boolean) { if (stop) { this.autoPlayStop(); } this.direction = 'forward'; this.selected = this.items.length - 1; this.setHash(); } public setHash() { if (this.modalVisible && this.options.hashUrl) { this.location.hash([this.slug, this.id, this.selected + 1].join('-')); } } public autoPlayToggle() { if (this.options.autoplay.enabled) { this.autoPlayStop(); } else { this.autoPlayStart(); } } public autoPlayStop() { if (!this.autoplay) { return; } this.interval.cancel(this.autoplay); this.options.autoplay.enabled = false; this.autoplay = null; this.event(this.events.AUTOPLAY_STOP, { index: this.selected, file: this.file }); } public autoPlayStart() { if (this.autoplay) { return; } this.options.autoplay.enabled = true; this.autoplay = this.interval(() => { this.toForward(); }, this.options.autoplay.delay); this.event(this.events.AUTOPLAY_START, { index: this.selected, file: this.file }); } private prepareItems() { let length = this.items.length; for (let key = 0; key < length; key++) { this.addImage(this.items[key]); } this.event(this.events.PARSE_IMAGES, this.files); } // preload the image when mouseover public hoverPreload(index: number) { this.loadImage(index); } // image preload private preload(wait?: number) { let index = this.direction === 'forward' ? this.selected + 1 : this.selected - 1; if (this.options.preloadNext === true) { this.timeout(() => { this.loadImage(index); }, (wait !== undefined) ? wait : this.options.preloadDelay); } } public normalize(index: number) { let last = this.files.length - 1; if (index > last) { return (index - last) - 1; } if (index < 0) { return last - Math.abs(index) + 1; } return index; } public loadImages(indexes: Array<number>, type: string) { if (!indexes || indexes.length === 0) { return; } let self = this; indexes.forEach((index: number) => { self.loadImage(index); }); } public loadImage(index?: number, callback?: {}) { index = index ? index : this.selected; index = this.normalize(index); if (!this.files[index]) { this.log('invalid file index', { index: index }); return; } if (this.modalVisible) { if (this.files[index].loaded.modal === true) { return; } let modal = new Image(); modal.src = this.files[index].source.modal; modal.addEventListener('load', (event) => { this.afterLoad(index, 'modal', modal); }); } else { if (this.files[index].loaded.image === true) { return; } let image = new Image(); image.src = this.files[index].source.image; image.addEventListener('load', () => { this.afterLoad(index, 'image', image); }); } } // get file name private getFilename(index: number, type?: string) { type = type ? type : 'modal'; let fileparts = this.files[index].source[type].split('/'); let filename = fileparts[fileparts.length - 1]; return filename; } // get file extension private getExtension(index: number, type?: string) { type = type ? type : 'modal'; let fileparts = this.files[index].source[type].split('.'); let extension = fileparts[fileparts.length - 1]; return extension; } // after load image private afterLoad(index, type, image) { if (!this.files[index] || !this.files[index].loaded) { return; } if (this.files[index].loaded[type] === true) { this.files[index].loaded[type] = true; return; } if (type === 'modal') { this.files[index].width = image.width; this.files[index].height = image.height; this.files[index].name = this.getFilename(index, type); this.files[index].extension = this.getExtension(index, type); this.files[index].download = this.files[index].source.modal; } this.files[index].loaded[type] = true; let data = { type: type, index: index, file: this.file, img: image }; if (!this.first) { this.first = true; this.event(this.events.FIRST_IMAGE, data); } this.event(this.events.LOAD_IMAGE, data); } // is single? public get isSingle() { return this.files.length > 1 ? false : true; } // get the download link public downloadLink() { if (this.selected !== undefined && this.files.length > 0) { return this.files[this.selected].source.modal; } } // get the file public get file(): IFile { return this.files[this.selected]; } // toggle element visible public toggle(element: string): void { this.options[element].visible = !this.options[element].visible; } // get visible public get modalVisible(): boolean { return this._visible; } // get theme public get theme(): string { return this.options.theme; } // get classes public get classes(): string { return this.options.theme + ' ' + this.id + (this.editing ? ' editing' : ''); } // get preload style public dynamicStyle(file: IFile, type: string, config: IOptionsModal | IOptionsImage) { let style = {}; if (file.source.color) { style['background-color'] = file.source.color; } if (this.options.loadingImage && file.loaded[type] === false) { style['background-image'] = 'url(' + this.options.loadingImage + ')'; } if (config.transitionSpeed !== undefined && config.transitionSpeed !== null) { style['transition'] = 'all ease ' + config.transitionSpeed + 's'; } return style; } // get placeholder style public placeholderStyle(file: IFile, type: string) { let style = {}; if (this.options[type].placeholder) { let index = this.options[type].placeholder; let isFull = (index.indexOf('//') === 0 || index.indexOf('http') === 0) ? true : false; let source; if (isFull) { source = index; } else { source = file.source[index]; } if (source) { style['background-image'] = 'url(' + source + ')'; } } if (file.source.color) { style['background-color'] = file.source.color; } if (file.source.placeholder) { style['background-image'] = 'url(' + file.source.placeholder + ')'; } return style; } // set visible public set modalVisible(value: boolean) { this._visible = value; // set index 0 if !selected this.selected = this.selected ? this.selected : 0; let body = document.body; let className = 'asg-yhidden'; if (value) { if (body.className.indexOf(className) < 0) { body.className = body.className + ' ' + className; } this.modalInit(); } else { body.className = body.className.replace(className, '').trim(); } } // initialize the gallery private modalInit() { let self = this; this.timeout(() => { self.setFocus(); }, 100); this.timeout(() => { this.modalInitialized = true; }, 460); } public modalOpen(index: number) { if (!this.modalAvailable) { return; } this.selected = index !== undefined ? index : this.selected; this.modalVisible = true; this.loadImage(); this.setHash(); this.event(this.events.MODAL_OPEN, { index: this.selected }); } public modalClose() { if (this.options.hashUrl) { this.location.hash(''); } this.modalInitialized = false; this.modalVisible = false; this.loadImage(); this.event(this.events.MODAL_CLOSE, { index: this.selected }); } // move thumbnails to correct position public thumbnailsMove(delay?: number) { let move = () => { let containers = this.el('div.asg-thumbnail.' + this.id); if (!containers.length) { return; } for (let i = 0; i < containers.length; i++) { let container: any = containers[i]; if (container.offsetWidth) { let items: any = container.querySelector('div.items'); let item: any = container.querySelector('div.item'); let thumbnail, moveX, remain; if (item) { if (items.scrollWidth > container.offsetWidth) { thumbnail = items.scrollWidth / this.files.length; moveX = (container.offsetWidth / 2) - (this.selected * thumbnail) - thumbnail / 2; remain = items.scrollWidth + moveX; moveX = moveX > 0 ? 0 : moveX; moveX = remain < container.offsetWidth ? container.offsetWidth - items.scrollWidth : moveX; } else { thumbnail = this.getRealWidth(item); moveX = (container.offsetWidth - thumbnail * this.files.length) / 2; } items.style.left = moveX + 'px'; this.event(this.events.THUMBNAIL_MOVE, { thumbnail: thumbnail, move: moveX, remain: remain, container: container.offsetWidth, items: items.scrollWidth }); } } } }; if (delay) { this.timeout(() => { move(); }, delay); } else { move(); } } public modalClick($event?: UIEvent) { if ($event) { $event.stopPropagation(); } this.setFocus(); } // set the focus public setFocus() { if (this.modalVisible) { let element: Node = this.el('div.asg-modal.' + this.id + ' .keyInput')[0]; if (element) { angular.element(element)[0]['focus'](); } } } public event(event: string, data?: any) { event = event + this.id; this.$rootScope.$emit(event, data); this.log(event, data); } public log(event: string, data?: any) { if (this.options.debug) { console.log(event, data ? data : null); } } // get element public el(selector): NodeList { return document.querySelectorAll(selector); } // calculating element real width public getRealWidth(item) { let style = item.currentStyle || window.getComputedStyle(item), width = item.offsetWidth, margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight), // padding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight), border = parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth); return width + margin + border; } // calculating element real height public getRealHeight(item) { let style = item.currentStyle || window.getComputedStyle(item), height = item.offsetHeight, margin = parseFloat(style.marginTop) + parseFloat(style.marginBottom), // padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom), border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); return height + margin + border; } // edit gallery public editGallery(edit: IEdit) { this.editing = true; let selected = this.selected; if (edit.options !== undefined) { this.optionsLoaded = false; this.setOptions(edit.options); } if (edit.delete !== undefined) { this.deleteImage(edit.delete); } if (edit.add) { let length = edit.add.length; for (let key = 0; key < length; key++) { this.addImage(edit.add[key]); } } if (edit.update) { let length = edit.update.length; for (let key = 0; key < length; key++) { this.addImage(edit.update[key], key); } let count = this.files.length - edit.update.length; if (count > 0) { this.deleteImage(length, count); } } if (edit.selected >= 0) { selected = edit.selected; } if (edit.selected == -1) { selected = this.files.length - 1; } selected = this.files[selected] ? selected : (selected >= this.files.length ? this.files.length - 1 : 0); this.forceSelect(this.files[selected] ? selected : 0); this.timeout(() => { this.editing = false; this.event(this.events.GALLERY_UPDATED, edit); this.thumbnailsMove(edit.delayThumbnails !== undefined ? edit.delayThumbnails : 220); this.event(this.events.LAST_THUMBNAIL); }, (edit.delayRefresh !== undefined ? edit.delayRefresh : 420)); } // delete image public deleteImage(index: number, count?: number) { index = index === null || index === undefined ? this.selected : index; count = count ? count : 1; this.files.splice(index, count); } // find image in gallery by modal source public findImage(filename : string) { let length = this.files.length; for (let key = 0; key < length; key++) { if (this.files[key].source.modal === filename) { return this.files[key]; } } return false; } public getFullUrl(url : string, baseUrl?: string) { baseUrl = baseUrl === undefined ? this.options.baseUrl : baseUrl; let isFull = (url.indexOf('//') === 0 || url.indexOf('http') === 0) ? true : false; return isFull ? url : baseUrl + url; } // add image public addImage(value: any, index?: number) { if (value === undefined || value === null) { return; } const self = this; if (angular.isString(value) === true) { value = { source: { modal: value } }; } let getAvailableSource = function (type: string, src: ISource) { if (src[type]) { return self.getFullUrl(src[type]); } else { if (type === 'panel') { type = 'image'; if (src[type]) { return self.getFullUrl(src[type]); } } if (type === 'image') { type = 'modal'; if (src[type]) { return self.getFullUrl(src[type]); } } if (type === 'modal') { type = 'image'; if (src[type]) { return self.getFullUrl(src[type]); } } } }; if (!value.source) { value.source = { modal: value[self.options.fields.source.modal], panel: value[self.options.fields.source.panel], image: value[self.options.fields.source.image], placeholder: value[self.options.fields.source.placeholder] }; } let source = { modal: getAvailableSource('modal', value.source), panel: getAvailableSource('panel', value.source), image: getAvailableSource('image', value.source), color: value.color ? value.color : 'transparent', placeholder: value.placeholder ? self.getFullUrl(value.placeholder) : null }; if (!source.modal) { self.log('invalid image data', { source: source, value: value }); return; } let parts = source.modal.split('/'); let filename = parts[parts.length - 1]; let title, subtitle, description, video; if (self.options.fields !== undefined) { title = value[self.options.fields.title] ? value[self.options.fields.title] : filename; subtitle = value[self.options.fields.subtitle] ? value[self.options.fields.subtitle] : null; description = value[self.options.fields.description] ? value[self.options.fields.description] : null; video = value[self.options.fields.video] ? value[self.options.fields.video] : null; } else { title = filename; subtitle = null; description = null; video = null; } let file = { source: source, title: title, subtitle: subtitle, description: description, video: video, loaded: { modal: false, panel: false, image: false } }; if (index !== undefined && this.files[index] !== undefined) { this.files[index] = file; } else { if (self.options.duplicates !== true && this.findImage(file.source.modal)) { self.event(self.events.DOUBLE_IMAGE, file); return; } this.files.push(file); } } } let app: ng.IModule = angular.module('angularSuperGallery'); app.service('asgService', ['$timeout', '$interval', '$location', '$rootScope', '$window', '$sce', ServiceController]); }
the_stack
import { expect } from "chai"; import { PresenceHandler } from "../src/presencehandler"; // we are a test file and thus our linting rules are slightly different // tslint:disable:no-unused-expression max-file-line-count no-any no-magic-numbers no-string-literal let CLIENT_REQUEST_METHOD = ""; let CLIENT_REQUEST_URL = ""; let CLIENT_REQUEST_DATA = {} as any; let CLIENT_STATE_EVENT_TYPE = ""; let CLIENT_STATE_EVENT_KEY = ""; let CLIENT_STATE_EVENT_DATA = {} as any; function getClient(userId) { CLIENT_REQUEST_METHOD = ""; CLIENT_REQUEST_URL = ""; CLIENT_REQUEST_DATA = {}; CLIENT_STATE_EVENT_TYPE = ""; CLIENT_STATE_EVENT_KEY = ""; CLIENT_STATE_EVENT_DATA = {}; return { getUserId: async () => userId, doRequest: async (method, url, qs, data) => { CLIENT_REQUEST_METHOD = method; CLIENT_REQUEST_URL = url; CLIENT_REQUEST_DATA = data; }, sendStateEvent: async (roomId, type, key, data) => { CLIENT_STATE_EVENT_TYPE = type; CLIENT_STATE_EVENT_KEY = key; CLIENT_STATE_EVENT_DATA = data; }, }; } let INTENT_ENSURE_REGISTERED = false; function getIntent(userId) { INTENT_ENSURE_REGISTERED = false; return { ensureRegistered: async () => { INTENT_ENSURE_REGISTERED = true; }, underlyingClient: getClient(userId), }; } function getHandler(config: any = {}) { CLIENT_STATE_EVENT_TYPE = ""; CLIENT_STATE_EVENT_KEY = ""; CLIENT_STATE_EVENT_DATA = {}; config = Object.assign({ enabled: true, interval: 500, enableStatusState: false, statusStateBlacklist: [], }, config); const bridge = { AS: { isNamespacedUser: (userId) => userId.startsWith("@_puppet"), getIntentForUserId: (userId) => getIntent(userId), }, botIntent: { userId: "@_puppet_bot:example.org" }, puppetStore: { getRoomsOfGhost: async (mxid) => { if (mxid === "@_puppet_1_fox:example.org") { return ["!room1:example.org", "!room2:example.org"]; } return []; }, }, userSync: { getPartsFromMxid: (mxid) => { return { puppetId: 1, userId: mxid.split("_")[3].split(":")[0], }; }, }, } as any; return new PresenceHandler(bridge, config); } let originalDateNow: any; const MOCK_DATE = 100 * 1000; describe("PresenceHandler", () => { beforeEach(() => { originalDateNow = Date.now; Date.now = () => { return MOCK_DATE; }; }); afterEach(() => { Date.now = originalDateNow; }); describe("set", () => { it("should ignore users not handled", () => { const handler = getHandler(); let presenceSet = false; handler["setMatrixPresence"] = ((info) => { presenceSet = true; }) as any; handler.set("@user:example.org", "online"); expect(presenceSet).to.be.false; }); it("should set presence and push to the presence queue", () => { const handler = getHandler(); let presenceSet = false; handler["setMatrixPresence"] = ((info) => { presenceSet = true; }) as any; handler.set("@_puppet_1_fox:example.org", "online"); expect(presenceSet).to.be.true; expect(handler["presenceQueue"].length).to.equal(1); expect(handler["presenceQueue"][0]).eql({ mxid: "@_puppet_1_fox:example.org", presence: "online", last_sent: MOCK_DATE, }); }); it("should update presence, should it already exist", () => { const handler = getHandler(); let presenceSet = false; handler["setMatrixPresence"] = ((info) => { presenceSet = true; }) as any; handler.set("@_puppet_1_fox:example.org", "online"); handler.set("@_puppet_1_fox:example.org", "unavailable"); expect(presenceSet).to.be.true; expect(handler["presenceQueue"].length).to.equal(1); expect(handler["presenceQueue"][0]).eql({ mxid: "@_puppet_1_fox:example.org", presence: "unavailable", last_sent: MOCK_DATE, }); }); }); describe("setStatus", () => { it("should ignore users not handled", () => { const handler = getHandler(); let presenceSet = false; handler["setMatrixPresence"] = ((info) => { presenceSet = true; }) as any; let statusSet = false; handler["setMatrixStatus"] = ((info) => { statusSet = true; }) as any; handler.setStatus("@user:example.org", "fox"); expect(presenceSet).to.be.false; expect(statusSet).to.be.false; }); it("should set status and push to the presence queue", () => { const handler = getHandler(); let presenceSet = false; handler["setMatrixPresence"] = ((info) => { presenceSet = true; }) as any; let statusSet = false; handler["setMatrixStatus"] = ((info) => { statusSet = true; }) as any; handler.setStatus("@_puppet_1_fox:example.org", "fox"); expect(presenceSet).to.be.true; expect(statusSet).to.be.true; expect(handler["presenceQueue"].length).to.equal(1); expect(handler["presenceQueue"][0]).eql({ mxid: "@_puppet_1_fox:example.org", status: "fox", last_sent: MOCK_DATE, }); }); it("should update an status, should it already exist", () => { const handler = getHandler(); let presenceSet = false; handler["setMatrixPresence"] = ((info) => { presenceSet = true; }) as any; let statusSet = false; handler["setMatrixStatus"] = ((info) => { statusSet = true; }) as any; handler.setStatus("@_puppet_1_fox:example.org", "fox"); handler.setStatus("@_puppet_1_fox:example.org", "raccoon"); expect(presenceSet).to.be.true; expect(statusSet).to.be.true; expect(handler["presenceQueue"].length).to.equal(1); expect(handler["presenceQueue"][0]).eql({ mxid: "@_puppet_1_fox:example.org", status: "raccoon", last_sent: Date.now(), }); }); }); describe("setStatusInRoom", () => { it("should ignore users not handled", () => { const handler = getHandler(); let statusSet = false; handler["setMatrixStatusInRoom"] = ((info) => { statusSet = true; }) as any; handler.setStatusInRoom("@user:example.org", "!someroom:example.org"); expect(statusSet).to.be.false; }); it("should ignore users not already found in the queue", () => { const handler = getHandler(); let statusSet = false; handler["setMatrixStatusInRoom"] = ((info) => { statusSet = true; }) as any; handler.setStatusInRoom("@_puppet_1_fox:example.org", "!someroom:example.org"); expect(statusSet).to.be.false; }); it("should pass on the status, if all is OK", () => { const handler = getHandler(); let statusSet = false; handler["setMatrixStatusInRoom"] = ((info) => { statusSet = true; }) as any; handler["presenceQueue"].push({ mxid: "@_puppet_1_fox:example.org", status: "blah", last_sent: 0, }); handler.setStatusInRoom("@_puppet_1_fox:example.org", "!someroom:example.org"); expect(statusSet).to.be.true; }); }); describe("remove", () => { it("should set the mxid as offline", () => { const handler = getHandler(); let setPresence = ""; handler.set = (mxid, presence) => { setPresence = presence; }; handler.remove("@_puppet_1_fox:example.org"); expect(setPresence).to.equal("offline"); }); }); describe("handled", () => { it("should ignore non-ghost users", () => { const handler = getHandler(); const ret = handler["handled"]("@user:example.org"); expect(ret).to.be.false; }); it("should handle ghost users", () => { const handler = getHandler(); const ret = handler["handled"]("@_puppet_1_fox:example.org"); expect(ret).to.be.true; }); }); describe("processIntervalThread", () => { it("should pop and re-push non-offline users", async () => { const handler = getHandler(); handler["presenceQueue"].push({ mxid: "@_puppet_1_fox:example.org", presence: "online", last_sent: 0, }); let setPresence = false; handler["setMatrixPresence"] = async (info) => { setPresence = true; }; await handler["processIntervalThread"](); expect(handler["presenceQueue"].length).to.equal(1); expect(handler["presenceQueue"][0]).eql({ mxid: "@_puppet_1_fox:example.org", presence: "online", last_sent: MOCK_DATE, }); expect(setPresence).to.be.true; }); it("should pop offline users from the queue", async () => { const handler = getHandler(); handler["presenceQueue"].push({ mxid: "@_puppet_1_fox:example.org", presence: "offline", last_sent: 0, }); let setPresence = false; handler["setMatrixPresence"] = async (info) => { setPresence = true; }; await handler["processIntervalThread"](); expect(handler["presenceQueue"].length).to.equal(0); expect(setPresence).to.be.true; }); it("should ignore invalid entries", async () => { const handler = getHandler(); handler["presenceQueue"].push(null as any); let setPresence = false; handler["setMatrixPresence"] = async (info) => { setPresence = true; }; await handler["processIntervalThread"](); expect(handler["presenceQueue"].length).to.equal(0); expect(setPresence).to.be.false; }); it("should not send fresh presence", async () => { const handler = getHandler(); handler["presenceQueue"].push({ mxid: "@_puppet_1_fox:example.org", presence: "online", last_sent: Date.now() - 1, }); let setPresence = false; handler["setMatrixPresence"] = async (info) => { setPresence = true; }; await handler["processIntervalThread"](); expect(handler["presenceQueue"].length).to.equal(1); expect(setPresence).to.be.false; }); }); describe("setMatrixPresence", () => { it("should set present and status", async () => { const handler = getHandler(); const info = { mxid: "@_puppet_1_fox:example.org", presence: "online", status: "fox!", } as any; await handler["setMatrixPresence"](info); expect(INTENT_ENSURE_REGISTERED).to.be.true; expect(CLIENT_REQUEST_METHOD).to.equal("PUT"); expect(CLIENT_REQUEST_URL).to.equal("/_matrix/client/r0/presence/%40_puppet_1_fox%3Aexample.org/status"); expect(CLIENT_REQUEST_DATA).eql({ presence: "online", status_msg: "fox!", }); }); }); describe("setMatrixStatus", () => { it("should fetch all rooms and pass responisbility on", async () => { const handler = getHandler(); let roomCount = 0; handler["setMatrixStatusInRoom"] = async (_, roomId) => { roomCount++; }; const info = { mxid: "@_puppet_1_fox:example.org", status: "Foxies!", last_sent: 0, }; await handler["setMatrixStatus"](info); expect(roomCount).to.equal(2); }); }); describe("setMatrixStatusInRoom", () => { it("should ignore offline blank presence changes", async () => { const handler = getHandler({ enableStatusState: true, }); const info = { mxid: "@_puppet_1_fox:example.org", status: "", presence: "offline", } as any; const roomId = "!room:example.org"; await handler["setMatrixStatusInRoom"](info, roomId); expect(CLIENT_STATE_EVENT_TYPE).to.equal(""); expect(CLIENT_STATE_EVENT_KEY).to.equal(""); expect(CLIENT_STATE_EVENT_DATA).eql({}); }); it("should set status state if setting is enabled", async () => { const handler = getHandler({ enableStatusState: true, }); const info = { mxid: "@_puppet_1_fox:example.org", status: "Foxies!", presence: "online", } as any; const roomId = "!room:example.org"; await handler["setMatrixStatusInRoom"](info, roomId); expect(CLIENT_STATE_EVENT_TYPE).to.equal("im.vector.user_status"); expect(CLIENT_STATE_EVENT_KEY).to.equal("@_puppet_1_fox:example.org"); expect(CLIENT_STATE_EVENT_DATA).eql({ status: "Foxies!", }); }); it("should not set status state if setting is not enabled", async () => { const handler = getHandler({ enableStatusState: false, }); const info = { mxid: "@_puppet_1_fox:example.org", status: "Foxies!", presence: "online", } as any; const roomId = "!room:example.org"; await handler["setMatrixStatusInRoom"](info, roomId); expect(CLIENT_STATE_EVENT_TYPE).to.equal(""); expect(CLIENT_STATE_EVENT_KEY).to.equal(""); expect(CLIENT_STATE_EVENT_DATA).eql({}); }); it("should ignore if presence status user is blacklisted", async () => { const handler = getHandler({ statusStateBlacklist: ["badfox"], enableStatusState: true, }); const info = { mxid: "@_puppet_1_badfox:example.org", status: "Foxies!", presence: "online", } as any; const roomId = "!room:example.org"; await handler["setMatrixStatusInRoom"](info, roomId); expect(CLIENT_STATE_EVENT_TYPE).to.equal(""); expect(CLIENT_STATE_EVENT_KEY).to.equal(""); expect(CLIENT_STATE_EVENT_DATA).eql({}); }); }); });
the_stack
import { LitElement, html, customElement, property, CSSResult, TemplateResult, PropertyValues, internalProperty, svg, } from 'lit-element'; import { HomeAssistant, hasConfigOrEntityChanged, LovelaceCardEditor, getLovelace } from 'custom-card-helpers'; import { HassEntity } from 'home-assistant-js-websocket' import localForage from 'localforage/src/localforage'; import { CARD_VERSION, DEFAULT_COLOR, DEFAULT_CONFIG, DEFAULT_SHOW, DEFAULT_BAR, DEFAULT_ICON } from "./const"; import './editor'; import style from './style'; import type { CardConfig } from "./types/config" import type { CacheData, Point, ApiPoint, Period, Repartition } from './types/card'; import { wrap, unwrap } from "./utils"; /* eslint no-console: 0 */ console.info( `%c Uptime card version ${CARD_VERSION} `, 'color: orange; font-weight: bold; background: black' ); // This puts your card into the UI card picker dialog (window as any).customCards = (window as any).customCards || []; (window as any).customCards.push({ type: 'uptime-card', name: 'Uptime Card', description: 'The uptime card show you the history of your binary sensors in a cool way.', }); @customElement('uptime-card') export class UptimeCard extends LitElement { public static async getConfigElement(): Promise<LovelaceCardEditor> { return document.createElement('uptime-card-editor'); } public static getStubConfig(): object { return {}; } @property({ attribute: false }) public _hass!: HomeAssistant; @internalProperty() private config!: CardConfig; @internalProperty() private sensor?: HassEntity; @internalProperty() private interval!: NodeJS.Timeout; @internalProperty() private cache!: CacheData; @internalProperty() private initialized = false; public set hass(hass: HomeAssistant) { this._hass = hass; this.sensor = hass.states[this.config.entity]; this.initialized = true; this.updateData(); } public setConfig(config: CardConfig): void { if (!config) { throw new Error("Invalid configuration !"); } this.config = { ...DEFAULT_CONFIG, ...config, color: { ...DEFAULT_COLOR, ...config.color }, alias: { ...config.alias }, show: { ...DEFAULT_SHOW, ...config.show }, bar: { ...DEFAULT_BAR, ...config.bar }, tap_action: { action: 'more-info' } }; if (this.initialized) this.updateData() } protected shouldUpdate(changedProps: PropertyValues): boolean { if (!this.config) { return false; } return hasConfigOrEntityChanged(this, changedProps, false); } protected firstUpdated(changedProps: PropertyValues): void { changedProps; this.updateData() } public connectedCallback(): void { super.connectedCallback(); if (this.config.update_interval) { this.interval = setInterval( () => this.updateData(), this.config.update_interval * 1000, ); } } public disconnectedCallback(): void { if (this.interval) { clearInterval(this.interval); } super.disconnectedCallback(); } private async updateData(): Promise<void> { const { entity, hours_to_show } = this.config; this.sensor = this._hass.states[this.config.entity]; if (this.sensor == undefined) { this.cache = { points: [], lastFetched: -1, lastChanged: -1, hoursToShow: hours_to_show } return; } const data: CacheData = await this.getCache(entity); const now = new Date().getTime() let cache: CacheData; if (data == undefined) { // First time we see the entity const lastChanged = new Date(this.sensor.last_changed).getTime(); const point = { x: lastChanged, y: this.sensor.state }; cache = { points: [point], lastFetched: now, lastChanged: lastChanged, hoursToShow: hours_to_show } } else { // When the state is updated const oldestHistory = data.hoursToShow < hours_to_show const lastFetched = oldestHistory ? this.getMinimumDate() : data.lastFetched; const fetchedPoints = await this.fetchRecent(entity, new Date(lastFetched), new Date()); const points = oldestHistory ? fetchedPoints : [...data.points, ...fetchedPoints]; const index = points.findIndex(point => point.x > this.getMinimumDate()); const usefulPoints = index == 0 ? points : points.slice(index - 1); const cleanedPoints = this.cleanPoints(usefulPoints); if (cleanedPoints.length > 0) { cache = { points: cleanedPoints, lastFetched: now, lastChanged: cleanedPoints[cleanedPoints.length - 1].x, hoursToShow: hours_to_show }; } else { const lastChanged = new Date(this.sensor.last_changed).getTime(); const point = { x: lastChanged, y: this.sensor.state }; cache = { points: [point], lastFetched: now, lastChanged: lastChanged, hoursToShow: hours_to_show }; } } await this.setCache(entity, cache) this.cache = cache } async getCache(key: string): Promise<any> { const data: string | null = await localForage.getItem(key); if (data == undefined) { console.warn(`Can't load the key ${key} from cache.`) return null; } else return unwrap(data); } async setCache(key: string, data: any): Promise<any> { return localForage.setItem(key, wrap(data)) } private isOk(state: string): boolean | undefined { const { ok, ko } = this.config if (ok == state) return true; else if (ko == state) return false; else { if (ok == undefined && ko == undefined) return undefined; else if (ok == undefined) return true; else if (ko == undefined) return false; return undefined; } } private findBarPeriod(index: number): Period { const { bar } = this.config const millisecondsPerBar = this.getUptimeSize() / bar.amount const now = new Date().getTime() const to = now - ((bar.amount - 1 - index) * millisecondsPerBar) return { from: to - millisecondsPerBar + 1, to: to, } } private findBarRepartition(period: Period): Repartition { const firstPoint = this.cache.points.findIndex(point => point.x >= period.from); const lastPoint = this.cache.points.findIndex(point => point.x > period.to); const noneRepartition: Repartition = { ok: 0, ko: 0, none: 100 }; let usefulPoints: Point[]; if (this.cache.points.length == 0) return noneRepartition; // All points are before period.from else if (firstPoint == -1) usefulPoints = [this.cache.points[this.cache.points.length - 1]]; // All points are after period.to else if (firstPoint == 0 && lastPoint == 0) return noneRepartition; else { const isNotFirst = firstPoint == 0 ? 0 : 1 const last = lastPoint == -1 ? this.cache.points.length : lastPoint usefulPoints = this.cache.points.slice(firstPoint - isNotFirst, last); } const repartition: Repartition = { ok: 0, ko: 0, none: 0 }; const total = period.to - period.from for (let i = 0; i < usefulPoints.length; i++) { const upper = usefulPoints[i + 1] ? usefulPoints[i + 1].x : period.to; const lower = Math.max(usefulPoints[i].x, period.from); const amount = upper - lower; if (this.isOk(usefulPoints[i].y) == true) repartition.ok += amount; else if (this.isOk(usefulPoints[i].y) == false) repartition.ko += amount; else repartition.none += amount; } const ok = repartition.ok / total * 100; const ko = repartition.ko / total * 100; const none = 100 - (ok + ko); return { ok: ok, ko: ko, none: none }; } private getUptimeSize(): number { const { hours_to_show } = this.config; return hours_to_show * 3.6e+6; } private getMinimumDate(): number { return new Date().getTime() - this.getUptimeSize(); } private getColor(state?: string): string { const { color } = this.config let c: string; if (state == undefined) return color.none if (this.isOk(state) == true) return color.ok else if (this.isOk(state) == false) return color.ko return color.none } private async fetchRecent(entity: string, start: Date, end: Date): Promise<Point[]> { let url = 'history/period'; if (start) url += `/${start.toISOString()}`; url += `?filter_entity_id=${entity}`; if (end) url += `&end_time=${end.toISOString()}`; url += '&minimal_response'; const result: ApiPoint[][] = await this._hass.callApi('GET', url); return result[0].map(result => { return { x: new Date(result.last_changed).getTime(), y: result.state } }); } private cleanPoints(points: Point[]): Point[] { const cleanedPoints: Point[] = [] let lastPointState: string | undefined = undefined for (const point of points) { if (point.y != lastPointState) { cleanedPoints.push(point); lastPointState = point.y; } } return cleanedPoints } /** * Rendering */ protected render(): TemplateResult { const { bar } = this.config const repartitions = [...Array(bar.amount).keys()].map( (_, idx) => { const period = this.findBarPeriod(idx) return this.findBarRepartition(period) } ) return html` <ha-card class="flex"> ${this.renderHeader()} ${this.renderState()} ${this.renderTimeline(repartitions)} ${this.renderFooter(repartitions)} </ha-card> `; } private renderHeader(): TemplateResult | string { const { show } = this.config return show.header ? html` <div class="header flex"> ${this.renderName()} ${this.renderIcon()} </div> `: ""; } private renderName(): TemplateResult { const { name } = this.config return html` <div class="name"> <span>${name}</span> </div> `; } private renderState(): TemplateResult { const { alias, show, color } = this.config let currentStatus: string; let currentColor: string; if (this.sensor == undefined) { currentStatus = "Unknown" currentColor = color.none } else { if (this.isOk(this.sensor.state) == true && alias.ok) currentStatus = alias.ok; else if (this.isOk(this.sensor.state) == false && alias.ko) currentStatus = alias.ko; else if (this.isOk(this.sensor.state) == undefined) currentStatus = "Unknown" else currentStatus = this.sensor.state currentColor = this.getColor(this.sensor.state); } const currentColorCss = `color: ${currentColor};` return show.status ? html` <div class="status"> <span style=${currentColorCss}>${currentStatus}</span> </div> `: html``; } private renderIcon(): TemplateResult | string { const { icon, show } = this.config; const currentIcon = icon || this.sensor?.attributes.icon || DEFAULT_ICON; return show.icon ? html` <div class="icon flex"> <ha-icon .icon=${currentIcon}></ha-icon> </div> ` : ''; } private renderTimeline(repartitions: Repartition[]): TemplateResult | string { const { show, color, bar, severity } = this.config; const width = 500; const spacingTotalWidth = bar.spacing * (bar.amount - 1); const barWidth = Math.floor((width - spacingTotalWidth) / bar.amount) const leftTotalWidth = width - spacingTotalWidth - barWidth * bar.amount if (show.timeline == false) return "" const bars = repartitions.map( (repartition, idx) => { let barColor: string; if (repartition.none == 100) barColor = color.none; else if (repartition.ok == 100) barColor = color.ok; else if (repartition.ko >= severity) barColor = color.ko; else barColor = color.half return this.renderBar(idx * (barWidth + bar.spacing) + (leftTotalWidth / 2), 0, barWidth, bar.height, barColor, bar.round) } ) return html` <div class="timeline"> <svg width='100%' height="100%"} viewBox='0 0 ${width} ${bar.height}'> ${bars} </svg> </div> ` } private renderBar(x: number, y: number, width: number, height: number, color: string, round: number): TemplateResult { return svg`<rect class='bar' x=${x} y=${y} rx=${round} ry=${round} height=${height} width=${width} fill=${color} ></rect>`; } private renderFooter(repartitions: Repartition[]): TemplateResult | string { const { show } = this.config; if (show.footer == false) return "" const sumOk = repartitions.reduce((prev, curr) => prev + curr.ok, 0) const uptime = (sumOk / repartitions.length).toFixed(2); const minimalDate = this.generateMinimalDate() return html` <div class="footer"> <div class="footer-text">${minimalDate}</div> ${this.renderLine()} <div class="footer-text">${uptime}% uptime</div> ${this.renderLine()} <div class="footer-text">Now</div> </div>`; } private generateMinimalDate(): string { const { hours_to_show } = this.config if (hours_to_show == 0) return "Now" else if (hours_to_show % 168 == 0) { const week = hours_to_show / 168 if (week == 1) { return `${week} week ago` } return `${week} weeks ago` } else if (hours_to_show % 24 == 0) { const day = hours_to_show / 24 if (day == 1) { return `${day} day ago` } return `${day} days ago` } else { if (hours_to_show == 1) { return `${hours_to_show} hour ago` } return `${hours_to_show} hours ago` } } private renderLine(): TemplateResult { return html`<div class="line"></div>` } private _showWarning(warning: string): TemplateResult { return html` <hui-warning>${warning}</hui-warning> `; } private _showError(error: string): TemplateResult { const errorCard = document.createElement('hui-error-card'); errorCard.setConfig({ type: 'error', error, origConfig: this.config, }); return html` ${errorCard} `; } static get styles(): CSSResult { return style; } }
the_stack
import * as ec2 from '@aws-cdk/aws-ec2'; import * as iam from '@aws-cdk/aws-iam'; import { AnyPrincipal, Effect, PolicyStatement } from '@aws-cdk/aws-iam'; import { RetentionDays } from '@aws-cdk/aws-logs'; import * as s3 from '@aws-cdk/aws-s3'; import { BlockPublicAccess } from '@aws-cdk/aws-s3'; import * as sqs from '@aws-cdk/aws-sqs'; import { Construct as CoreConstruct, Duration, Stack, Tags } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { createRestrictedSecurityGroups } from './_limited-internet-access'; import { AlarmActions, Domain } from './api'; import { DenyList, Ingestion } from './backend'; import { BackendDashboard } from './backend-dashboard'; import { DenyListRule } from './backend/deny-list/api'; import { Inventory } from './backend/inventory'; import { LicenseList } from './backend/license-list'; import { Orchestration } from './backend/orchestration'; import { PackageStats } from './backend/package-stats'; import { CATALOG_KEY, STORAGE_KEY_PREFIX } from './backend/shared/constants'; import { VersionTracker } from './backend/version-tracker'; import { Repository } from './codeartifact/repository'; import { DomainRedirect, DomainRedirectSource } from './domain-redirect'; import { Monitoring } from './monitoring'; import { IPackageSource } from './package-source'; import { NpmJs } from './package-sources'; import { PackageTag } from './package-tag'; import { PackageTagGroup } from './package-tag-group'; import { PreloadFile } from './preload-file'; import { S3StorageFactory } from './s3/storage'; import { SpdxLicense } from './spdx-license'; import { WebApp, PackageLinkConfig, FeaturedPackages, FeatureFlags, Category } from './webapp'; /** * Props for `ConstructHub`. */ export interface ConstructHubProps { /** * Connect the hub to a domain (requires a hosted zone and a certificate). */ readonly domain?: Domain; /** * Actions to perform when alarms are set. */ readonly alarmActions?: AlarmActions; /** * Whether compute environments for sensitive tasks (which operate on * un-trusted complex data, such as the transliterator, which operates with * externally-sourced npm package tarballs) should run in network-isolated * environments. This implies the creation of additonal resources, including: * * - A VPC with only isolated subnets. * - VPC Endpoints (CloudWatch Logs, CodeArtifact, CodeArtifact API, S3, ...) * - A CodeArtifact Repository with an external connection to npmjs.com * * @deprecated use sensitiveTaskIsolation instead. */ readonly isolateSensitiveTasks?: boolean; /** * Whether compute environments for sensitive tasks (which operate on * un-trusted complex data, such as the transliterator, which operates with * externally-sourced npm package tarballs) should run in network-isolated * environments. This implies the creation of additonal resources, including: * * - A VPC with only isolated subnets. * - VPC Endpoints (CloudWatch Logs, CodeArtifact, CodeArtifact API, S3, ...) * - A CodeArtifact Repository with an external connection to npmjs.com * * @default Isolation.NO_INTERNET_ACCESS */ readonly sensitiveTaskIsolation?: Isolation; /** * How long to retain CloudWatch logs for. * * @defaults RetentionDays.TEN_YEARS */ readonly logRetention?: RetentionDays; /** * The name of the CloudWatch dashboard that represents the health of backend * systems. */ readonly backendDashboardName?: string; /** * A list of packages to block from the construct hub. * * @default [] */ readonly denyList?: DenyListRule[]; /** * The package sources to register with this ConstructHub instance. * * @default - a standard npmjs.com package source will be configured. */ readonly packageSources?: IPackageSource[]; /** * The allowed licenses for packages indexed by this instance of ConstructHub. * * @default [...SpdxLicense.apache(),...SpdxLicense.bsd(),...SpdxLicense.cddl(),...SpdxLicense.epl(),SpdxLicense.ISC,...SpdxLicense.mit(),SpdxLicense.MPL_2_0] */ readonly allowedLicenses?: SpdxLicense[]; /** * When using a CodeArtifact package source, it is often desirable to have * ConstructHub provision it's internal CodeArtifact repository in the same * CodeArtifact domain, and to configure the package source repository as an * upstream of the internal repository. This way, all packages in the source * are available to ConstructHub's backend processing. * * @default - none. */ readonly codeArtifactDomain?: CodeArtifactDomainProps; /** * Configuration for custom package page links. */ readonly packageLinks?: PackageLinkConfig[]; /** * Configuration for custom package tags */ readonly packageTags?: PackageTag[]; /** * Optional configuration for grouping custom package tags */ readonly packageTagGroups?: PackageTagGroup[]; /** * Configuration for packages to feature on the home page. * @default - Display the 10 most recently updated packages */ readonly featuredPackages?: FeaturedPackages; /** * Configure feature flags for the web app. */ readonly featureFlags?: FeatureFlags; /** * Configure whether or not the backend should periodically query NPM * for the number of downloads a package has in the past week, and * display download counts on the web app. * * @default - true if packageSources is not specified (the defaults are * used), false otherwise */ readonly fetchPackageStats?: boolean; /** * Browse categories. Each category will appear in the home page as a button * with a link to the relevant search query. */ readonly categories?: Category[]; /** * Wire construct hub to use the failover storage buckets. * * Do not activate this property until you've populated your failover buckets * with the necessary data. * * @see https://github.com/cdklabs/construct-hub/blob/dev/docs/operator-runbook.md#storage-disaster * @default false */ readonly failoverStorage?: boolean; /** * How frequently all packages should get fully reprocessed. * * See the operator runbook for more information about reprocessing. * @see https://github.com/cdklabs/construct-hub/blob/main/docs/operator-runbook.md * * @default - never */ readonly reprocessFrequency?: Duration; /** * Additional domains which will be set up to redirect to the primary * construct hub domain. * * @default [] */ readonly additionalDomains?: DomainRedirectSource[]; /** * Javascript to run on webapp before app loads */ readonly preloadScript?: PreloadFile; } /** * Information pertaining to an existing CodeArtifact Domain. */ export interface CodeArtifactDomainProps { /** * The name of the CodeArtifact domain. */ readonly name: string; /** * Any upstream repositories in this CodeArtifact domain that should be * configured on the internal CodeArtifact repository. */ readonly upstreams?: string[]; } /** * Construct Hub. */ export class ConstructHub extends CoreConstruct implements iam.IGrantable { private readonly ingestion: Ingestion; public constructor( scope: Construct, id: string, props: ConstructHubProps = {}, ) { super(scope, id); if (props.isolateSensitiveTasks != null && props.sensitiveTaskIsolation != null) { throw new Error('Supplying both isolateSensitiveTasks and sensitiveTaskIsolation is not supported. Remove usage of isolateSensitiveTasks.'); } const storageFactory = S3StorageFactory.getOrCreate(this, { failover: props.failoverStorage, }); const monitoring = new Monitoring(this, 'Monitoring', { alarmActions: props.alarmActions, }); const packageData = storageFactory.newBucket(this, 'PackageData', { blockPublicAccess: BlockPublicAccess.BLOCK_ALL, enforceSSL: true, encryption: s3.BucketEncryption.S3_MANAGED, lifecycleRules: [ // Abort multi-part uploads after 1 day { abortIncompleteMultipartUploadAfter: Duration.days(1) }, // Transition non-current object versions to IA after 1 month { noncurrentVersionTransitions: [ { storageClass: s3.StorageClass.INFREQUENT_ACCESS, transitionAfter: Duration.days(31), }, ], }, // Permanently delete non-current object versions after 3 months { noncurrentVersionExpiration: Duration.days(90), expiredObjectDeleteMarker: true, }, // Permanently delete non-current versions of catalog.json earlier { noncurrentVersionExpiration: Duration.days(7), prefix: CATALOG_KEY }, ], versioned: true, }); const isolation = props.sensitiveTaskIsolation ?? (props.isolateSensitiveTasks ? Isolation.NO_INTERNET_ACCESS : Isolation.UNLIMITED_INTERNET_ACCESS); // Create an internal CodeArtifact repository if we run in network-controlled mode, or if a domain is provided. const codeArtifact = isolation === Isolation.NO_INTERNET_ACCESS || props.codeArtifactDomain != null ? new Repository(this, 'CodeArtifact', { description: 'Proxy to npmjs.com for ConstructHub', domainName: props.codeArtifactDomain?.name, domainExists: props.codeArtifactDomain != null, upstreams: props.codeArtifactDomain?.upstreams, }) : undefined; const { vpc, vpcEndpoints, vpcSubnets, vpcSecurityGroups } = this.createVpc(isolation, codeArtifact); const denyList = new DenyList(this, 'DenyList', { rules: props.denyList ?? [], packageDataBucket: packageData, packageDataKeyPrefix: STORAGE_KEY_PREFIX, monitoring: monitoring, }); // disable fetching package stats by default if a different package // source is configured const fetchPackageStats = props.fetchPackageStats ?? ( props.packageSources ? false : true ); let packageStats: PackageStats | undefined; const statsKey = 'stats.json'; if (fetchPackageStats) { packageStats = new PackageStats(this, 'Stats', { bucket: packageData, monitoring, logRetention: props.logRetention, objectKey: statsKey, }); } const versionTracker = new VersionTracker(this, 'VersionTracker', { bucket: packageData, monitoring, logRetention: props.logRetention, }); const orchestration = new Orchestration(this, 'Orchestration', { bucket: packageData, codeArtifact, denyList, logRetention: props.logRetention, monitoring, vpc, vpcEndpoints, vpcSubnets, vpcSecurityGroups, }); // rebuild the catalog when the deny list changes. denyList.prune.onChangeInvoke(orchestration.catalogBuilder.function); const packageTagsSerialized = props.packageTags?.map((config) => { return { ...config, condition: config.condition.bind(), }; }) ?? []; this.ingestion = new Ingestion(this, 'Ingestion', { bucket: packageData, codeArtifact, orchestration, logRetention: props.logRetention, monitoring, packageLinks: props.packageLinks, packageTags: packageTagsSerialized, reprocessFrequency: props.reprocessFrequency, }); const licenseList = new LicenseList(this, 'LicenseList', { licenses: props.allowedLicenses ?? [ ...SpdxLicense.apache(), ...SpdxLicense.bsd(), ...SpdxLicense.cddl(), ...SpdxLicense.epl(), SpdxLicense.ISC, ...SpdxLicense.mit(), SpdxLicense.MPL_2_0, ], }); const webApp = new WebApp(this, 'WebApp', { domain: props.domain, monitoring, packageData, packageLinks: props.packageLinks, packageTags: packageTagsSerialized, packageTagGroups: props.packageTagGroups, featuredPackages: props.featuredPackages, packageStats, featureFlags: props.featureFlags, categories: props.categories, preloadScript: props.preloadScript, }); const sources = new CoreConstruct(this, 'Sources'); const packageSources = (props.packageSources ?? [new NpmJs()]).map( (source) => source.bind(sources, { baseUrl: webApp.baseUrl, denyList, ingestion: this.ingestion, licenseList, monitoring, queue: this.ingestion.queue, repository: codeArtifact, }), ); const inventory = new Inventory(this, 'InventoryCanary', { bucket: packageData, logRetention: props.logRetention, monitoring }); new BackendDashboard(this, 'BackendDashboard', { packageData, dashboardName: props.backendDashboardName, packageSources, ingestion: this.ingestion, inventory, orchestration, denyList, packageStats, versionTracker, }); // add domain redirects if (props.domain) { for (const redirctSource of props.additionalDomains ?? []) { new DomainRedirect(this, `Redirect-${redirctSource.hostedZone.zoneName}`, { source: redirctSource, targetDomainName: props.domain?.zone.zoneName, }); } } else { if (props.additionalDomains && props.additionalDomains.length > 0) { throw new Error('Cannot specify "domainRedirects" if a domain is not specified'); } } } public get grantPrincipal(): iam.IPrincipal { return this.ingestion.grantPrincipal; } public get ingestionQueue(): sqs.IQueue { return this.ingestion.queue; } private createVpc(isolation: Isolation, codeArtifact: Repository | undefined) { if (isolation === Isolation.UNLIMITED_INTERNET_ACCESS) { return { vpc: undefined, vpcEndpoints: undefined, vpcSubnets: undefined }; } const subnetType = isolation === Isolation.NO_INTERNET_ACCESS ? ec2.SubnetType.ISOLATED : ec2.SubnetType.PRIVATE_WITH_NAT; const vpcSubnets = { subnetType }; const vpc = new ec2.Vpc(this, 'VPC', { enableDnsHostnames: true, enableDnsSupport: true, // Provision no NAT gateways if we are running ISOLATED (we wouldn't have a public subnet) natGateways: subnetType === ec2.SubnetType.ISOLATED ? 0 : undefined, // Pre-allocating PUBLIC / PRIVATE / INTERNAL subnets, regardless of use, so we don't create // a whole new VPC if we ever need to introduce subnets of these types. subnetConfiguration: [ // If there is a PRIVATE subnet, there must also have a PUBLIC subnet (for NAT gateways). { name: 'Public', subnetType: ec2.SubnetType.PUBLIC, reserved: subnetType === ec2.SubnetType.ISOLATED }, { name: 'Private', subnetType: ec2.SubnetType.PRIVATE_WITH_NAT, reserved: subnetType === ec2.SubnetType.ISOLATED }, { name: 'Isolated', subnetType: ec2.SubnetType.ISOLATED, reserved: subnetType !== ec2.SubnetType.ISOLATED }, ], }); Tags.of(vpc.node.defaultChild!).add('Name', vpc.node.path); const securityGroups = subnetType === ec2.SubnetType.PRIVATE_WITH_NAT ? createRestrictedSecurityGroups(this, vpc) : undefined; // Creating the CodeArtifact endpoints only if a repository is present. const codeArtifactEndpoints = codeArtifact && { codeArtifactApi: vpc.addInterfaceEndpoint('CodeArtifact.API', { privateDnsEnabled: false, service: new ec2.InterfaceVpcEndpointAwsService('codeartifact.api'), subnets: vpcSubnets, securityGroups, }), codeArtifact: vpc.addInterfaceEndpoint('CodeArtifact', { privateDnsEnabled: true, service: new ec2.InterfaceVpcEndpointAwsService('codeartifact.repositories'), subnets: vpcSubnets, securityGroups, }), }; // We'll only use VPC endpoints if we are configured to run in an ISOLATED subnet. const vpcEndpoints = { ...codeArtifactEndpoints, // This is needed so that ECS workloads can use the awslogs driver cloudWatchLogs: vpc.addInterfaceEndpoint('CloudWatch.Logs', { privateDnsEnabled: true, service: ec2.InterfaceVpcEndpointAwsService.CLOUDWATCH_LOGS, subnets: vpcSubnets, securityGroups, }), // These are needed for ECS workloads to be able to pull images ecrApi: vpc.addInterfaceEndpoint('ECR.API', { privateDnsEnabled: true, service: ec2.InterfaceVpcEndpointAwsService.ECR, subnets: vpcSubnets, securityGroups, }), ecr: vpc.addInterfaceEndpoint('ECR.Docker', { privateDnsEnabled: true, service: ec2.InterfaceVpcEndpointAwsService.ECR_DOCKER, subnets: vpcSubnets, securityGroups, }), // This is needed (among others) for CodeArtifact registry usage s3: vpc.addGatewayEndpoint('S3', { service: ec2.GatewayVpcEndpointAwsService.S3, subnets: [vpcSubnets], }), // This is useful for getting results from ECS tasks within workflows stepFunctions: vpc.addInterfaceEndpoint('StepFunctions', { privateDnsEnabled: true, service: ec2.InterfaceVpcEndpointAwsService.STEP_FUNCTIONS, subnets: vpcSubnets, securityGroups, }), }; // The S3 access is necessary for the CodeArtifact Repository and ECR Docker // endpoints to be used (they serve objects from S3). vpcEndpoints.s3.addToPolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ['s3:GetObject'], resources: [ // The in-region CodeArtifact S3 Bucket ...codeArtifact ? [`${codeArtifact.s3BucketArn}/*`] : [], // The in-region ECR layer bucket `arn:aws:s3:::prod-${Stack.of(this).region}-starport-layer-bucket/*`, ], // It doesn't seem we can constrain principals for these grants (unclear // which principal those calls are made from, or if that is something we // could name here). principals: [new AnyPrincipal()], sid: 'Allow-CodeArtifact-and-ECR', })); return { vpc, vpcEndpoints, vpcSubnets, vpcSecurityGroups: securityGroups }; } } /** * How possibly risky operations (such as doc-generation, which requires * installing the indexed packages in order to trans-literate sample code) are * isolated to mitigate possible arbitrary code execution vulnerabilities in and * around `npm install` or the transliterator's use of the TypeScript compiler. */ export enum Isolation { /** * No isolation is done whatsoever. The doc-generation process still is * provisioned with least-privilege permissions, but retains complete access * to internet. * * While this maximizes the chances of successfully installing packages (and * hence successfully generating documentation for those), it is also the * least secure mode of operation. * * We advise you only consider using this isolation mode if you are hosting a * ConstructHub instance that only indexes trusted packages (including * transitive dependencies). */ UNLIMITED_INTERNET_ACCESS, /** * The same protections as `UNLIMITED_INTERNET_ACCESS`, except outbound * internet connections are limited to IP address ranges corresponding to * hosting endpoints for npmjs.com. */ LIMITED_INTERNET_ACCESS, /** * The same protections as `LIMITED_INTERNET_ACCESS`, except all remaining * internet access is removed. All traffic to AWS service endpoints is routed * through VPC Endpoints, as the compute nodes are jailed in a completely * isolated VPC. * * This is the most secure (and recommended) mode of operation for * ConstructHub instances. */ NO_INTERNET_ACCESS, }
the_stack
import BigNumber from 'bignumber.js'; import Web3 from 'web3'; import { Contract } from 'web3-eth-contract'; import { Contracts } from './Contracts'; import { addressToBytes32, bnToBytes32, hashString, addressesAreEqual, combineHexStrings, } from '../lib/BytesHelper'; import { SIGNATURE_TYPES, EIP712_DOMAIN_STRING, EIP712_DOMAIN_STRUCT, createTypedSignature, ecRecoverTypedSignature, ethSignTypedDataInternal, hashHasValidSignature, getEIP712Hash, } from '../lib/SignatureHelper'; import { Balance, BigNumberable, CallOptions, Fee, Order, OrderState, Price, SendOptions, SignedOrder, SigningMethod, TypedSignature, address, } from '../lib/types'; import { ORDER_FLAGS } from '../lib/Constants'; const EIP712_ORDER_STRUCT = [ { type: 'bytes32', name: 'flags' }, { type: 'uint256', name: 'amount' }, { type: 'uint256', name: 'limitPrice' }, { type: 'uint256', name: 'triggerPrice' }, { type: 'uint256', name: 'limitFee' }, { type: 'address', name: 'maker' }, { type: 'address', name: 'taker' }, { type: 'uint256', name: 'expiration' }, ]; const DEFAULT_EIP712_DOMAIN_NAME = 'P1Orders'; const EIP712_DOMAIN_VERSION = '1.0'; const EIP712_ORDER_STRUCT_STRING = 'Order(' + 'bytes32 flags,' + 'uint256 amount,' + 'uint256 limitPrice,' + 'uint256 triggerPrice,' + 'uint256 limitFee,' + 'address maker,' + 'address taker,' + 'uint256 expiration' + ')'; const EIP712_CANCEL_ORDER_STRUCT = [ { type: 'string', name: 'action' }, { type: 'bytes32[]', name: 'orderHashes' }, ]; const EIP712_CANCEL_ORDER_STRUCT_STRING = 'CancelLimitOrder(' + 'string action,' + 'bytes32[] orderHashes' + ')'; export class Orders { private contracts: Contracts; private web3: Web3; private eip712DomainName: string; private orders: Contract; // ============ Constructor ============ constructor( contracts: Contracts, web3: Web3, eip712DomainName: string = DEFAULT_EIP712_DOMAIN_NAME, orders: Contract = contracts.p1Orders, ) { this.contracts = contracts; this.web3 = web3; this.eip712DomainName = eip712DomainName; this.orders = orders; } get address(): address { return this.orders.options.address; } // ============ On-Chain Approve / On-Chain Cancel ============ /** * Sends an transaction to pre-approve an order on-chain (so that no signature is required when * filling the order). */ public async approveOrder( order: Order, options?: SendOptions, ): Promise<any> { const stringifiedOrder = this.orderToSolidity(order); return this.contracts.send( this.orders.methods.approveOrder(stringifiedOrder), options, ); } /** * Sends an transaction to cancel an order on-chain. */ public async cancelOrder( order: Order, options?: SendOptions, ): Promise<any> { const stringifiedOrder = this.orderToSolidity(order); return this.contracts.send( this.orders.methods.cancelOrder(stringifiedOrder), options, ); } // ============ Getter Contract Methods ============ /** * Gets the status and the current filled amount (in makerAmount) of all given orders. */ public async getOrdersStatus( orders: Order[], options?: CallOptions, ): Promise<OrderState[]> { const orderHashes = orders.map(order => this.getOrderHash(order)); const states: any[] = await this.contracts.call( this.orders.methods.getOrdersStatus(orderHashes), options, ); return states.map((state) => { return { status: parseInt(state[0], 10), filledAmount: new BigNumber(state[1]), }; }); } // ============ Off-Chain Helper Functions ============ /** * Estimate the maker's collateralization after executing a sequence of orders. * * The `maker` of every order must be the same. This function does not make any on-chain calls, * so all information must be passed in, including the oracle price and remaining amounts * on the orders. Orders are assumed to be filled at the limit price and limit fee. * * Returns the ending collateralization ratio for the account, or BigNumber(Infinity) if the * account does not end with any negative balances. * * @param initialBalance The initial margin and position balances of the maker account. * @param oraclePrice The price at which to calculate collateralization. * @param orders A sequence of orders, with the same maker, to be hypothetically filled. * @param fillAmounts The corresponding fill amount for each order, denominated in the token * spent by the maker--quote currency when buying, and base when selling. */ public getAccountCollateralizationAfterMakingOrders( initialBalance: Balance, oraclePrice: Price, orders: Order[], makerTokenFillAmounts: BigNumber[], ): BigNumber { const runningBalance: Balance = initialBalance.copy(); // For each order, determine the effect on the balance by following the smart contract math. for (let i = 0; i < orders.length; i += 1) { const order = orders[i]; const fillAmount = order.isBuy ? makerTokenFillAmounts[i].dividedBy(order.limitPrice.value) : makerTokenFillAmounts[i]; // Assume orders are filled at the limit price and limit fee. const { marginDelta, positionDelta } = this.getBalanceUpdatesAfterFillingOrder( fillAmount, order.limitPrice, order.limitFee, order.isBuy, ); runningBalance.margin = runningBalance.margin.plus(marginDelta); runningBalance.position = runningBalance.position.plus(positionDelta); } return runningBalance.getCollateralization(oraclePrice); } /** * Calculate the effect of filling an order on the maker's balances. */ public getBalanceUpdatesAfterFillingOrder( fillAmount: BigNumberable, fillPrice: Price, fillFee: Fee, isBuy: boolean, ): { marginDelta: BigNumber, positionDelta: BigNumber, } { const positionAmount = new BigNumber(fillAmount).dp(0, BigNumber.ROUND_DOWN); const fee = fillFee.times(fillPrice.value).value.dp(18, BigNumber.ROUND_DOWN); const marginPerPosition = isBuy ? fillPrice.plus(fee) : fillPrice.minus(fee); const marginAmount = positionAmount.times(marginPerPosition.value).dp(0, BigNumber.ROUND_DOWN); return { marginDelta: isBuy ? marginAmount.negated() : marginAmount, positionDelta: isBuy ? positionAmount : positionAmount.negated(), }; } public getFeeForOrder( amount: BigNumber, isTaker: boolean = true, ): Fee { if (!isTaker) { return Fee.fromBips('-2.5'); } // PBTC-USDC: Small order size is 0.5 BTC. // // TODO: Address fees more generally on a per-market basis. const isSmall = amount.lt('0.5e8'); return isSmall ? Fee.fromBips('50.0') : Fee.fromBips('15'); } // ============ Signing Methods ============ public async getSignedOrder( order: Order, signingMethod: SigningMethod, ): Promise<SignedOrder> { const typedSignature = await this.signOrder(order, signingMethod); return { ...order, typedSignature, }; } /** * Sends order to current provider for signing. Can sign locally if the signing account is * loaded into web3 and SigningMethod.Hash is used. */ public async signOrder( order: Order, signingMethod: SigningMethod, ): Promise<string> { switch (signingMethod) { case SigningMethod.Hash: case SigningMethod.UnsafeHash: case SigningMethod.Compatibility: const orderHash = this.getOrderHash(order); const rawSignature = await this.web3.eth.sign(orderHash, order.maker); const hashSig = createTypedSignature(rawSignature, SIGNATURE_TYPES.DECIMAL); if (signingMethod === SigningMethod.Hash) { return hashSig; } const unsafeHashSig = createTypedSignature(rawSignature, SIGNATURE_TYPES.NO_PREPEND); if (signingMethod === SigningMethod.UnsafeHash) { return unsafeHashSig; } if (hashHasValidSignature(orderHash, unsafeHashSig, order.maker)) { return unsafeHashSig; } return hashSig; case SigningMethod.TypedData: case SigningMethod.MetaMask: case SigningMethod.MetaMaskLatest: case SigningMethod.CoinbaseWallet: return this.ethSignTypedOrderInternal( order, signingMethod, ); default: throw new Error(`Invalid signing method ${signingMethod}`); } } /** * Sends order to current provider for signing of a cancel message. Can sign locally if the * signing account is loaded into web3 and SigningMethod.Hash is used. */ public async signCancelOrder( order: Order, signingMethod: SigningMethod, ): Promise<string> { return this.signCancelOrderByHash( this.getOrderHash(order), order.maker, signingMethod, ); } /** * Sends orderHash to current provider for signing of a cancel message. Can sign locally if * the signing account is loaded into web3 and SigningMethod.Hash is used. */ public async signCancelOrderByHash( orderHash: string, signer: string, signingMethod: SigningMethod, ): Promise<string> { switch (signingMethod) { case SigningMethod.Hash: case SigningMethod.UnsafeHash: case SigningMethod.Compatibility: const cancelHash = this.orderHashToCancelOrderHash(orderHash); const rawSignature = await this.web3.eth.sign(cancelHash, signer); const hashSig = createTypedSignature(rawSignature, SIGNATURE_TYPES.DECIMAL); if (signingMethod === SigningMethod.Hash) { return hashSig; } const unsafeHashSig = createTypedSignature(rawSignature, SIGNATURE_TYPES.NO_PREPEND); if (signingMethod === SigningMethod.UnsafeHash) { return unsafeHashSig; } if (hashHasValidSignature(cancelHash, unsafeHashSig, signer)) { return unsafeHashSig; } return hashSig; case SigningMethod.TypedData: case SigningMethod.MetaMask: case SigningMethod.MetaMaskLatest: case SigningMethod.CoinbaseWallet: return this.ethSignTypedCancelOrderInternal( orderHash, signer, signingMethod, ); default: throw new Error(`Invalid signing method ${signingMethod}`); } } // ============ Signature Verification ============ /** * Returns true if the order object has a non-null valid signature from the maker of the order. */ public orderHasValidSignature( order: SignedOrder, ): boolean { return hashHasValidSignature( this.getOrderHash(order), order.typedSignature, order.maker, ); } /** * Returns true if the order hash has a non-null valid signature from a particular signer. */ public orderByHashHasValidSignature( orderHash: string, typedSignature: string, expectedSigner: address, ): boolean { const signer = ecRecoverTypedSignature(orderHash, typedSignature); return addressesAreEqual(signer, expectedSigner); } /** * Returns true if the cancel order message has a valid signature. */ public cancelOrderHasValidSignature( order: Order, typedSignature: string, ): boolean { return this.cancelOrderByHashHasValidSignature( this.getOrderHash(order), typedSignature, order.maker, ); } /** * Returns true if the cancel order message has a valid signature. */ public cancelOrderByHashHasValidSignature( orderHash: string, typedSignature: string, expectedSigner: address, ): boolean { const cancelHash = this.orderHashToCancelOrderHash(orderHash); const signer = ecRecoverTypedSignature(cancelHash, typedSignature); return addressesAreEqual(signer, expectedSigner); } // ============ Hashing Functions ============ /** * Returns the final signable EIP712 hash for approving an order. */ public getOrderHash( order: Order, ): string { const structHash = Web3.utils.soliditySha3( { t: 'bytes32', v: hashString(EIP712_ORDER_STRUCT_STRING) }, { t: 'bytes32', v: this.getOrderFlags(order) }, { t: 'uint256', v: order.amount.toFixed(0) }, { t: 'uint256', v: order.limitPrice.toSolidity() }, { t: 'uint256', v: order.triggerPrice.toSolidity() }, { t: 'uint256', v: order.limitFee.toSolidity() }, { t: 'bytes32', v: addressToBytes32(order.maker) }, { t: 'bytes32', v: addressToBytes32(order.taker) }, { t: 'uint256', v: order.expiration.toFixed(0) }, ); return getEIP712Hash(this.getDomainHash(), structHash); } /** * Given some order hash, returns the hash of a cancel-order message. */ public orderHashToCancelOrderHash( orderHash: string, ): string { const structHash = Web3.utils.soliditySha3( { t: 'bytes32', v: hashString(EIP712_CANCEL_ORDER_STRUCT_STRING) }, { t: 'bytes32', v: hashString('Cancel Orders') }, { t: 'bytes32', v: Web3.utils.soliditySha3({ t: 'bytes32', v: orderHash }) }, ); return getEIP712Hash(this.getDomainHash(), structHash); } /** * Returns the EIP712 domain separator hash. */ public getDomainHash(): string { return Web3.utils.soliditySha3( { t: 'bytes32', v: hashString(EIP712_DOMAIN_STRING) }, { t: 'bytes32', v: hashString(this.eip712DomainName) }, { t: 'bytes32', v: hashString(EIP712_DOMAIN_VERSION) }, { t: 'uint256', v: `${this.contracts.networkId}` }, { t: 'bytes32', v: addressToBytes32(this.address) }, ); } // ============ To-Bytes Functions ============ public orderToBytes( order: Order, ): string { const solidityOrder = this.orderToSolidity(order); return this.web3.eth.abi.encodeParameters( EIP712_ORDER_STRUCT.map(arg => arg.type), EIP712_ORDER_STRUCT.map(arg => solidityOrder[arg.name]), ); } public fillToTradeData( order: SignedOrder, amount: BigNumber, price: Price, fee: Fee, ): string { const orderData = this.orderToBytes(order); const signatureData = order.typedSignature + '0'.repeat(60); const fillData = this.web3.eth.abi.encodeParameters( [ 'uint256', 'uint256', 'uint256', 'bool', ], [ amount.toFixed(0), price.toSolidity(), fee.toSolidity(), fee.isNegative(), ], ); return combineHexStrings(orderData, fillData, signatureData); } // ============ Private Helper Functions ============ private orderToSolidity( order: Order, ): any { return { flags: this.getOrderFlags(order), amount: order.amount.toFixed(0), limitPrice: order.limitPrice.toSolidity(), triggerPrice: order.triggerPrice.toSolidity(), limitFee: order.limitFee.toSolidity(), maker: order.maker, taker: order.taker, expiration: order.expiration.toFixed(0), }; } private getDomainData() { return { name: this.eip712DomainName, version: EIP712_DOMAIN_VERSION, chainId: this.contracts.networkId, verifyingContract: this.address, }; } private async ethSignTypedOrderInternal( order: Order, signingMethod: SigningMethod, ): Promise<TypedSignature> { const orderData = this.orderToSolidity(order); const data = { types: { EIP712Domain: EIP712_DOMAIN_STRUCT, Order: EIP712_ORDER_STRUCT, }, domain: this.getDomainData(), primaryType: 'Order', message: orderData, }; return ethSignTypedDataInternal( this.web3.currentProvider, order.maker, data, signingMethod, ); } private async ethSignTypedCancelOrderInternal( orderHash: string, signer: string, signingMethod: SigningMethod, ): Promise<TypedSignature> { const data = { types: { EIP712Domain: EIP712_DOMAIN_STRUCT, CancelLimitOrder: EIP712_CANCEL_ORDER_STRUCT, }, domain: this.getDomainData(), primaryType: 'CancelLimitOrder', message: { action: 'Cancel Orders', orderHashes: [orderHash], }, }; return ethSignTypedDataInternal( this.web3.currentProvider, signer, data, signingMethod, ); } private getOrderFlags( order: Order, ): string { const booleanFlag = 0 + (order.limitFee.isNegative() ? ORDER_FLAGS.IS_NEGATIVE_LIMIT_FEE : 0) + (order.isDecreaseOnly ? ORDER_FLAGS.IS_DECREASE_ONLY : 0) + (order.isBuy ? ORDER_FLAGS.IS_BUY : 0); const saltBytes = bnToBytes32(order.salt); return `0x${saltBytes.slice(-63)}${booleanFlag}`; } }
the_stack
import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import fetchMock from 'fetch-mock'; import React from 'react'; import { QueryClient, QueryClientProvider } from 'react-query'; import { modelName } from '../../types/models'; import { Deferred } from '../../utils/tests/Deferred'; import { playlistMockFactory, videoMockFactory, } from '../../utils/tests/factories'; import { wrapInIntlProvider } from '../../utils/tests/intl'; import { UploadManagerContext, UploadManagerStatus } from '../UploadManager'; import { VideoCreateForm } from '.'; jest.mock('../../data/appData', () => ({ appData: {}, })); describe('<VideoCreateForm />', () => { jest.spyOn(console, 'error').mockImplementation(() => jest.fn()); beforeEach(() => { fetchMock.restore(); }); it('lets the user create a video with the title and playlist ID through 3 steps', async () => { const queryClient = new QueryClient(); const postStep1Deferred = new Deferred(); fetchMock.post('/api/videos/', postStep1Deferred.promise); const playlist = playlistMockFactory(); const video = videoMockFactory({ title: 'new video title', playlist }); const { rerender } = render( wrapInIntlProvider( <QueryClientProvider client={queryClient}> <UploadManagerContext.Provider value={{ setUploadState: jest.fn(), uploadManagerState: {} }} > <VideoCreateForm /> </UploadManagerContext.Provider> </QueryClientProvider>, ), ); { // Step 1 const titleField = screen.getByRole('textbox', { name: 'Title' }); const playlistField = screen.getByRole('textbox', { name: 'Playlist ID', }); const btn = screen.getByRole('button', { name: 'Create the video' }); screen.getByRole('list', { name: 'Video creation progress' }); { const step1 = screen.getByRole('listitem', { name: 'Current: Video details (1/3)', }); expect(step1).toHaveAttribute('aria-current', 'step'); const step2 = screen.getByRole('listitem', { name: 'File selection (2/3)', }); expect(step2).toHaveAttribute('aria-current', 'false'); const step3 = screen.getByRole('listitem', { name: 'Processing (3/3)', }); expect(step3).toHaveAttribute('aria-current', 'false'); } // The form does not send when the title field is not set userEvent.click(btn); screen.getByText('The title is required to create a new video.'); // The form does not send when the playlist is not passed and the playlist field is not set userEvent.type(titleField, 'new video title'); userEvent.click(btn); screen.getByText('The playlist ID is required to create a new video.'); expect( screen.queryByText('The title is required to create a new video.'), ).toBeNull(); userEvent.type(playlistField, playlist.id); userEvent.click(btn); expect( screen.queryByText('The title is required to create a new video.'), ).toBeNull(); expect( screen.queryByText( 'The playlist ID is required to create a new video.', ), ).toBeNull(); await waitFor(() => { expect( fetchMock.called('/api/videos/', { body: { title: 'new video title', playlist: playlist.id }, method: 'POST', }), ).toEqual(true); }); screen.getByRole('status', { name: 'Creating video...' }); await act(async () => postStep1Deferred.resolve(video)); } { // Step 2 is the file upload field screen.getByRole('button', { name: 'Select a file to upload', }); { const step1 = screen.getByRole('listitem', { name: 'Completed: Video details (1/3)', }); expect(step1).toHaveAttribute('aria-current', 'false'); const step2 = screen.getByRole('listitem', { name: 'Current: File selection (2/3)', }); expect(step2).toHaveAttribute('aria-current', 'step'); const step3 = screen.getByRole('listitem', { name: 'Processing (3/3)', }); expect(step3).toHaveAttribute('aria-current', 'false'); } // Rerender with a different value in upload manager to simulate an ongoing upload rerender( wrapInIntlProvider( <QueryClientProvider client={queryClient}> <UploadManagerContext.Provider value={{ setUploadState: jest.fn(), uploadManagerState: { [video.id]: { file: new File(['(⌐□_□)'], 'course.mp4', { type: 'video/mp4', }), objectId: video.id, objectType: modelName.VIDEOS, progress: 10, status: UploadManagerStatus.UPLOADING, }, }, }} > <VideoCreateForm /> </UploadManagerContext.Provider> </QueryClientProvider>, ), ); // Step 3 is just the ongoing upload with some help text for users screen.getByRole('button', { name: 'Create another video' }); screen.getByText('Video creation in progress'); screen.getByText( 'You can use the file uploads manager to monitor ongoing uploads, or go to the video page to start adding subtitles.', ); { const step1 = screen.getByRole('listitem', { name: 'Completed: Video details (1/3)', }); expect(step1).toHaveAttribute('aria-current', 'false'); const step2 = screen.getByRole('listitem', { name: 'Completed: File selection (2/3)', }); expect(step2).toHaveAttribute('aria-current', 'false'); const step3 = screen.getByRole('listitem', { name: 'Current: Processing (3/3)', }); expect(step3).toHaveAttribute('aria-current', 'step'); } } }); it('does not ask for the playlist ID it it is provided to the form as a prop', async () => { const queryClient = new QueryClient(); const postStep1Deferred = new Deferred(); fetchMock.post('/api/videos/', postStep1Deferred.promise); const playlist = playlistMockFactory(); const video = videoMockFactory({ title: 'new video title', playlist }); render( wrapInIntlProvider( <QueryClientProvider client={queryClient}> <VideoCreateForm playlist={playlist.id} /> </QueryClientProvider>, ), ); const titleField = screen.getByRole('textbox', { name: 'Title' }); expect( screen.queryByRole('textbox', { name: 'Playlist ID', }), ).toBeNull(); const btn = screen.getByRole('button', { name: 'Create the video' }); screen.getByRole('list', { name: 'Video creation progress' }); // The form does not send when the title field is not set userEvent.click(btn); screen.getByText('The title is required to create a new video.'); // As the playlist ID is available to the component, it does not ask it from the user userEvent.type(titleField, 'new video title'); userEvent.click(btn); expect( screen.queryByText('The title is required to create a new video.'), ).toBeNull(); await waitFor(() => { expect( fetchMock.called('/api/videos/', { body: { title: 'new video title', playlist: playlist.id }, method: 'POST', }), ).toEqual(true); }); screen.getByRole('status', { name: 'Creating video...' }); await act(async () => postStep1Deferred.resolve(video)); // We move on to step 2, which is covered by the previous test screen.getByRole('button', { name: 'Select a file to upload', }); }); it('shows errors on the title field as they are returned by the API', async () => { const queryClient = new QueryClient(); const postStep1Deferred = new Deferred(); fetchMock.post('/api/videos/', postStep1Deferred.promise); const playlist = playlistMockFactory(); render( wrapInIntlProvider( <QueryClientProvider client={queryClient}> <VideoCreateForm /> </QueryClientProvider>, ), ); const titleField = screen.getByRole('textbox', { name: 'Title' }); const playlistField = screen.getByRole('textbox', { name: 'Playlist ID', }); const btn = screen.getByRole('button', { name: 'Create the video' }); screen.getByRole('list', { name: 'Video creation progress' }); userEvent.type(titleField, 'new video title'); userEvent.type(playlistField, playlist.id); userEvent.click(btn); await waitFor(() => { expect( fetchMock.called('/api/videos/', { body: { title: 'new video title', playlist: playlist.id }, method: 'POST', }), ).toEqual(true); }); screen.getByRole('status', { name: 'Creating video...' }); await act(async () => postStep1Deferred.resolve({ status: 400, body: { errors: [ { title: ['Some title related error.', 'Another title error.'], }, ], }, }), ); screen.getByText('Some title related error.'); screen.getByText('Another title error.'); }); it('shows errors on the playlist ID field as they are returned by the API', async () => { const queryClient = new QueryClient(); const postStep1Deferred = new Deferred(); fetchMock.post('/api/videos/', postStep1Deferred.promise); const playlist = playlistMockFactory(); render( wrapInIntlProvider( <QueryClientProvider client={queryClient}> <VideoCreateForm /> </QueryClientProvider>, ), ); const titleField = screen.getByRole('textbox', { name: 'Title' }); const playlistField = screen.getByRole('textbox', { name: 'Playlist ID', }); const btn = screen.getByRole('button', { name: 'Create the video' }); screen.getByRole('list', { name: 'Video creation progress' }); userEvent.type(titleField, 'new video title'); userEvent.type(playlistField, playlist.id); userEvent.click(btn); await waitFor(() => { expect( fetchMock.called('/api/videos/', { body: { title: 'new video title', playlist: playlist.id }, method: 'POST', }), ).toEqual(true); }); screen.getByRole('status', { name: 'Creating video...' }); await act(async () => postStep1Deferred.resolve({ status: 400, body: { errors: [ { playlist: [ 'Some playlist related error.', 'Another playlist error.', ], }, ], }, }), ); screen.getByText('Some playlist related error.'); screen.getByText('Another playlist error.'); }); });
the_stack
import { Component, OnInit } from '@angular/core'; import { IndexeddbService } from '../indexeddb.service'; import { Router } from '@angular/router'; import { ApiService } from '../api.service'; import { DialogApikeyComponent } from '../dialog-apikey/dialog-apikey.component'; import { DialogApiaddComponent } from '../dialog-apiadd/dialog-apiadd.component'; import { MatDialog } from '@angular/material/dialog'; import { MatTableDataSource } from '@angular/material/table'; import { DialogAddreportprofileComponent } from '../dialog-addreportprofile/dialog-addreportprofile.component'; export interface ApiList { apikey: string; apiname: string; apiurl: string; status: string; created: string; expires: string; current_storage: number; } @Component({ selector: 'app-settings', templateUrl: './settings.component.html', styleUrls: ['./settings.component.scss'] }) export class SettingsComponent implements OnInit { color = 'accent'; info = ''; listkey = false; checked = false; hide = true; remain: any; tryconnectdb = false; wipechecked = false; enableAPI = true; wipehide = false; showregapi = true; wipeall = false; apiconneted = false; user = ''; today = new Date().toISOString().slice(0, 10); createdate: any; pro: any; expirydate: any; current_storage: any; max_storage: any; status = 'Not connected!'; reportProfileList = []; ReportProfilesdisplayedColumns: string[] = ['profile_name', 'profile_settings']; ReportProfilesdataSource = new MatTableDataSource([]); displayedColumns: string[] = ['apiname', 'status', 'created', 'expires', 'storage', 'settings']; dataSource = new MatTableDataSource([]); constructor(public router: Router, private indexeddbService: IndexeddbService, private apiService: ApiService, public dialog: MatDialog) { } ngOnInit() { const localkey = sessionStorage.getItem('VULNREPO-API'); if (localkey) { console.log('Key found'); this.apiconnect(localkey); this.listkey = true; this.showregapi = false; } else { this.indexeddbService.retrieveAPIkey().then(ret => { if (ret) { this.tryconnectdb = true; this.listkey = true; this.showregapi = false; if (sessionStorage.getItem('hidedialog') !== 'true') { setTimeout(_ => this.openDialog(ret)); } } else { this.showregapi = true; } }); } this.getReportProfiles(); } wipeDatachanged() { if (this.wipechecked === true) { this.wipehide = true; } if (this.wipechecked === false) { this.wipehide = false; } } wipealldata() { indexedDB.deleteDatabase('vulnrepo-settings'); indexedDB.deleteDatabase('vulnrepo-api'); indexedDB.deleteDatabase('vulnrepo-db'); window.location.href = window.location.protocol + '//' + window.location.host; } dumpallmyreports() { this.indexeddbService.getReports().then(data => { if (data) { // download dump const blob = new Blob([JSON.stringify(data)], { type: 'text/plain' }); const link = document.createElement('a'); const url = window.URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', 'Dumped My Reports (vulnrepo.com).txt'); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else { console.log('DB read error'); } }); } parseandrestorereports(array) { const parsed = JSON.parse(array); for (let _i = 0; _i < parsed.length; _i++) { const num = parsed[_i]; console.log(num); this.indexeddbService.importReportfromfileSettings(num); if (_i + 1 === parsed.length) { this.router.navigate(['/my-reports']); } } } restoreMyReports(input: HTMLInputElement) { const files = input.files; if (files && files.length) { const fileToRead = files[0]; const fileReader = new FileReader(); fileReader.onload = (e) => { this.parseandrestorereports(fileReader.result); }; fileReader.readAsText(fileToRead, 'UTF-8'); } } gettimebetweendates(date11, date22) { let date1 = date11; let date2 = date22; date1 = date1.split('-'); date2 = date2.split('-'); date1 = new Date(date1[0], date1[1], date1[2]); date2 = new Date(date2[0], date2[1], date2[2]); const oneDay = 24 * 60 * 60 * 1000; const diffDays = Math.round(Math.abs((date1 - date2) / oneDay)); return diffDays; } apiconnect(vault: string) { const elementlist: ApiList[] = []; const vaultobj = JSON.parse(vault); vaultobj.forEach( (element) => { if (element.apikey !== undefined && element.apikey !== '') { this.apiService.APISend(element.value, element.apikey, 'apiconnect', '').then(resp => { if (resp !== undefined && resp !== null && resp.AUTH === 'OK') { this.apiconneted = true; this.listkey = false; this.createdate = resp.CREATEDATE; this.expirydate = resp.EXPIRYDATE; this.remain = this.gettimebetweendates(this.today, this.expirydate); this.user = resp.WELCOME; this.max_storage = resp.MAX_STORAGE; this.current_storage = resp.CURRENT_STORAGE; const stor = this.current_storage / this.max_storage * 100; // tslint:disable-next-line:max-line-length const elementdata = { apikey: element.apikey, apiname: element.viewValue, apiurl: element.value, status: 'Connected', created: resp.CREATEDATE, expires: resp.EXPIRYDATE + ' (' + this.remain + ' days left)', current_storage: stor }; elementlist.push(elementdata); this.dataSource.data = elementlist; this.tryconnectdb = false; } else { if (resp === null) { // tslint:disable-next-line:max-line-length const elementdata = { apikey: element.apikey, apiname: element.viewValue, apiurl: element.value, status: 'Not connected: wrong API key?', created: '', expires: '', current_storage: 0 }; elementlist.push(elementdata); this.dataSource.data = elementlist; } else { // tslint:disable-next-line:max-line-length const elementdata = { apikey: element.apikey, apiname: element.viewValue, apiurl: element.value, status: 'Not connected', created: '', expires: '', current_storage: 0 }; elementlist.push(elementdata); this.dataSource.data = elementlist; } } }).catch(error => { console.log('API error: ', error); }); } }); sessionStorage.setItem('VULNREPO-API', JSON.stringify(vaultobj)); } removeapikey() { indexedDB.deleteDatabase('vulnrepo-api'); this.showregapi = true; this.listkey = false; this.apiconneted = false; this.tryconnectdb = false; this.status = 'Not connected!'; } apidisconnect() { sessionStorage.removeItem('VULNREPO-API'); this.showregapi = false; this.listkey = true; this.apiconneted = false; this.status = 'Not connected!'; this.tryconnectdb = true; } tryconnect() { this.indexeddbService.retrieveAPIkey().then(ret => { if (ret) { this.listkey = true; this.showregapi = false; this.tryconnectdb = true; setTimeout(_ => this.openDialog(ret)); } else { this.showregapi = true; } }); } openDialog(data: any): void { const dialogRef = this.dialog.open(DialogApikeyComponent, { width: '400px', disableClose: true, data: data }); dialogRef.afterClosed().subscribe(result => { console.log('The security key dialog was closed'); if (result) { this.apiconnect(result); if (data) { this.indexeddbService.saveKEYinDB(data).then(ret => {}); } this.tryconnectdb = false; this.showregapi = false; } }); } openDialogAPIADD(): void { const dialogRef = this.dialog.open(DialogApiaddComponent, { width: '400px', disableClose: true, data: '' }); dialogRef.afterClosed().subscribe(result => { console.log('The security key dialog was closed'); if (result === 'OK') { this.apiconneted = true; this.tryconnectdb = false; this.listkey = false; this.showregapi = false; const localkey = sessionStorage.getItem('VULNREPO-API'); if (localkey) { this.apiconnect(localkey); } } }); } openDialogAPIaddtovault(): void { const dialogRef = this.dialog.open(DialogApikeyComponent, { width: '400px', disableClose: true, data: 'addtovault' }); dialogRef.afterClosed().subscribe(result => { if (result) { const dialogRef2 = this.dialog.open(DialogApiaddComponent, { width: '400px', disableClose: true, data: result }); dialogRef2.afterClosed().subscribe(resul => { console.log('The security key dialog was closed'); if (resul === 'OK') { const localkey = sessionStorage.getItem('VULNREPO-API'); if (localkey) { this.apiconnect(localkey); } } }); } }); } openDialogAPIremove(drem): any { const dialogRef = this.dialog.open(DialogApikeyComponent, { width: '400px', disableClose: true, data: 'addtovault' }); dialogRef.afterClosed().subscribe(result => { if (result) { sessionStorage.setItem('VULNREPO-API', JSON.stringify(drem)); this.saveAPIKEY(drem, result); this.apiconnect(JSON.stringify(drem)); } }); } exportvault() { this.indexeddbService.retrieveAPIkey().then(data => { if (data) { const today = new Date().toLocaleString(); // download dump const blob = new Blob([JSON.stringify(data)], { type: 'application/json;charset=utf-8' }); const link = document.createElement('a'); const url = window.URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', 'VULNREPO Vault Dump ' + today + ' (vulnrepo.com).json'); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else { console.log('DB read error'); } }); } onFileLoad(fileLoadedEvent) { } importvault(input: HTMLInputElement) { console.log('import vault'); const files = input.files; if (files && files.length) { const fileToRead = files[0]; const fileReader = new FileReader(); fileReader.onload = this.onFileLoad; fileReader.onload = (e) => { this.Processimportfile(fileReader.result); }; fileReader.readAsText(fileToRead, 'UTF-8'); } } Processimportfile(file) { file = file.replace(/^"(.*)"$/, '$1'); this.openDialog(file); } removeApi(element) { const localkey = sessionStorage.getItem('VULNREPO-API'); if (localkey) { const result = JSON.parse(localkey); const index = result.map(function(e) { return e.apikey; }).indexOf(element); if (index !== -1) { this.openDialogAPIremove(result); result.splice(index, 1); } } } saveAPIKEY(key, pass) { this.indexeddbService.encryptKEY(JSON.stringify(key), pass).then(data => { if (data) { this.indexeddbService.saveKEYinDB(data).then(ret => {}); } }); } getReportProfiles() { this.indexeddbService.retrieveReportProfile().then(ret => { if (ret) { this.ReportProfilesdataSource = new MatTableDataSource(ret); this.reportProfileList = this.ReportProfilesdataSource.data; } }); } openDialogReportProfiles(data: any): void { const dialogRef = this.dialog.open(DialogAddreportprofileComponent, { width: '600px', disableClose: true, data: data }); dialogRef.afterClosed().subscribe(result => { console.log('Report Settings Profile dialog was closed'); if (result) { this.reportProfileList = this.reportProfileList.concat(result); this.ReportProfilesdataSource.data = this.reportProfileList; this.indexeddbService.saveReportProfileinDB(this.reportProfileList).then(ret => {}); this.getReportProfiles(); } }); } removeProfileItem(item: any): void { const index: number = this.reportProfileList.indexOf(item as never); if (index !== -1) { this.reportProfileList.splice(index, 1); this.ReportProfilesdataSource.data = this.reportProfileList; this.indexeddbService.saveReportProfileinDB(this.reportProfileList).then(ret => {}); this.getReportProfiles(); } } editProfileItem(item: any): void { const dialogRef = this.dialog.open(DialogAddreportprofileComponent, { width: '600px', disableClose: true, data: item }); dialogRef.afterClosed().subscribe(result => { console.log('Report Settings Profile dialog was closed'); if (result) { const index: number = this.reportProfileList.indexOf(result.original[0]); if (index !== -1) { this.reportProfileList[index] = { profile_name: result.profile_name, logo: result.logo, logow: result.logow, logoh: result.logoh, theme: result.profile_theme, video_embed: result.video_embed, remove_lastpage: result.remove_lastpage, remove_issueStatus: result.remove_issueStatus, remove_researcher: result.remove_researcher, remove_changelog: result.remove_changelog, remove_tags: result.remove_tags, ResName: result.ResName, ResEmail: result.ResEmail, ResSocial: result.ResSocial, ResWeb: result.ResWeb }; this.ReportProfilesdataSource.data = this.reportProfileList; this.indexeddbService.saveReportProfileinDB(this.reportProfileList).then(ret => {}); this.getReportProfiles(); } } }); } exportprofiles(): void { this.indexeddbService.retrieveReportProfile().then(ret => { if (ret) { const blob = new Blob([JSON.stringify(ret)], { type: 'text/plain' }); const link = document.createElement('a'); const url = window.URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', 'Backup Report Profiles (vulnrepo.com).txt'); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } }); } importReportProfile(input: HTMLInputElement) { console.log('import profile'); const files = input.files; if (files && files.length) { const fileToRead = files[0]; const fileReader = new FileReader(); fileReader.onload = this.onFileLoad; fileReader.onload = (e) => { this.parseprofile(fileReader.result); }; fileReader.readAsText(fileToRead, 'UTF-8'); } } parseprofile(profile){ const parsed = JSON.parse(profile); this.reportProfileList = this.reportProfileList.concat(parsed); this.ReportProfilesdataSource.data = this.reportProfileList; this.indexeddbService.saveReportProfileinDB(this.reportProfileList).then(ret => {}); this.getReportProfiles(); } }
the_stack
import {readdirSync, statSync, writeFileSync} from 'fs' import {readFileSync} from 'fs' import * as mkdir from 'mkdirp' import * as npmRun from 'npm-run' import {join, relative, resolve, dirname} from 'path' import * as rm from 'rimraf' import * as tmp from 'tmp' import {Cli, ECliArgument, INpmDtsArgs} from './cli' import {debug, ELogLevel, error, info, init, verbose, warn} from './log' import * as fs from 'fs' const MKDIR_RETRIES = 5 /** * Logic for generating aggregated typings for NPM module */ export class Generator extends Cli { private packageInfo: any private moduleNames: string[] private throwErrors: boolean private cacheContentEmptied: boolean = true /** * Auto-launches generation based on command line arguments * @param injectedArguments generation arguments (same as CLI) * @param enableLog enables logging when true, null allows application to decide * @param throwErrors makes generation throw errors when true */ public constructor( injectedArguments?: INpmDtsArgs, enableLog: boolean | null = null, throwErrors = false, ) { super(injectedArguments) this.throwErrors = throwErrors if (enableLog === null) { enableLog = !injectedArguments } if (enableLog) { init('npm-dts', this.getLogLevel()) const myPackageJson = JSON.parse( readFileSync(resolve(__dirname, '..', 'package.json'), { encoding: 'utf8', }), ) const soft = ` npm-dts v${myPackageJson.version} ` let author = ' by Vytenis Urbonavičius ' let spaces = ' ' let border = '___________________________________________________________' author = author.substring(0, soft.length) spaces = spaces.substring(0, soft.length) border = border.substring(0, soft.length) info(` ${border} `) info(`|${spaces}|`) info(`|${spaces}|`) info(`|${soft}|`) info(`|${author}|`) info(`|${spaces}|`) info(`|${border}|`) info(` ${spaces} `) } } /** * Executes generation of single declaration file */ public async generate() { info(`Generating declarations for "${this.getRoot()}"...`) let hasError = false let exception = null const cleanupTasks: (() => void)[] = [] if (!this.tmpPassed) { verbose('Locating OS Temporary Directory...') try { await new Promise<void>(done => { tmp.dir((tmpErr, tmpDir, rmTmp) => { if (tmpErr) { error('Could not create OS Temporary Directory!') this.showDebugError(tmpErr) throw tmpErr } verbose('OS Temporary Directory was located!') this.setArgument(ECliArgument.tmp, resolve(tmpDir, 'npm-dts')) cleanupTasks.push(() => { verbose('Deleting OS Temporary Directory...') rmTmp() verbose('OS Temporary Directory was deleted!') }) done() }) }) } catch (e) { hasError = true exception = e } } if (!hasError) { await this._generate().catch(async e => { hasError = true const output = this.getOutput() error(`Generation of ${output} has failed!`) this.showDebugError(e) if (!this.useForce()) { if (this.getLogLevel() === ELogLevel.debug) { info( 'If issue is not severe, you can try forcing execution using force flag.', ) info( 'In case of command line usage, add "-f" as the first parameter.', ) } else { info('You should try running npm-dts with debug level logging.') info( 'In case of command line, debug mode is enabled using "-L debug".', ) } } if (!this.cacheContentEmptied) { await this.clearTempDir() } exception = e }) } cleanupTasks.forEach(task => task()) if (!hasError) { info('Generation is completed!') } else { error('Generation failed!') if (this.throwErrors) { throw exception || new Error('Generation failed!') } } } /** * Logs serialized error if it exists * @param e - error to be shown */ private showDebugError(e: any) { if (e) { if (e.stdout) { debug(`Error: \n${e.stdout.toString()}`) } else { debug(`Error: \n${JSON.stringify(e)}`) } } } /** * Launches generation of typings */ private async _generate() { await this.generateTypings() let source = await this.combineTypings() source = this.addAlias(source) await this.storeResult(source) } private getLogLevel(): ELogLevel { const logLevel = this.getArgument(ECliArgument.logLevel) as ELogLevel return ELogLevel[logLevel] ? logLevel : ELogLevel.info } /** * Gathers entry file address (relative to project root path) */ private getEntry(): string { return this.getArgument(ECliArgument.entry) as string } /** * Gathers target project root path */ private getRoot(): string { return resolve(this.getArgument(ECliArgument.root) as string) } /** * Gathers TMP directory to be used for TSC operations */ private getTempDir(): string { return resolve(this.getArgument(ECliArgument.tmp) as string) } /** * Gathers output path to be used (relative to root) */ private getOutput(): string { return this.getArgument(ECliArgument.output) as string } /** * Checks if script is forced to use its built-in TSC */ private useTestMode(): boolean { return this.getArgument(ECliArgument.testMode) as boolean } /** * Checks if script is forced to attempt generation despite errors */ private useForce(): boolean { return this.getArgument(ECliArgument.force) as boolean } /** * Creates TMP directory to be used for TSC operations * @param retries amount of times to retry on failure */ private makeTempDir(retries = MKDIR_RETRIES): Promise<void> { const tmpDir = this.getTempDir() verbose('Preparing "tmp" directory...') return new Promise((done, fail) => { mkdir(tmpDir) .then(() => { this.cacheContentEmptied = false verbose('"tmp" directory was prepared!') done() }) .catch(mkdirError => { error(`Failed to create "${tmpDir}"!`) this.showDebugError(mkdirError) if (retries) { const sleepTime = 100 verbose(`Will retry in ${sleepTime}ms...`) setTimeout(() => { this.makeTempDir(retries - 1).then(done, fail) }, sleepTime) } else { error(`Stopped trying after ${MKDIR_RETRIES} retries!`) fail() } }) }) } /** * Removes TMP directory */ private clearTempDir() { const tmpDir = this.getTempDir() verbose('Cleaning up "tmp" directory...') return new Promise<void>((done, fail) => { rm(tmpDir, rmError => { if (rmError) { error(`Could not clean up "tmp" directory at "${tmpDir}"!`) this.showDebugError(rmError) fail() } else { this.cacheContentEmptied = true verbose('"tmp" directory was cleaned!') done() } }) }) } /** * Re-creates empty TMP directory to be used for TSC operations */ private resetCacheDir() { verbose('Will now reset "tmp" directory...') return new Promise((done, fail) => { this.clearTempDir().then(() => { this.makeTempDir().then(done, fail) }, fail) }) } /** * Generates per-file typings using TSC */ private async generateTypings() { await this.resetCacheDir() verbose('Generating per-file typings using TSC...') const tscOptions = this.getArgument(ECliArgument.tsc) as string const cmd = 'tsc --declaration --emitDeclarationOnly --declarationDir "' + this.getTempDir() + '"' + (tscOptions.length ? ` ${tscOptions}` : '') debug(cmd) try { npmRun.execSync( cmd, { cwd: this.useTestMode() ? resolve(__dirname, '..') : this.getRoot(), }, (err: any, stdout: any, stderr: any) => { if (err) { if (this.useForce()) { warn('TSC exited with errors!') } else { error('TSC exited with errors!') } this.showDebugError(err) } else { if (stdout) { process.stdout.write(stdout) } if (stderr) { process.stderr.write(stderr) } } }, ) } catch (e) { if (this.useForce()) { warn('Suppressing errors due to "force" flag!') this.showDebugError(e) warn('Generated declaration files might not be valid!') } else { throw e } } verbose('Per-file typings have been generated using TSC!') } /** * Gathers a list of created per-file declaration files * @param dir directory to be scanned for files (called during recursion) * @param files discovered array of files (called during recursion) */ private getDeclarationFiles( dir: string = this.getTempDir(), files: string[] = [], ) { if (dir === this.getTempDir()) { verbose('Loading list of generated typing files...') } try { readdirSync(dir).forEach(file => { if (statSync(join(dir, file)).isDirectory()) { files = this.getDeclarationFiles(join(dir, file), files) } else { files = files.concat(join(dir, file)) } }) } catch (e) { error('Failed to load list of generated typing files...') this.showDebugError(e) throw e } if (dir === this.getTempDir()) { verbose('Successfully loaded list of generated typing files!') } return files } /** * Loads package.json information of target project */ private getPackageDetails() { if (this.packageInfo) { return this.packageInfo } verbose('Loading package.json...') const root = this.getRoot() const packageJsonPath = resolve(root, 'package.json') try { this.packageInfo = JSON.parse( readFileSync(packageJsonPath, {encoding: 'utf8'}), ) } catch (e) { error(`Failed to read package.json at "'${packageJsonPath}'"`) this.showDebugError(e) throw e } verbose('package.json information has been loaded!') return this.packageInfo } /** * Generates module name based on file path * @param path path to be converted to module name * @param options additional conversion options */ private convertPathToModule( path: string, options: ConvertPathToModuleOptions = {}, ) { const { rootType = IBasePathType.tmp, noPrefix = false, noExtensionRemoval = false, noExistenceCheck = false, } = options const packageDetails = this.getPackageDetails() const fileExisted = noExistenceCheck || (!noExtensionRemoval && fs.existsSync(path) && fs.lstatSync(path).isFile()) if (rootType === IBasePathType.cwd) { path = relative(process.cwd(), path) } else if (rootType === IBasePathType.root) { path = relative(this.getRoot(), path) } else if (rootType === IBasePathType.tmp) { path = relative(this.getTempDir(), path) } if (!noPrefix) { path = `${packageDetails.name}/${path}` } path = path.replace(/\\/g, '/') if (fileExisted && !noExtensionRemoval) { path = path.replace(/\.[^.]+$/g, '') path = path.replace(/\.d$/g, '') } return path } /** * Loads generated per-file declaration files */ private loadTypings() { const result: IDeclarationMap = {} const declarationFiles = this.getDeclarationFiles() verbose('Loading declaration files and mapping to modules...') declarationFiles.forEach(file => { const moduleName = this.convertPathToModule(file) try { result[moduleName] = readFileSync(file, {encoding: 'utf8'}) } catch (e) { error(`Could not load declaration file '${file}'!`) this.showDebugError(e) throw e } }) verbose('Loaded declaration files and mapped to modules!') return result } private resolveImportSourcesAtLine( regexp: RegExp, line: string, moduleName: string, ) { const matches = line.match(regexp) if (matches && matches[2].startsWith('.')) { const relativePath = `../${matches[2]}` let resolvedModule = resolve(moduleName, relativePath) resolvedModule = this.convertPathToModule(resolvedModule, { rootType: IBasePathType.cwd, noPrefix: true, noExtensionRemoval: true, }) if (!this.moduleExists(resolvedModule)) { resolvedModule += '/index' } line = line.replace(regexp, `$1${resolvedModule}$3`) } return line } /** * Alters import sources to avoid relative addresses and default index usage * @param source import source to be resolved * @param moduleName name of module containing import */ private resolveImportSources(source: string, moduleName: string) { source = source.replace(/\r\n/g, '\n') source = source.replace(/\n\r/g, '\n') source = source.replace(/\r/g, '\n') let lines = source.split('\n') lines = lines.map(line => { line = this.resolveImportSourcesAtLine( /(from ['"])([^'"]+)(['"])/, line, moduleName, ) line = this.resolveImportSourcesAtLine( /(import\(['"])([^'"]+)(['"]\))/, line, moduleName, ) return line }) source = lines.join('\n') return source } /** * Combines typings into a single declaration source */ private async combineTypings() { const typings = this.loadTypings() await this.clearTempDir() this.moduleNames = Object.keys(typings) verbose('Combining typings into single file...') const sourceParts: string[] = [] Object.entries(typings).forEach(([moduleName, fileSource]) => { fileSource = fileSource.replace(/declare /g, '') fileSource = this.resolveImportSources(fileSource, moduleName) sourceParts.push( `declare module '${moduleName}' {\n${(fileSource as string).replace( /^./gm, ' $&', )}\n}`, ) }) verbose('Combined typings into a single file!') return sourceParts.join('\n') } /** * Verifies if module specified exists among known modules * @param moduleName name of module to be checked */ private moduleExists(moduleName: string) { return this.moduleNames.includes(moduleName) } /** * Adds alias for main NPM package file to generated .d.ts source * @param source generated .d.ts declaration source so far */ private addAlias(source: string) { verbose('Adding alias for main file of the package...') const packageDetails = this.getPackageDetails() const entry = this.getEntry() if (!entry) { error('No entry file is available!') throw new Error('No entry file is available!') } const mainFile = this.convertPathToModule(resolve(this.getRoot(), entry), { rootType: IBasePathType.root, noExistenceCheck: true, }) source += `\ndeclare module '${packageDetails.name}' {\n` + ` import main = require('${mainFile}');\n` + ' export = main;\n' + '}' verbose('Successfully created alias for main file!') return source } /** * Stores generated .d.ts declaration source into file * @param source generated .d.ts source */ private async storeResult(source: string) { const output = this.getOutput() const root = this.getRoot() const file = resolve(root, output) const folderPath = dirname(file) verbose('Ensuring that output folder exists...') debug(`Creating output folder: "${folderPath}"...`) try { await mkdir(folderPath) } catch (mkdirError) { error(`Failed to create "${folderPath}"!`) this.showDebugError(mkdirError) throw mkdirError } verbose('Output folder is ready!') verbose(`Storing typings into ${output} file...`) try { writeFileSync(file, source, {encoding: 'utf8'}) } catch (e) { error(`Failed to create ${output}!`) this.showDebugError(e) throw e } verbose(`Successfully created ${output} file!`) } } /** * Map of modules and their declarations */ export interface IDeclarationMap { [moduleNames: string]: string } /** * Types of base path used during path resolving */ export enum IBasePathType { /** * Base path is root of targeted project */ root = 'root', /** * Base path is tmp directory */ tmp = 'tmp', /** * Base path is CWD */ cwd = 'cwd', } /** * Additional conversion options */ export interface ConvertPathToModuleOptions { /** * Type of base path used during path resolving */ rootType?: IBasePathType /** * Disables addition of module name as prefix for module name */ noPrefix?: boolean /** * Disables extension removal */ noExtensionRemoval?: boolean /** * Disables existence check and assumes that file exists */ noExistenceCheck?: boolean }
the_stack
import 'should' import { Readable } from 'stream' import crypto from 'crypto' import { Curl, CurlCode, curly } from '../../lib' import { app, closeServer, host, port, server } from '../helper/server' import { allMethodsWithMultipleReqResTypes } from '../helper/commonRoutes' interface GetReadableStreamForBufferOptions { filterDataToPush?(pushIteration: number, data: Buffer): Promise<Buffer> } const url = `http://${host}:${port}` // @ts-ignore const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) // 1mb const getRandomBuffer = (size: number = 1024 * 1024) => crypto.randomBytes(size) const getReadableStreamForBuffer = ( buffer: Buffer, { filterDataToPush = async (_, buf) => buf, }: GetReadableStreamForBufferOptions = {}, ): Readable => { let bufferOffset = 0 let pushIteration = 0 let canRead = true const stream = new Readable({ // this defaults to 16kb highWaterMark: 4 * 1024, async read(size) { if (!canRead) return canRead = false let wantsMore = true while (wantsMore) { try { const dataToPush = await filterDataToPush( pushIteration++, buffer.slice( bufferOffset, Math.min(buffer.length, bufferOffset + size), ), ) wantsMore = this.push(dataToPush) bufferOffset += dataToPush.length if (bufferOffset >= buffer.length) { this.push(null) wantsMore = false } } catch (error) { stream.destroy(error) } } canRead = true }, }) return stream } const getUploadOptions = (curlyStreamUpload: Readable) => { const options: Record<string, any> = { // we are doing a PUT upload upload: true, // as we are setting this, there is no need to specify the payload size httpHeader: ['Transfer-Encoding: chunked', 'Connection: close'], curlyStreamUpload, } if (Curl.isVersionGreaterOrEqualThan(7, 62)) { // This defaults to 64kb, setting to 16kb to cause more buffering options.uploadBufferSize = 16 * 1024 } return options } const getDownloadOptions = () => ({ curlyStreamResponse: true, // This defaults to undefined, which means using the Node.js default value of 16kb. // Here we are explicitly setting it to 4kb. curlyStreamResponseHighWaterMark: 4 * 1024, }) let randomBuffer: Buffer describe('streams', () => { before((done) => { randomBuffer = getRandomBuffer() server.listen(port, host, done) allMethodsWithMultipleReqResTypes(app, { putUploadBuffer: randomBuffer, }) }) after(() => { closeServer() // beatiful is not it? app._router.stack.pop() }) describe('curly', () => { // libcurl versions older than this are not really reliable for streams usage. if (Curl.isVersionGreaterOrEqualThan(7, 69, 1)) { it('works for uploading and downloading', async () => { const curlyStreamUpload = getReadableStreamForBuffer(randomBuffer, { filterDataToPush: async (pushIteration, data) => { // we are waiting 1200 ms at the 5th iteration just to cause // some pauses in the READFUNCTION if (pushIteration === 5) { await sleep(1200) } return data }, }) const { statusCode, data: downloadStream, headers } = await curly.put< Readable >(`${url}/all?type=put-upload`, { ...getUploadOptions(curlyStreamUpload), ...getDownloadOptions(), curlyProgressCallback() { return 0 }, }) statusCode.should.be.equal(200) headers[headers.length - 1]['x-is-same-buffer'].should.be.equal('0') // TODO: add snapshot testing for headers // we cannot use async iterators here because we need to support Node.js v8 return new Promise((resolve, reject) => { const acc: Buffer[] = [] let iteration = 0 // we are waiting 1200 ms at the 5th iteration just to cause // some pauses in the PUSHFUNCTION downloadStream.on('data', (data) => { acc.push(data) if (iteration++ === 2) { downloadStream.pause() setTimeout(() => downloadStream.resume(), 1200) } }) downloadStream.on('close', () => { curlyStreamUpload.destroy() }) downloadStream.on('end', () => { const finalBuffer = Buffer.concat(acc) const result = finalBuffer.compare(randomBuffer) result.should.be.equal(0) resolve() }) downloadStream.on('error', (error) => { reject(error) }) }) }) it('works with responses without body', async function () { this.timeout(3000) const { statusCode, data: downloadStream } = await curly.get<Readable>( `${url}/all?type=no-body`, { ...getDownloadOptions(), curlyProgressCallback() { return 0 }, }, ) statusCode.should.be.equal(200) // TODO: add snapshot testing for headers // we cannot use async iterators here because we need to support Node.js v8 return new Promise((resolve, reject) => { const acc: Buffer[] = [] downloadStream.on('data', (data) => { acc.push(data) }) downloadStream.on('end', () => { const finalBuffer = Buffer.concat(acc) finalBuffer.byteLength.should.be.equal(0) resolve() }) downloadStream.on('error', (error) => { reject(error) }) }) }) it('works with HEAD requests', async function () { this.timeout(3000) const { statusCode, data: downloadStream } = await curly.head<Readable>( `${url}/all?type=method`, { ...getDownloadOptions(), curlyProgressCallback() { return 0 }, }, ) statusCode.should.be.equal(200) // TODO: add snapshot testing for headers // we cannot use async iterators here because we need to support Node.js v8 return new Promise((resolve, reject) => { const acc: Buffer[] = [] downloadStream.on('data', (data) => { acc.push(data) }) downloadStream.on('end', () => { const finalBuffer = Buffer.concat(acc) finalBuffer.byteLength.should.be.equal(0) resolve() }) downloadStream.on('error', (error) => { reject(error) }) }) }) } it('returns an error when the upload stream throws an error', async () => { const errorMessage = 'custom error' const curlyStreamUpload = getReadableStreamForBuffer(randomBuffer, { async filterDataToPush(iteration, buffer) { if (iteration === 5) { throw new Error(errorMessage) } return buffer }, }) await curly .put(`${url}/all?type=put-upload`, getUploadOptions(curlyStreamUpload)) // @ts-ignore .should.be.rejectedWith(Error, { message: errorMessage, isCurlError: true, code: CurlCode.CURLE_ABORTED_BY_CALLBACK, }) }) it('returns an error when the upload stream is destroyed unexpectedly', async () => { const curlyStreamUpload = getReadableStreamForBuffer(randomBuffer, { async filterDataToPush(iteration, buffer) { if (iteration === 5) { curlyStreamUpload.destroy() } return buffer }, }) await curly .put(`${url}/all?type=put-upload`, getUploadOptions(curlyStreamUpload)) // @ts-ignore .should.be.rejectedWith(Error, { message: 'Curl upload stream was unexpectedly destroyed', isCurlError: true, code: CurlCode.CURLE_ABORTED_BY_CALLBACK, }) }) it('returns an error when the upload stream is destroyed unexpectedly with a specific error', async () => { const errorMessage = 'Custom error message' const curlyStreamUpload = getReadableStreamForBuffer(randomBuffer, { async filterDataToPush(iteration, buffer) { if (iteration === 5) { curlyStreamUpload.destroy(new Error(errorMessage)) } return buffer }, }) await curly .put(`${url}/all?type=put-upload`, getUploadOptions(curlyStreamUpload)) // @ts-ignore .should.be.rejectedWith(Error, { message: errorMessage, isCurlError: true, code: CurlCode.CURLE_ABORTED_BY_CALLBACK, }) }) it('emits an error when the download stream is destroyed unexpectedly', async () => { const { statusCode, data: downloadStream } = await curly.get<Readable>( `${url}/all?type=json`, { ...getDownloadOptions(), }, ) statusCode.should.be.equal(200) // we cannot use async iterators here because we need to support Node.js v8 return new Promise((resolve, reject) => { downloadStream.on('data', () => { downloadStream.destroy() }) downloadStream.on('end', () => { reject( new Error('Stream ended without any errors - This is invalid!'), ) }) downloadStream.on('error', (error) => { error.should.match({ message: 'Curl response stream was unexpectedly destroyed', isCurlError: true, code: CurlCode.CURLE_ABORTED_BY_CALLBACK, }) resolve() }) }) }) it('emits an error when the download stream is destroyed unexpectedly with a specific error', async () => { const errorMessage = 'Custom error message' const { statusCode, data: downloadStream } = await curly.get<Readable>( `${url}/all?type=json`, { ...getDownloadOptions(), // this is just to also test the branching for when this is not set curlyStreamResponseHighWaterMark: undefined, }, ) statusCode.should.be.equal(200) // we cannot use async iterators here because we need to support Node.js v8 return new Promise((resolve, reject) => { downloadStream.on('data', () => { downloadStream.destroy(new Error(errorMessage)) }) downloadStream.on('end', () => { reject( new Error('Stream ended without any errors - This is invalid!'), ) }) downloadStream.on('error', (error) => { error.should.match({ message: errorMessage, isCurlError: true, code: CurlCode.CURLE_ABORTED_BY_CALLBACK, }) resolve() }) }) }) }) describe('Curl', () => { it('throws an error when passing something that is not a stream to setUploadStream', async () => { const curl = new Curl() const values = [123, [], { read: true }] for (const val of values) { ;(() => { // @ts-expect-error curl.setUploadStream(val) }).should.throw(Error, { message: /^The passed value to setUploadStream does not/, }) } }) it('does nothing when passing the same stream to setUploadStream', async () => { const streamUpload = getReadableStreamForBuffer(randomBuffer) const curl = new Curl() curl.setUploadStream(streamUpload) curl.setUploadStream(streamUpload) // the way we are testing this is by making sure we are // not adding more listeners to the stream end evt streamUpload.listenerCount('end').should.be.equal(1) }) it('resets stream back to null after calling setUploadStream(null)', async () => { const streamUpload = getReadableStreamForBuffer(randomBuffer) const curl = new Curl() curl.setUploadStream(streamUpload) streamUpload.listenerCount('end').should.be.equal(1) curl.setUploadStream(null) streamUpload.listenerCount('end').should.be.equal(0) }) }) })
the_stack
import { IObservableArray, observable } from "mobx"; import { IAnyModelType, Instance } from "mobx-state-tree"; import { Decimal } from "decimal.js-light"; import { Converter, ConverterOrFactory, IConverter, StateConverterOptionsWithContext, ConversionError, withDefaults, makeConverter, } from "./converter"; import { controlled } from "./controlled"; import { dynamic } from "./dynamic-converter"; import { identity } from "./utils"; import { parseDecimal, renderDecimal, DecimalOptions, DecimalParserError, checkConverterOptions, } from "./decimalParser"; const INTEGER_REGEX = new RegExp("^-?(0|[1-9]\\d*)$"); export class StringConverter<V> extends Converter<string, V> { defaultControlled = controlled.value; } type StringOptions = { maxLength?: number; }; function string(options: StringOptions) { return new StringConverter<string>({ emptyRaw: "", emptyValue: "", convert(raw) { if (options.maxLength != null && options.maxLength < raw.length) { throw new ConversionError("exceedsMaxLength"); } return raw; }, render(value) { return value; }, preprocessRaw(raw: string): string { return raw.trim(); }, }); } function literalString<T>() { return new Converter<T, T>({ emptyRaw: "" as any, emptyImpossible: true, convert(raw) { return raw; }, render(value) { return value; }, defaultControlled: controlled.value, }); } function number() { return new StringConverter<number>({ emptyRaw: "", emptyImpossible: true, convert(raw, converterOptions) { checkConverterOptions(converterOptions); try { return +parseDecimal(raw, { maxWholeDigits: 100, decimalPlaces: 100, allowNegative: true, addZeroes: false, decimalSeparator: converterOptions.decimalSeparator || ".", thousandSeparator: converterOptions.thousandSeparator || ",", renderThousands: converterOptions.renderThousands || false, }); } catch (e) { if (e instanceof DecimalParserError) { throw new ConversionError(e.type); } throw e; } }, render(value, converterOptions) { return renderDecimal(value.toString(), { maxWholeDigits: 100, decimalPlaces: 100, allowNegative: true, addZeroes: false, decimalSeparator: converterOptions.decimalSeparator || ".", thousandSeparator: converterOptions.thousandSeparator || ",", renderThousands: converterOptions.renderThousands || false, }); }, preprocessRaw(raw: string): string { return raw.trim(); }, }); } function integer() { return new StringConverter<number>({ emptyRaw: "", emptyImpossible: true, convert(raw) { if (!INTEGER_REGEX.test(raw)) { throw new ConversionError(); } return +raw; }, render(value) { return value.toString(); }, preprocessRaw(raw: string): string { return raw.trim(); }, }); } function boolean() { return new Converter<boolean, boolean>({ emptyRaw: false, emptyImpossible: true, convert(raw) { return raw; }, render(value) { return value; }, defaultControlled: controlled.checked, neverRequired: true, }); } function decimalConvert( raw: string, options: DecimalOptions, converterOptions: StateConverterOptionsWithContext ): string { checkConverterOptions(converterOptions); try { return parseDecimal(raw, { ...options, decimalSeparator: converterOptions.decimalSeparator || ".", thousandSeparator: converterOptions.thousandSeparator || ",", renderThousands: converterOptions.renderThousands || false, }); } catch (e) { if (e instanceof DecimalParserError) { throw new ConversionError(e.type); } throw e; } } function decimalRender( value: string, options: DecimalOptions, converterOptions: StateConverterOptionsWithContext ): string { return renderDecimal(value, { ...options, decimalSeparator: converterOptions.decimalSeparator || ".", thousandSeparator: converterOptions.thousandSeparator || ",", renderThousands: converterOptions.renderThousands || false, }); } function stringDecimal(options: DecimalOptions) { return new StringConverter<string>({ emptyRaw: "", emptyImpossible: true, defaultControlled: controlled.value, neverRequired: false, preprocessRaw(raw: string): string { return raw.trim(); }, convert(raw, converterOptions) { return decimalConvert(raw, options, converterOptions); }, render(value, converterOptions) { return decimalRender(value, options, converterOptions); }, }); } function decimal(options: DecimalOptions) { return new Converter<string, Decimal>({ emptyRaw: "", emptyImpossible: true, defaultControlled: controlled.value, neverRequired: false, preprocessRaw(raw: string): string { return raw.trim(); }, convert(raw, converterOptions): Decimal { return new Decimal(decimalConvert(raw, options, converterOptions)); }, render(value, converterOptions) { return decimalRender(value.toString(), options, converterOptions); }, }); } // XXX create a way to create arrays with mobx state tree types function stringArray() { return new Converter<string[], IObservableArray<string>>({ emptyRaw: [], emptyValue: observable.array([]), convert(raw) { return observable.array(raw); }, render(value) { return value.slice(); }, }); } function textStringArray() { return new Converter<string, IObservableArray<string>>({ emptyRaw: "", emptyValue: observable.array([]), defaultControlled: controlled.value, convert(raw) { const rawSplit = raw.split("\n").map((r) => r.trim()); if (rawSplit.length === 1 && rawSplit[0] === "") { return observable.array([]); } return observable.array(rawSplit); }, render(value) { return value.join("\n"); }, preprocessRaw(raw: string) { // Filter out empty lines. return raw .split("\n") .filter((rawValue) => rawValue) .join("\n"); }, }); } function maybe<_R, V>( converter: StringConverter<V> | (() => StringConverter<V>) ): IConverter<string, V | undefined>; function maybe<M>( converter: ConverterOrFactory<M | null, M | undefined> ): IConverter<M | null, M | undefined>; function maybe<R, V>( converter: ConverterOrFactory<R, V> ): IConverter<string, V | undefined> | IConverter<R | null, V | undefined> { converter = makeConverter(converter); // we detect that we're converting a string, which needs a special maybe if (typeof converter.emptyRaw === "string") { return stringMaybe( converter as unknown as IConverter<string, V>, undefined ); } // XXX add an 'as any' as we get a typeerror for some reason now return maybeModel(converter as any, null, undefined) as IConverter< R | null, V | undefined >; } function maybeNull<_R, V>( converter: StringConverter<V> | (() => StringConverter<V>) ): IConverter<string, V | null>; function maybeNull<M>( converter: ConverterOrFactory<M | null, M | null> ): IConverter<M | null, M | null>; function maybeNull<R, V>( converter: ConverterOrFactory<R, V> ): IConverter<string, V | null> | IConverter<R | null, V | null> { converter = makeConverter(converter); // we detect that we're converting a string, which needs a special maybe if (typeof converter.emptyRaw === "string") { return stringMaybe( converter as unknown as IConverter<string, V | null>, null ); } // XXX add an 'as any' as we get a typeerror for some reason now return maybeModel(converter as any, null, null) as IConverter< R | null, V | null >; } function stringMaybe<V>(converter: IConverter<string, V>, emptyValue: V) { return new Converter<string, V>({ emptyRaw: "", emptyValue: emptyValue, defaultControlled: controlled.value, preprocessRaw( raw: string, options: StateConverterOptionsWithContext ): string { raw = raw.trim(); return converter.preprocessRaw(raw, options); }, convert(raw: string, options: StateConverterOptionsWithContext) { if (raw.trim() === "") { return emptyValue; } const r = converter.convert(raw, options); if (r instanceof ConversionError) { throw r; } return r.value; }, render(value: V, options: StateConverterOptionsWithContext) { if (value === this.emptyValue) { return ""; } return converter.render(value, options); }, }); } function model<M extends IAnyModelType>(_model: M) { return new Converter<Instance<M> | null, Instance<M>>({ emptyRaw: null, emptyImpossible: true, defaultControlled: controlled.object, neverRequired: false, convert(raw) { if (raw == null) { throw new Error("Raw should never be null at this point"); } return raw; }, render(value) { return value; }, }); } function maybeModel<M, RE, VE>( converter: IConverter<M, M>, emptyRaw: RE, emptyValue: VE ): IConverter<M | RE, M | VE> { return new Converter({ emptyRaw: emptyRaw, emptyValue: emptyValue, convert: (r: M | RE) => (r !== emptyRaw ? (r as M) : emptyValue), render: (v: M | VE) => (v !== emptyValue ? (v as M) : emptyRaw), defaultControlled: controlled.object, }); } const object = new Converter<any, any>({ emptyRaw: null, emptyValue: undefined, convert: identity, render: identity, }); export const converters = { string: withDefaults(string, {}), literalString, number, integer, stringDecimal: withDefaults(stringDecimal, { maxWholeDigits: 10, decimalPlaces: 2, allowNegative: true, addZeroes: true, }), decimal: withDefaults(decimal, { maxWholeDigits: 10, decimalPlaces: 2, allowNegative: true, addZeroes: true, }), boolean, textStringArray, stringArray, maybe, maybeNull, model, object, dynamic, };
the_stack
export const provinceName = { // 直辖市 "北京市": "北京", "天津市": "天津", "上海市": "上海", "重庆市": "重庆", // 自治区 "内蒙古自治区": "内蒙古", "广西壮族自治区": "广西", "西藏自治区": "西藏", "宁夏回族自治区": "宁夏", "新疆维吾尔自治区": "新疆", // 特别行政区 "香港特別行政區": "香港", "澳门特别行政区": "澳门", "江西省": "江西", "河南省": "河南", "四川省": "四川", "贵州省": "贵州", "辽宁省": "辽宁", "山东省": "山东", "山西省": "山西", "浙江省": "浙江", "海南省": "海南", "陕西省": "陕西", "福建省": "福建", "青海省": "青海", "湖北省": "湖北", "甘肃省": "甘肃", "安徽省": "安徽", "台湾省": "台湾", "云南省": "云南", "黑龙江省": "黑龙江", "广东省": "广东", "湖南省": "湖南", "河北省": "河北", "吉林省": "吉林", "江苏省": "江苏", }; export const positionMap = { "云南省": {"lat": 25.04581, "lng": 102.71}, "内蒙古自治区": {"lat": 40.8175, "lng": 111.76562}, "吉林省": {"lat": 43.89654, "lng": 125.32599}, "四川省": {"lat": 30.65165, "lng": 104.07593}, "宁夏回族自治区": {"lat": 38.47132, "lng": 106.25875}, "安徽省": {"lat": 31.86118, "lng": 117.28492}, "山东省": {"lat": 36.66853, "lng": 117.02036}, "山西省": {"lat": 37.87353, "lng": 112.5624}, "广东省": {"lat": 23.13219, "lng": 113.26653}, "广西壮族自治区": {"lat": 22.81548, "lng": 108.32755}, "新疆维吾尔自治区": {"lat": 43.79303, "lng": 87.6277}, "江苏省": {"lat": 32.06171, "lng": 118.76323}, "江西省": {"lat": 28.6757, "lng": 115.90923}, "河北省": {"lat": 38.03706, "lng": 114.46866}, "河南省": {"lat": 34.76552, "lng": 113.7536}, "浙江省": {"lat": 30.26745, "lng": 120.15279}, "海南省": {"lat": 20.01738, "lng": 110.34923}, "湖北省": {"lat": 30.5465, "lng": 114.34186}, "湖南省": {"lat": 28.11244, "lng": 112.98381}, "甘肃省": {"lat": 36.05942, "lng": 103.82631}, "福建省": {"lat": 26.10078, "lng": 119.29514}, "贵州省": {"lat": 26.59819, "lng": 106.70741}, "辽宁省": {"lat": 41.83544, "lng": 123.4291}, "陕西省": {"lat": 34.26547, "lng": 108.95424}, "青海省": {"lat": 36.6209, "lng": 101.7802}, "黑龙江省": {"lat": 45.74237, "lng": 126.66166}, "西藏自治区": {"lat": 31.64946, "lng": 86.51326}, "台湾省": {"lat": 23.74205, "lng": 120.9814}, "重庆": { "lng": 107.7539, "lat": 30.1904, "fullName": "重庆市", "province": "重庆", }, "北京": { "lng": 116.4551, "lat": 40.2539, "fullName": "北京市", "province": "北京", }, "天津": { "lng": 117.4219, "lat": 39.4189, "fullName": "天津市", "province": "天津", }, "上海": { "lng": 121.4648, "lat": 31.2891, "fullName": "上海市", "province": "上海", }, "香港": { "lng": 114.2578, "lat": 22.3242, "fullName": "香港", "province": "香港", }, "澳门": { "lng": 113.5547, "lat": 22.1484, "fullName": "澳门", "province": "澳门", }, "巴音": { "lng": 88.1653, "lat": 39.6002, "fullName": "巴音郭楞蒙古自治州", "province": "新疆", }, "和田": { "lng": 81.167, "lat": 36.9855, "fullName": "和田地区", "province": "新疆", }, "哈密": { "lng": 93.7793, "lat": 42.9236, "fullName": "哈密地区", "province": "新疆", }, "阿克": { "lng": 82.9797, "lat": 41.0229, "fullName": "阿克苏地区", "province": "新疆", }, "阿勒": { "lng": 88.2971, "lat": 47.0929, "fullName": "阿勒泰地区", "province": "新疆", }, "喀什": { "lng": 77.168, "lat": 37.8534, "fullName": "喀什地区", "province": "新疆", }, "塔城": { "lng": 86.6272, "lat": 45.8514, "fullName": "塔城地区", "province": "新疆", }, "昌吉": { "lng": 89.6814, "lat": 44.4507, "fullName": "昌吉回族自治州", "province": "新疆", }, "克孜": { "lng": 74.6301, "lat": 39.5233, "fullName": "克孜勒苏柯尔克孜自治州", "province": "新疆", }, "吐鲁": { "lng": 89.6375, "lat": 42.4127, "fullName": "吐鲁番地区", "province": "新疆", }, "伊犁": { "lng": 82.5513, "lat": 43.5498, "fullName": "伊犁哈萨克自治州", "province": "新疆", }, "博尔": { "lng": 81.8481, "lat": 44.6979, "fullName": "博尔塔拉蒙古自治州", "province": "新疆", }, "乌鲁": { "lng": 87.9236, "lat": 43.5883, "fullName": "乌鲁木齐市", "province": "新疆", }, "克拉": { "lng": 85.2869, "lat": 45.5054, "fullName": "克拉玛依市", "province": "新疆", }, "阿拉尔": { "lng": 81.2769, "lat": 40.6549, "fullName": "阿拉尔市", "province": "新疆", }, "图木": { "lng": 79.1345, "lat": 39.8749, "fullName": "图木舒克市", "province": "新疆", }, "五家": { "lng": 87.5391, "lat": 44.3024, "fullName": "五家渠市", "province": "新疆", }, "石河": { "lng": 86.0229, "lat": 44.2914, "fullName": "石河子市", "province": "新疆", }, "那曲": { "lng": 88.1982, "lat": 33.3215, "fullName": "那曲地区", "province": "西藏", }, "阿里": { "lng": 82.3645, "lat": 32.7667, "fullName": "阿里地区", "province": "西藏", }, "日喀": { "lng": 86.2427, "lat": 29.5093, "fullName": "日喀则地区", "province": "西藏", }, "林芝": { "lng": 95.4602, "lat": 29.1138, "fullName": "林芝地区", "province": "西藏", }, "昌都": { "lng": 97.0203, "lat": 30.7068, "fullName": "昌都地区", "province": "西藏", }, "山南": { "lng": 92.2083, "lat": 28.3392, "fullName": "山南地区", "province": "西藏", }, "拉萨": { "lng": 91.1865, "lat": 30.1465, "fullName": "拉萨市", "province": "西藏", }, "呼伦": { "lng": 120.8057, "lat": 50.2185, "fullName": "呼伦贝尔市", "province": "内蒙古", }, "阿拉善": { "lng": 102.019, "lat": 40.1001, "fullName": "阿拉善盟", "province": "内蒙古", }, "锡林": { "lng": 115.6421, "lat": 44.176, "fullName": "锡林郭勒盟", "province": "内蒙古", }, "鄂尔": { "lng": 108.9734, "lat": 39.2487, "fullName": "鄂尔多斯市", "province": "内蒙古", }, "赤峰": { "lng": 118.6743, "lat": 43.2642, "fullName": "赤峰市", "province": "内蒙古", }, "巴彦": { "lng": 107.5562, "lat": 41.3196, "fullName": "巴彦淖尔市", "province": "内蒙古", }, "通辽": { "lng": 121.4758, "lat": 43.9673, "fullName": "通辽市", "province": "内蒙古", }, "乌兰": { "lng": 112.5769, "lat": 41.77, "fullName": "乌兰察布市", "province": "内蒙古", }, "兴安": { "lng": 121.3879, "lat": 46.1426, "fullName": "兴安盟", "province": "内蒙古", }, "包头": { "lng": 110.3467, "lat": 41.4899, "fullName": "包头市", "province": "内蒙古", }, "呼和": { "lng": 111.4124, "lat": 40.4901, "fullName": "呼和浩特市", "province": "内蒙古", }, "乌海": { "lng": 106.886, "lat": 39.4739, "fullName": "乌海市", "province": "内蒙古", }, "海西": { "lng": 94.9768, "lat": 37.1118, "fullName": "海西蒙古族藏族自治州", "province": "青海", }, "玉树": { "lng": 93.5925, "lat": 33.9368, "fullName": "玉树藏族自治州", "province": "青海", }, "果洛": { "lng": 99.3823, "lat": 34.0466, "fullName": "果洛藏族自治州", "province": "青海", }, "海南": { "lng": 100.3711, "lat": 35.9418, "fullName": "海南藏族自治州", "province": "青海", }, "海北": { "lng": 100.3711, "lat": 37.9138, "fullName": "海北藏族自治州", "province": "青海", }, "黄南": { "lng": 101.5686, "lat": 35.1178, "fullName": "黄南藏族自治州", "province": "青海", }, "海东": { "lng": 102.3706, "lat": 36.2988, "fullName": "海东地区", "province": "青海", }, "西宁": { "lng": 101.4038, "lat": 36.8207, "fullName": "西宁市", "province": "青海", }, "甘孜": { "lng": 99.9207, "lat": 31.0803, "fullName": "甘孜藏族自治州", "province": "四川", }, "阿坝": { "lng": 102.4805, "lat": 32.4536, "fullName": "阿坝藏族羌族自治州", "province": "四川", }, "凉山": { "lng": 101.9641, "lat": 27.6746, "fullName": "凉山彝族自治州", "province": "四川", }, "绵阳": { "lng": 104.7327, "lat": 31.8713, "fullName": "绵阳市", "province": "四川", }, "达州": { "lng": 107.6111, "lat": 31.333, "fullName": "达州市", "province": "四川", }, "广元": { "lng": 105.6885, "lat": 32.2284, "fullName": "广元市", "province": "四川", }, "雅安": { "lng": 102.6672, "lat": 29.8938, "fullName": "雅安市", "province": "四川", }, "宜宾": { "lng": 104.6558, "lat": 28.548, "fullName": "宜宾市", "province": "四川", }, "乐山": { "lng": 103.5791, "lat": 29.1742, "fullName": "乐山市", "province": "四川", }, "南充": { "lng": 106.2048, "lat": 31.1517, "fullName": "南充市", "province": "四川", }, "巴中": { "lng": 107.0618, "lat": 31.9977, "fullName": "巴中市", "province": "四川", }, "泸州": { "lng": 105.4578, "lat": 28.493, "fullName": "泸州市", "province": "四川", }, "成都": { "lng": 103.9526, "lat": 30.7617, "fullName": "成都市", "province": "四川", }, "资阳": { "lng": 104.9744, "lat": 30.1575, "fullName": "资阳市", "province": "四川", }, "攀枝": { "lng": 101.6895, "lat": 26.7133, "fullName": "攀枝花市", "province": "四川", }, "眉山": { "lng": 103.8098, "lat": 30.0146, "fullName": "眉山市", "province": "四川", }, "广安": { "lng": 106.6333, "lat": 30.4376, "fullName": "广安市", "province": "四川", }, "德阳": { "lng": 104.48, "lat": 31.1133, "fullName": "德阳市", "province": "四川", }, "内江": { "lng": 104.8535, "lat": 29.6136, "fullName": "内江市", "province": "四川", }, "遂宁": { "lng": 105.5347, "lat": 30.6683, "fullName": "遂宁市", "province": "四川", }, "自贡": { "lng": 104.6667, "lat": 29.2786, "fullName": "自贡市", "province": "四川", }, "黑河": { "lng": 127.1448, "lat": 49.2957, "fullName": "黑河市", "province": "黑龙江", }, "大兴": { "lng": 124.1016, "lat": 52.2345, "fullName": "大兴安岭地区", "province": "黑龙江", }, "哈尔": { "lng": 127.9688, "lat": 45.368, "fullName": "哈尔滨市", "province": "黑龙江", }, "齐齐": { "lng": 124.541, "lat": 47.5818, "fullName": "齐齐哈尔市", "province": "黑龙江", }, "牡丹": { "lng": 129.7815, "lat": 44.7089, "fullName": "牡丹江市", "province": "黑龙江", }, "绥化": { "lng": 126.7163, "lat": 46.8018, "fullName": "绥化市", "province": "黑龙江", }, "伊春": { "lng": 129.1992, "lat": 47.9608, "fullName": "伊春市", "province": "黑龙江", }, "佳木": { "lng": 133.0005, "lat": 47.5763, "fullName": "佳木斯市", "province": "黑龙江", }, "鸡西": { "lng": 132.7917, "lat": 45.7361, "fullName": "鸡西市", "province": "黑龙江", }, "双鸭": { "lng": 133.5938, "lat": 46.7523, "fullName": "双鸭山市", "province": "黑龙江", }, "大庆": { "lng": 124.7717, "lat": 46.4282, "fullName": "大庆市", "province": "黑龙江", }, "鹤岗": { "lng": 130.4407, "lat": 47.7081, "fullName": "鹤岗市", "province": "黑龙江", }, "七台": { "lng": 131.2756, "lat": 45.9558, "fullName": "七台河市", "province": "黑龙江", }, "酒泉": { "lng": 96.2622, "lat": 40.4517, "fullName": "酒泉市", "province": "甘肃", }, "张掖": { "lng": 99.7998, "lat": 38.7433, "fullName": "张掖市", "province": "甘肃", }, "甘南": { "lng": 102.9199, "lat": 34.6893, "fullName": "甘南藏族自治州", "province": "甘肃", }, "武威": { "lng": 103.0188, "lat": 38.1061, "fullName": "武威市", "province": "甘肃", }, "陇南": { "lng": 105.304, "lat": 33.5632, "fullName": "陇南市", "province": "甘肃", }, "庆阳": { "lng": 107.5342, "lat": 36.2, "fullName": "庆阳市", "province": "甘肃", }, "白银": { "lng": 104.8645, "lat": 36.5076, "fullName": "白银市", "province": "甘肃", }, "定西": { "lng": 104.5569, "lat": 35.0848, "fullName": "定西市", "province": "甘肃", }, "天水": { "lng": 105.6445, "lat": 34.6289, "fullName": "天水市", "province": "甘肃", }, "兰州": { "lng": 103.5901, "lat": 36.3043, "fullName": "兰州市", "province": "甘肃", }, "平凉": { "lng": 107.0728, "lat": 35.321, "fullName": "平凉市", "province": "甘肃", }, "临夏": { "lng": 103.2715, "lat": 35.5737, "fullName": "临夏回族自治州", "province": "甘肃", }, "金昌": { "lng": 102.074, "lat": 38.5126, "fullName": "金昌市", "province": "甘肃", }, "嘉峪": { "lng": 98.1738, "lat": 39.8035, "fullName": "嘉峪关市", "province": "甘肃", }, "普洱": { "lng": 100.7446, "lat": 23.4229, "fullName": "普洱市", "province": "云南", }, "红河": { "lng": 103.0408, "lat": 23.6041, "fullName": "红河哈尼族彝族自治州", "province": "云南", }, "文山": { "lng": 104.8865, "lat": 23.5712, "fullName": "文山壮族苗族自治州", "province": "云南", }, "曲靖": { "lng": 103.9417, "lat": 25.7025, "fullName": "曲靖市", "province": "云南", }, "楚雄": { "lng": 101.6016, "lat": 25.3619, "fullName": "楚雄彝族自治州", "province": "云南", }, "大理": { "lng": 99.9536, "lat": 25.6805, "fullName": "大理白族自治州", "province": "云南", }, "临沧": { "lng": 99.613, "lat": 24.0546, "fullName": "临沧市", "province": "云南", }, "迪庆": { "lng": 99.4592, "lat": 27.9327, "fullName": "迪庆藏族自治州", "province": "云南", }, "昭通": { "lng": 104.0955, "lat": 27.6031, "fullName": "昭通市", "province": "云南", }, "昆明": { "lng": 102.9199, "lat": 25.4663, "fullName": "昆明市", "province": "云南", }, "丽江": { "lng": 100.448, "lat": 26.955, "fullName": "丽江市", "province": "云南", }, "西双": { "lng": 100.8984, "lat": 21.8628, "fullName": "西双版纳傣族自治州", "province": "云南", }, "保山": { "lng": 99.0637, "lat": 24.9884, "fullName": "保山市", "province": "云南", }, "玉溪": { "lng": 101.9312, "lat": 23.8898, "fullName": "玉溪市", "province": "云南", }, "怒江": { "lng": 99.1516, "lat": 26.5594, "fullName": "怒江傈僳族自治州", "province": "云南", }, "德宏": { "lng": 98.1299, "lat": 24.5874, "fullName": "德宏傣族景颇族自治州", "province": "云南", }, "百色": { "lng": 106.6003, "lat": 23.9227, "fullName": "百色市", "province": "广西", }, "河池": { "lng": 107.8638, "lat": 24.5819, "fullName": "河池市", "province": "广西", }, "桂林": { "lng": 110.5554, "lat": 25.318, "fullName": "桂林市", "province": "广西", }, "南宁": { "lng": 108.479, "lat": 23.1152, "fullName": "南宁市", "province": "广西", }, "柳州": { "lng": 109.3799, "lat": 24.9774, "fullName": "柳州市", "province": "广西", }, "崇左": { "lng": 107.3364, "lat": 22.4725, "fullName": "崇左市", "province": "广西", }, "来宾": { "lng": 109.7095, "lat": 23.8403, "fullName": "来宾市", "province": "广西", }, "玉林": { "lng": 110.2148, "lat": 22.3792, "fullName": "玉林市", "province": "广西", }, "梧州": { "lng": 110.9949, "lat": 23.5052, "fullName": "梧州市", "province": "广西", }, "贺州": { "lng": 111.3135, "lat": 24.4006, "fullName": "贺州市", "province": "广西", }, "钦州": { "lng": 109.0283, "lat": 22.0935, "fullName": "钦州市", "province": "广西", }, "贵港": { "lng": 109.9402, "lat": 23.3459, "fullName": "贵港市", "province": "广西", }, "防城": { "lng": 108.0505, "lat": 21.9287, "fullName": "防城港市", "province": "广西", }, "北海": { "lng": 109.314, "lat": 21.6211, "fullName": "北海市", "province": "广西", }, "怀化": { "lng": 109.9512, "lat": 27.4438, "fullName": "怀化市", "province": "湖南", }, "永州": { "lng": 111.709, "lat": 25.752, "fullName": "永州市", "province": "湖南", }, "邵阳": { "lng": 110.9619, "lat": 26.8121, "fullName": "邵阳市", "province": "湖南", }, "郴州": { "lng": 113.2361, "lat": 25.8673, "fullName": "郴州市", "province": "湖南", }, "常德": { "lng": 111.4014, "lat": 29.2676, "fullName": "常德市", "province": "湖南", }, "湘西": { "lng": 109.7864, "lat": 28.6743, "fullName": "湘西土家族苗族自治州", }, "衡阳": { "lng": 112.4121, "lat": 26.7902, "fullName": "衡阳市", "province": "湖南", }, "岳阳": { "lng": 113.2361, "lat": 29.1357, "fullName": "岳阳市", "province": "湖南", }, "益阳": { "lng": 111.731, "lat": 28.3832, "fullName": "益阳市", "province": "湖南", }, "长沙": { "lng": 113.0823, "lat": 28.2568, "fullName": "长沙市", "province": "湖南", }, "株洲": { "lng": 113.5327, "lat": 27.0319, "fullName": "株洲市", "province": "湖南", }, "张家界": { "lng": 110.5115, "lat": 29.328, "fullName": "张家界市", "province": "湖南", }, "娄底": { "lng": 111.6431, "lat": 27.7185, "fullName": "娄底市", "province": "湖南", }, "湘潭": { "lng": 112.5439, "lat": 27.7075, "fullName": "湘潭市", "province": "湖南", }, "榆林": { "lng": 109.8743, "lat": 38.205, "fullName": "榆林市", "province": "陕西", }, "延安": { "lng": 109.1052, "lat": 36.4252, "fullName": "延安市", "province": "陕西", }, "汉中": { "lng": 106.886, "lat": 33.0139, "fullName": "汉中市", "province": "陕西", }, "安康": { "lng": 109.1162, "lat": 32.7722, "fullName": "安康市", "province": "陕西", }, "商洛": { "lng": 109.8083, "lat": 33.761, "fullName": "商洛市", "province": "陕西", }, "宝鸡": { "lng": 107.1826, "lat": 34.3433, "fullName": "宝鸡市", "province": "陕西", }, "渭南": { "lng": 109.7864, "lat": 35.0299, "fullName": "渭南市", "province": "陕西", }, "咸阳": { "lng": 108.4131, "lat": 34.8706, "fullName": "咸阳市", "province": "陕西", }, "西安": { "lng": 109.1162, "lat": 34.2004, "fullName": "西安市", "province": "陕西", }, "铜川": { "lng": 109.0393, "lat": 35.1947, "fullName": "铜川市", "province": "陕西", }, "清远": { "lng": 112.9175, "lat": 24.3292, "fullName": "清远市", "province": "广东", }, "韶关": { "lng": 113.7964, "lat": 24.7028, "fullName": "韶关市", "province": "广东", }, "湛江": { "lng": 110.3577, "lat": 20.9894, "fullName": "湛江市", "province": "广东", }, "梅州": { "lng": 116.1255, "lat": 24.1534, "fullName": "梅州市", "province": "广东", }, "河源": { "lng": 114.917, "lat": 23.9722, "fullName": "河源市", "province": "广东", }, "肇庆": { "lng": 112.1265, "lat": 23.5822, "fullName": "肇庆市", "province": "广东", }, "惠州": { "lng": 114.6204, "lat": 23.1647, "fullName": "惠州市", "province": "广东", }, "茂名": { "lng": 111.0059, "lat": 22.0221, "fullName": "茂名市", "province": "广东", }, "江门": { "lng": 112.6318, "lat": 22.1484, "fullName": "江门市", "province": "广东", }, "阳江": { "lng": 111.8298, "lat": 22.0715, "fullName": "阳江市", "province": "广东", }, "云浮": { "lng": 111.7859, "lat": 22.8516, "fullName": "云浮市", "province": "广东", }, "广州": { "lng": 113.5107, "lat": 23.2196, "fullName": "广州市", "province": "广东", }, "汕尾": { "lng": 115.5762, "lat": 23.0438, "fullName": "汕尾市", "province": "广东", }, "揭阳": { "lng": 116.1255, "lat": 23.313, "fullName": "揭阳市", "province": "广东", }, "珠海": { "lng": 113.7305, "lat": 22.1155, "fullName": "珠海市", "province": "广东", }, "佛山": { "lng": 112.8955, "lat": 23.1097, "fullName": "佛山市", "province": "广东", }, "潮州": { "lng": 116.7847, "lat": 23.8293, "fullName": "潮州市", "province": "广东", }, "汕头": { "lng": 117.1692, "lat": 23.3405, "fullName": "汕头市", "province": "广东", }, "深圳": { "lng": 114.5435, "lat": 22.5439, "fullName": "深圳市", "province": "广东", }, "东莞": { "lng": 113.8953, "lat": 22.901, "fullName": "东莞市", "province": "广东", }, "中山": { "lng": 113.4229, "lat": 22.478, "fullName": "中山市", "province": "广东", }, "延边": { "lng": 129.397, "lat": 43.2587, "fullName": "延边朝鲜族自治州", "province": "吉林", }, "吉林": { "lng": 126.8372, "lat": 43.6047, "fullName": "吉林市", "province": "吉林", }, "白城": { "lng": 123.0029, "lat": 45.2637, "fullName": "白城市", "province": "吉林", }, "松原": { "lng": 124.0906, "lat": 44.7198, "fullName": "松原市", "province": "吉林", }, "长春": { "lng": 125.8154, "lat": 44.2584, "fullName": "长春市", "province": "吉林", }, "白山": { "lng": 127.2217, "lat": 42.0941, "fullName": "白山市", "province": "吉林", }, "通化": { "lng": 125.9583, "lat": 41.8579, "fullName": "通化市", "province": "吉林", }, "四平": { "lng": 124.541, "lat": 43.4894, "fullName": "四平市", "province": "吉林", }, "辽源": { "lng": 125.343, "lat": 42.7643, "fullName": "辽源市", "province": "吉林", }, "承德": { "lng": 117.5757, "lat": 41.4075, "fullName": "承德市", "province": "河北", }, "张家口": { "lng": 115.1477, "lat": 40.8527, "fullName": "张家口市", "province": "河北", }, "保定": { "lng": 115.0488, "lat": 39.0948, "fullName": "保定市", "province": "河北", }, "唐山": { "lng": 118.4766, "lat": 39.6826, "fullName": "唐山市", "province": "河北", }, "沧州": { "lng": 116.8286, "lat": 38.2104, "fullName": "沧州市", "province": "河北", }, "石家": { "lng": 114.4995, "lat": 38.1006, "fullName": "石家庄市", "province": "河北", }, "邢台": { "lng": 114.8071, "lat": 37.2821, "fullName": "邢台市", "province": "河北", }, "邯郸": { "lng": 114.4775, "lat": 36.535, "fullName": "邯郸市", "province": "河北", }, "秦皇": { "lng": 119.2126, "lat": 40.0232, "fullName": "秦皇岛市", "province": "河北", }, "衡水": { "lng": 115.8838, "lat": 37.7161, "fullName": "衡水市", "province": "河北", }, "廊坊": { "lng": 116.521, "lat": 39.0509, "fullName": "廊坊市", "province": "河北", }, "恩施": { "lng": 109.5007, "lat": 30.2563, "fullName": "恩施土家族苗族自治州", "province": "湖北", }, "十堰": { "lng": 110.5115, "lat": 32.3877, "fullName": "十堰市", "province": "湖北", }, "宜昌": { "lng": 111.1707, "lat": 30.7617, "fullName": "宜昌市", "province": "湖北", }, "襄樊": { "lng": 111.9397, "lat": 31.9263, "fullName": "襄樊市", "province": "湖北", }, "黄冈": { "lng": 115.2686, "lat": 30.6628, "fullName": "黄冈市", "province": "湖北", }, "荆州": { "lng": 113.291, "lat": 30.0092, "fullName": "荆州市", "province": "湖北", }, "荆门": { "lng": 112.6758, "lat": 30.9979, "fullName": "荆门市", "province": "湖北", }, "咸宁": { "lng": 114.2578, "lat": 29.6631, "fullName": "咸宁市", "province": "湖北", }, "随州": { "lng": 113.4338, "lat": 31.8768, "fullName": "随州市", "province": "湖北", }, "孝感": { "lng": 113.9502, "lat": 31.1188, "fullName": "孝感市", "province": "湖北", }, "武汉": { "lng": 114.3896, "lat": 30.6628, "fullName": "武汉市", "province": "湖北", }, "黄石": { "lng": 115.0159, "lat": 29.9213, "fullName": "黄石市", "province": "湖北", }, "神农": { "lng": 110.4565, "lat": 31.5802, "fullName": "神农架林区", "province": "湖北", }, "天门": { "lng": 113.0273, "lat": 30.6409, "fullName": "天门市", "province": "湖北", }, "仙桃": { "lng": 113.3789, "lat": 30.3003, "fullName": "仙桃市", "province": "湖北", }, "潜江": { "lng": 112.7637, "lat": 30.3607, "fullName": "潜江市", "province": "湖北", }, "鄂州": { "lng": 114.7302, "lat": 30.4102, "fullName": "鄂州市", "province": "湖北", }, "遵义": { "lng": 106.908, "lat": 28.1744, "fullName": "遵义市", "province": "贵州", }, "黔东": { "lng": 108.4241, "lat": 26.4166, "fullName": "黔东南苗族侗族自治州", "province": "贵州", }, "毕节": { "lng": 105.1611, "lat": 27.0648, "fullName": "毕节地区", "province": "贵州", }, "黔南": { "lng": 107.2485, "lat": 25.8398, "fullName": "黔南布依族苗族自治州", "province": "贵州", }, "铜仁": { "lng": 108.6218, "lat": 28.0096, "fullName": "铜仁地区", "province": "贵州", }, "黔西": { "lng": 105.5347, "lat": 25.3949, "fullName": "黔西南布依族苗族自治州", "province": "贵州", }, "六盘": { "lng": 104.7546, "lat": 26.0925, "fullName": "六盘水市", "province": "贵州", }, "安顺": { "lng": 105.9082, "lat": 25.9882, "fullName": "安顺市", "province": "贵州", }, "贵阳": { "lng": 106.6992, "lat": 26.7682, "fullName": "贵阳市", "province": "贵州", }, "烟台": { "lng": 120.7397, "lat": 37.5128, "fullName": "烟台市", "province": "山东", }, "临沂": { "lng": 118.3118, "lat": 35.2936, "fullName": "临沂市", "province": "山东", }, "潍坊": { "lng": 119.0918, "lat": 36.524, "fullName": "潍坊市", "province": "山东", }, "青岛": { "lng": 120.4651, "lat": 36.3373, "fullName": "青岛市", "province": "山东", }, "菏泽": { "lng": 115.6201, "lat": 35.2057, "fullName": "菏泽市", "province": "山东", }, "济宁": { "lng": 116.8286, "lat": 35.3375, "fullName": "济宁市", "province": "山东", }, "德州": { "lng": 116.6858, "lat": 37.2107, "fullName": "德州市", "province": "山东", }, "滨州": { "lng": 117.8174, "lat": 37.4963, "fullName": "滨州市", "province": "山东", }, "聊城": { "lng": 115.9167, "lat": 36.4032, "fullName": "聊城市", "province": "山东", }, "东营": { "lng": 118.7073, "lat": 37.5513, "fullName": "东营市", "province": "山东", }, "济南": { "lng": 117.1582, "lat": 36.8701, "fullName": "济南市", "province": "山东", }, "泰安": { "lng": 117.0264, "lat": 36.0516, "fullName": "泰安市", "province": "山东", }, "威海": { "lng": 121.9482, "lat": 37.1393, "fullName": "威海市", "province": "山东", }, "日照": { "lng": 119.2786, "lat": 35.5023, "fullName": "日照市", "province": "山东", }, "淄博": { "lng": 118.0371, "lat": 36.6064, "fullName": "淄博市", "province": "山东", }, "枣庄": { "lng": 117.323, "lat": 34.8926, "fullName": "枣庄市", "province": "山东", }, "莱芜": { "lng": 117.6526, "lat": 36.2714, "fullName": "莱芜市", "province": "山东", }, "赣州": { "lng": 115.2795, "lat": 25.8124, "fullName": "赣州市", "province": "江西", }, "吉安": { "lng": 114.884, "lat": 26.9659, "fullName": "吉安市", "province": "江西", }, "上饶": { "lng": 117.8613, "lat": 28.7292, "fullName": "上饶市", "province": "江西", }, "九江": { "lng": 115.4224, "lat": 29.3774, "fullName": "九江市", "province": "江西", }, "抚州": { "lng": 116.4441, "lat": 27.4933, "fullName": "抚州市", "province": "江西", }, "宜春": { "lng": 115.0159, "lat": 28.3228, "fullName": "宜春市", "province": "江西", }, "南昌": { "lng": 116.0046, "lat": 28.6633, "fullName": "南昌市", "province": "江西", }, "景德": { "lng": 117.334, "lat": 29.3225, "fullName": "景德镇市", "province": "江西", }, "萍乡": { "lng": 113.9282, "lat": 27.4823, "fullName": "萍乡市", "province": "江西", }, "鹰潭": { "lng": 117.0813, "lat": 28.2349, "fullName": "鹰潭市", "province": "江西", }, "新余": { "lng": 114.95, "lat": 27.8174, "fullName": "新余市", "province": "江西", }, "南阳": { "lng": 112.4011, "lat": 33.0359, "fullName": "南阳市", "province": "河南", }, "信阳": { "lng": 114.8291, "lat": 32.0197, "fullName": "信阳市", "province": "河南", }, "洛阳": { "lng": 112.0605, "lat": 34.3158, "fullName": "洛阳市", "province": "河南", }, "驻马": { "lng": 114.1589, "lat": 32.9041, "fullName": "驻马店市", "province": "河南", }, "周口": { "lng": 114.873, "lat": 33.6951, "fullName": "周口市", "province": "河南", }, "商丘": { "lng": 115.741, "lat": 34.2828, "fullName": "商丘市", "province": "河南", }, "三门": { "lng": 110.8301, "lat": 34.3158, "fullName": "三门峡市", "province": "河南", }, "新乡": { "lng": 114.2029, "lat": 35.3595, "fullName": "新乡市", "province": "河南", }, "平顶": { "lng": 112.9724, "lat": 33.739, "fullName": "平顶山市", "province": "河南", }, "郑州": { "lng": 113.4668, "lat": 34.6234, "fullName": "郑州市", "province": "河南", }, "安阳": { "lng": 114.5325, "lat": 36.0022, "fullName": "安阳市", "province": "河南", }, "开封": { "lng": 114.5764, "lat": 34.6124, "fullName": "开封市", "province": "河南", }, "焦作": { "lng": 112.8406, "lat": 35.1508, "fullName": "焦作市", "province": "河南", }, "济源": { "lng": 112.3571, "lat": 35.0849, "fullName": "济源市", "province": "河南", }, "许昌": { "lng": 113.6975, "lat": 34.0466, "fullName": "许昌市", "province": "河南", }, "濮阳": { "lng": 115.1917, "lat": 35.799, "fullName": "濮阳市", "province": "河南", }, "漯河": { "lng": 113.8733, "lat": 33.6951, "fullName": "漯河市", "province": "河南", }, "鹤壁": { "lng": 114.3787, "lat": 35.744, "fullName": "鹤壁市", "province": "河南", }, "大连": { "lng": 122.2229, "lat": 39.4409, "fullName": "大连市", "province": "辽宁", }, "朝阳": { "lng": 120.0696, "lat": 41.4899, "fullName": "朝阳市", "province": "辽宁", }, "丹东": { "lng": 124.541, "lat": 40.4242, "fullName": "丹东市", "province": "辽宁", }, "铁岭": { "lng": 124.2773, "lat": 42.7423, "fullName": "铁岭市", "province": "辽宁", }, "沈阳": { "lng": 123.1238, "lat": 42.1216, "fullName": "沈阳市", "province": "辽宁", }, "抚顺": { "lng": 124.585, "lat": 41.8579, "fullName": "抚顺市", "province": "辽宁", }, "葫芦": { "lng": 120.1575, "lat": 40.578, "fullName": "葫芦岛市", "province": "辽宁", }, "阜新": { "lng": 122.0032, "lat": 42.2699, "fullName": "阜新市", "province": "辽宁", }, "锦州": { "lng": 121.6626, "lat": 41.4294, "fullName": "锦州市", "province": "辽宁", }, "鞍山": { "lng": 123.0798, "lat": 40.6055, "fullName": "鞍山市", "province": "辽宁", }, "本溪": { "lng": 124.1455, "lat": 41.1987, "fullName": "本溪市", "province": "辽宁", }, "营口": { "lng": 122.4316, "lat": 40.4297, "fullName": "营口市", "province": "辽宁", }, "辽阳": { "lng": 123.4094, "lat": 41.1383, "fullName": "辽阳市", "province": "辽宁", }, "盘锦": { "lng": 121.9482, "lat": 41.0449, "fullName": "盘锦市", "province": "辽宁", }, "忻州": { "lng": 112.4561, "lat": 38.8971, "fullName": "忻州市", "province": "山西", }, "吕梁": { "lng": 111.3574, "lat": 37.7325, "fullName": "吕梁市", "province": "山西", }, "临汾": { "lng": 111.4783, "lat": 36.1615, "fullName": "临汾市", "province": "山西", }, "晋中": { "lng": 112.7747, "lat": 37.37, "fullName": "晋中市", "province": "山西", }, "运城": { "lng": 111.1487, "lat": 35.2002, "fullName": "运城市", "province": "山西", }, "大同": { "lng": 113.7854, "lat": 39.8035, "fullName": "大同市", "province": "山西", }, "长治": { "lng": 112.8625, "lat": 36.4746, "fullName": "长治市", "province": "山西", }, "朔州": { "lng": 113.0713, "lat": 39.6991, "fullName": "朔州市", "province": "山西", }, "晋城": { "lng": 112.7856, "lat": 35.6342, "fullName": "晋城市", "province": "山西", }, "太原": { "lng": 112.3352, "lat": 37.9413, "fullName": "太原市", "province": "山西", }, "阳泉": { "lng": 113.4778, "lat": 38.0951, "fullName": "阳泉市", "province": "山西", }, "六安": { "lng": 116.3123, "lat": 31.8329, "fullName": "六安市", "province": "安徽", }, "安庆": { "lng": 116.7517, "lat": 30.5255, "fullName": "安庆市", "province": "安徽", }, "滁州": { "lng": 118.1909, "lat": 32.536, "fullName": "滁州市", "province": "安徽", }, "宣城": { "lng": 118.8062, "lat": 30.6244, "fullName": "宣城市", "province": "安徽", }, "阜阳": { "lng": 115.7629, "lat": 32.9919, "fullName": "阜阳市", "province": "安徽", }, "宿州": { "lng": 117.5208, "lat": 33.6841, "fullName": "宿州市", "province": "安徽", }, "黄山": { "lng": 118.0481, "lat": 29.9542, "fullName": "黄山市", "province": "安徽", }, "巢湖": { "lng": 117.7734, "lat": 31.4978, "fullName": "巢湖市", "province": "安徽", }, "亳州": { "lng": 116.1914, "lat": 33.4698, "fullName": "亳州市", "province": "安徽", }, "池州": { "lng": 117.3889, "lat": 30.2014, "fullName": "池州市", "province": "安徽", }, "合肥": { "lng": 117.29, "lat": 32.0581, "fullName": "合肥市", "province": "安徽", }, "蚌埠": { "lng": 117.4109, "lat": 33.1073, "fullName": "蚌埠市", "province": "安徽", }, "芜湖": { "lng": 118.3557, "lat": 31.0858, "fullName": "芜湖市", "province": "安徽", }, "淮北": { "lng": 116.6968, "lat": 33.6896, "fullName": "淮北市", "province": "安徽", }, "淮南": { "lng": 116.7847, "lat": 32.7722, "fullName": "淮南市", "province": "安徽", }, "马鞍": { "lng": 118.6304, "lat": 31.5363, "fullName": "马鞍山市", "province": "安徽", }, "铜陵": { "lng": 117.9382, "lat": 30.9375, "fullName": "铜陵市", "province": "安徽", }, "南平": { "lng": 118.136, "lat": 27.2845, "fullName": "南平市", "province": "福建", }, "三明": { "lng": 117.5317, "lat": 26.3013, "fullName": "三明市", "province": "福建", }, "龙岩": { "lng": 116.8066, "lat": 25.2026, "fullName": "龙岩市", "province": "福建", }, "宁德": { "lng": 119.6521, "lat": 26.9824, "fullName": "宁德市", "province": "福建", }, "福州": { "lng": 119.4543, "lat": 25.9222, "fullName": "福州市", "province": "福建", }, "漳州": { "lng": 117.5757, "lat": 24.3732, "fullName": "漳州市", "province": "福建", }, "泉州": { "lng": 118.3228, "lat": 25.1147, "fullName": "泉州市", "province": "福建", }, "莆田": { "lng": 119.0918, "lat": 25.3455, "fullName": "莆田市", "province": "福建", }, "厦门": { "lng": 118.1689, "lat": 24.6478, "fullName": "厦门市", "province": "福建", }, "丽水": { "lng": 119.5642, "lat": 28.1854, "fullName": "丽水市", "province": "浙江", }, "杭州": { "lng": 119.5313, "lat": 29.8773, "fullName": "杭州市", "province": "浙江", }, "温州": { "lng": 120.498, "lat": 27.8119, "fullName": "温州市", "province": "浙江", }, "宁波": { "lng": 121.5967, "lat": 29.6466, "fullName": "宁波市", "province": "浙江", }, "舟山": { "lng": 122.2559, "lat": 30.2234, "fullName": "舟山市", "province": "浙江", }, "台州": { "lng": 121.1353, "lat": 28.6688, "fullName": "台州市", "province": "浙江", }, "金华": { "lng": 120.0037, "lat": 29.1028, "fullName": "金华市", "province": "浙江", }, "衢州": { "lng": 118.6853, "lat": 28.8666, "fullName": "衢州市", "province": "浙江", }, "绍兴": { "lng": 120.564, "lat": 29.7565, "fullName": "绍兴市", "province": "浙江", }, "嘉兴": { "lng": 120.9155, "lat": 30.6354, "fullName": "嘉兴市", "province": "浙江", }, "湖州": { "lng": 119.8608, "lat": 30.7782, "fullName": "湖州市", "province": "浙江", }, "盐城": { "lng": 120.2234, "lat": 33.5577, "fullName": "盐城市", "province": "江苏", }, "徐州": { "lng": 117.5208, "lat": 34.3268, "fullName": "徐州市", "province": "江苏", }, "南通": { "lng": 121.1023, "lat": 32.1625, "fullName": "南通市", "province": "江苏", }, "淮安": { "lng": 118.927, "lat": 33.4039, "fullName": "淮安市", "province": "江苏", }, "苏州": { "lng": 120.6519, "lat": 31.3989, "fullName": "苏州市", "province": "江苏", }, "宿迁": { "lng": 118.5535, "lat": 33.7775, "fullName": "宿迁市", "province": "江苏", }, "连云": { "lng": 119.1248, "lat": 34.552, "fullName": "连云港市", "province": "江苏", }, "扬州": { "lng": 119.4653, "lat": 32.8162, "fullName": "扬州市", "province": "江苏", }, "南京": { "lng": 118.8062, "lat": 31.9208, "fullName": "南京市", "province": "江苏", }, "泰州": { "lng": 120.0586, "lat": 32.5525, "fullName": "泰州市", "province": "江苏", }, "无锡": { "lng": 120.3442, "lat": 31.5527, "fullName": "无锡市", "province": "江苏", }, "常州": { "lng": 119.4543, "lat": 31.5582, "fullName": "常州市", "province": "江苏", }, "镇江": { "lng": 119.4763, "lat": 31.9702, "fullName": "镇江市", "province": "江苏", }, "吴忠": { "lng": 106.853, "lat": 37.3755, "fullName": "吴忠市", "province": "宁夏", }, "中卫": { "lng": 105.4028, "lat": 36.9525, "fullName": "中卫市", "province": "宁夏", }, "固原": { "lng": 106.1389, "lat": 35.9363, "fullName": "固原市", "province": "宁夏", }, "银川": { "lng": 106.3586, "lat": 38.1775, "fullName": "银川市", "province": "宁夏", }, "石嘴": { "lng": 106.4795, "lat": 39.0015, "fullName": "石嘴山市", "province": "宁夏", }, "儋州": { "lng": 109.3291, "lat": 19.5653, "fullName": "儋州市", "province": "海南", }, "文昌": { "lng": 110.8905, "lat": 19.7823, "fullName": "文昌市", "province": "海南", }, "乐东": { "lng": 109.0283, "lat": 18.6301, "fullName": "乐东黎族自治县", "province": "海南", }, "三亚": { "lng": 109.3716, "lat": 18.3698, "fullName": "三亚市", "province": "海南", }, "琼中": { "lng": 109.8413, "lat": 19.0736, "fullName": "琼中黎族苗族自治县", "province": "海南", }, "东方": { "lng": 108.8498, "lat": 19.0414, "fullName": "东方市", "province": "海南", }, "海口": { "lng": 110.3893, "lat": 19.8516, "fullName": "海口市", "province": "海南", }, "万宁": { "lng": 110.3137, "lat": 18.8388, "fullName": "万宁市", "province": "海南", }, "澄迈": { "lng": 109.9937, "lat": 19.7314, "fullName": "澄迈县", "province": "海南", }, "白沙": { "lng": 109.3703, "lat": 19.211, "fullName": "白沙黎族自治县", "province": "海南", }, "琼海": { "lng": 110.4208, "lat": 19.224, "fullName": "琼海市", "province": "海南", }, "昌江": { "lng": 109.0407, "lat": 19.2137, "fullName": "昌江黎族自治县", "province": "海南", }, "临高": { "lng": 109.6957, "lat": 19.8063, "fullName": "临高县", "province": "海南", }, "陵水": { "lng": 109.9924, "lat": 18.5415, "fullName": "陵水黎族自治县", "province": "海南", }, "屯昌": { "lng": 110.0377, "lat": 19.362, "fullName": "屯昌县", "province": "海南", }, "定安": { "lng": 110.3384, "lat": 19.4698, "fullName": "定安县", "province": "海南", }, "保亭": { "lng": 109.6284, "lat": 18.6108, "fullName": "保亭黎族苗族自治县", "province": "海南", }, "五指": { "lng": 109.5282, "lat": 18.8299, "fullName": "五指山市", "province": "海南", } }; // 外国坐标,先注释 // const worldCountriesMap = { // "Moscow": { // "lat": "55.7494733", // "lng": "37.3523218", // "fullName": "莫斯科" // }, // "Petersburg": { // "lat": "59.9171483", // "lng": "30.0448871", // "fullName": "圣彼得堡" // }, // "Vladivostok": { // "lat": "43.1736206", // "lng": "131.895754", // "fullName": "符拉迪沃斯托克(海参崴)" // }, // "Yekaterinburg": { // "lat": "56.8138126", // "lng": "60.5148523", // "fullName": "叶卡捷琳堡" // }, // "Novgorod": { // "lat": "56.2926609", // "lng": "43.786664", // "fullName": "下诺夫哥罗德" // }, // "Novosibirsk": { // "lat": "54.969655", // "lng": "82.6692313", // "fullName": "新西伯利亚" // }, // "Rostov": { // "lat": "57.1968001", // "lng": "39.3805101", // "fullName": "罗斯托夫" // }, // "Uhde": { // "lat": "51.8298243", // "lng": "107.4760822", // "fullName": "乌兰乌德" // }, // "Irkutsk": { // "lat": "52.2983044", // "lng": "104.1270763", // "fullName": "伊尔库茨克" // }, // "Murmansk": { // "lat": "68.9673991", // "lng": "32.9457132", // "fullName": "摩尔曼斯克" // }, // "Sochi": { // "lat": "43.6017001", // "lng": "39.6550893", // "fullName": "索契" // }, // "Volgograd": { // "lat": "48.6700797", // "lng": "44.22653", // "fullName": "伏尔加格勒" // }, // "Kazan": { // "lat": "55.7954219", // "lng": "48.9332217", // "fullName": "喀山" // }, // "RostovOnDon": { // "lat": "47.2609231", // "lng": "39.4879174", // "fullName": "顿河畔罗斯托夫" // }, // "Samara": { // "lat": "53.2605796", // "lng": "49.9179024", // "fullName": "萨马拉" // }, // "Omsk": { // "lat": "54.985554", // "lng": "73.0759653", // "fullName": "鄂木斯克" // }, // "Chelyabinsk": { // "lat": "55.1519087", // "lng": "61.1283971", // "fullName": "车里雅宾斯克" // }, // "Khabarovsk": { // "lat": "48.4647596", // "lng": "134.9733447", // "fullName": "伯力" // }, // "Pyatigorsk": { // "lat": "44.0433504", // "lng": "42.9705613", // "fullName": "皮亚季戈尔斯克" // }, // "Ufa": { // "lat": "54.8086988", // "lng": "55.8807921", // "fullName": "乌法" // }, // "Perm": { // "lat": "58.0201783", // "lng": "55.9541039", // "fullName": "彼尔姆" // }, // "Krasnoyarsk": { // "lat": "56.0266501", // "lng": "92.7256527", // "fullName": "克拉斯诺亚尔斯克" // }, // "Voronezh": { // "lat": "51.6753557", // "lng": "38.9559888", // "fullName": "沃罗涅日" // }, // "Saratov": { // "lat": "51.5341886", // "lng": "45.8700586", // "fullName": "萨拉托夫" // }, // "Krasnodar": { // "lat": "45.0535266", // "lng": "38.9460163", // "fullName": "克拉斯诺达尔" // }, // "Tolyatti": { // "lat": "53.5218291", // "lng": "49.2950109", // "fullName": "陶里亚蒂" // }, // "Izevsk": { // "lat": "56.8637312", // "lng": "53.0880195", // "fullName": "伊热夫斯克" // }, // "Ulyanovsk": { // "lat": "54.3110964", // "lng": "48.326138", // "fullName": "乌里扬诺夫斯克" // }, // "Barnaul": { // "lat": "53.3332194", // "lng": "83.5971963", // "fullName": "巴尔瑙尔" // }, // "Yaroslavl": { // "lat": "57.6523811", // "lng": "39.7244361", // "fullName": "雅罗斯拉夫尔" // }, // // "Brasilia": { // "lat": "-15.7217175", // "lng": "-48.0783217", // "fullName": "巴西利亚" // }, // "Paulo": { // "lat": "-23.6821604", // "lng": "-46.8754884", // "fullName": "圣保罗" // }, // "Iguazul": { // "lat": "-25.46543", // "lng": "-54.5972328", // "fullName": "伊瓜苏市" // }, // "Janeiro": { // "lat": "-22.9109878", // "lng": "-43.7285235", // "fullName": "里约热内卢" // }, // "Horizonte": { // "lat": "-19.9178164", // "lng": "-44.100397", // "fullName": "贝洛奥里藏特" // }, // "Manaus": { // "lat": "-2.573136", // "lng": "-60.5418579", // "fullName": "玛瑙斯市" // }, // "Salvador": { // "lat": "-12.8808976", // "lng": "-38.557671", // "fullName": "萨尔瓦多" // }, // "Recife": { // "lat": "-8.0464433", // "lng": "-35.0025286", // "fullName": "累西腓" // }, // "Alegre": { // "lat": "-30.1007488", // "lng": "-51.2990333", // "fullName": "阿雷格里港" // }, // "Goiania": { // "lat": "-16.6427714", // "lng": "-49.4025521", // "fullName": "戈亚尼亚" // }, // "Curitiba": { // "lat": "-25.4950853", // "lng": "-49.4274875", // "fullName": "库里蒂巴" // }, // // "Istanbul": { // "lat": "41.0049823", // "lng": "28.7319977", // "fullName": "伊斯坦布尔" // }, // "Ankara": { // "lat": "39.9032923", // "lng": "32.6226813", // "fullName": "安卡拉" // }, // "Izmir": { // "lat": "38.4175917", // "lng": "26.9396782", // "fullName": "伊兹密尔" // }, // "Bursa": { // "lat": "40.2215936", // "lng": "28.8922061", // "fullName": "布尔萨" // }, // "Adana": { // "lat": "36.9973327", // "lng": "35.1479832", // "fullName": "阿达纳" // }, // "Gaziantep": { // "lat": "37.0587663", // "lng": "37.3451175", // "fullName": "加济安泰普" // }, // "Konya": { // "lat": "37.8784235", // "lng": "32.3663988", // "fullName": "科尼亚" // }, // "Antalya": { // "lat": "36.897917", // "lng": "30.6480652", // "fullName": "安塔利亚" // }, // "Kayserispor": { // "lat": "38.7233801", // "lng": "35.4001473", // "fullName": "开塞利" // }, // "Samsun": { // "lat": "41.291388", // "lng": "36.2436588", // "fullName": "萨姆松" // }, // // "Madrid": { // "lat": "40.4378698", // "lng": "-3.81962", // "fullName": "马德里" // }, // "Barcelona": { // "lat": "41.3947688", // "lng": "2.0787281", // "fullName": "巴塞罗那" // }, // "Valencia": { // "lat": "39.468913", // "lng": "-0.4364238", // "fullName": "巴伦西亚" // }, // "Sevilla": { // "lat": "37.3753501", // "lng": "-6.0250981", // "fullName": "塞维利亚" // }, // "Cordoba": { // "lat": "37.8915808", // "lng": "-4.8195047", // "fullName": "科尔多瓦" // }, // // "NewYork": { // "lat": "40.7029741", // "lng": "-74.2598629", // "fullName": "纽约" // }, // "LosAngeles": { // "lat": "34.0201812", // "lng": "-118.6919177", // "fullName": "洛杉矶" // }, // "Chicago": { // "lat": "41.8336478", // "lng": "-87.8722387", // "fullName": "芝加哥" // }, // "Houston": { // "lat": "29.8168824", // "lng": "-95.6814784", // "fullName": "休斯敦" // }, // "Philadelphia": { // "lat": "40.0046684", // "lng": "-75.2581164", // "fullName": "费城" // }, // "Phoenix": { // "lat": "33.6050991", // "lng": "-112.4052364", // "fullName": "菲尼克斯(凤凰城)" // }, // "SanDiego": { // "lat": "32.8242404", // "lng": "-117.375349", // "fullName": "圣地亚哥" // }, // "Dallas": { // "lat": "32.8205865", // "lng": "-96.8714239", // "fullName": "达拉斯" // }, // "SanAntonio": { // "lat": "29.481137", // "lng": "-98.7945916", // "fullName": "圣安东尼奥" // }, // "Detroit": { // "lat": "42.3526257", // "lng": "-83.2392882", // "fullName": "底特律" // }, // "Indianapolis": { // "lat": "39.7797003", // "lng": "-86.2728335", // "fullName": "印第安纳波利斯" // }, // "SanFrancisco": { // "lat": "37.7576793", // "lng": "-122.5076399", // "fullName": "旧金山" // }, // "Columbus": { // "lat": "39.9828671", // "lng": "-83.1309125", // "fullName": "哥伦布" // }, // "Austin": { // "lat": "30.3076863", // "lng": "-97.8934859", // "fullName": "奥斯汀" // }, // "Baltimore": { // "lat": "39.2846854", // "lng": "-76.6905258", // "fullName": "巴尔的摩" // }, // "Milwaukee": { // "lat": "43.057806", // "lng": "-88.1075131", // "fullName": "密尔沃基" // }, // "Boston": { // "lat": "42.3133521", // "lng": "-71.1271968", // "fullName": "波士顿" // }, // "Washington": { // "lat": "38.8993278", // "lng": "-77.0846063", // "fullName": "华盛顿" // }, // "Seattle": { // "lat": "47.6147628", // "lng": "-122.4759883", // "fullName": "西雅图" // }, // "Atlanta": { // "lat": "33.7676338", // "lng": "-84.5606881", // "fullName": "亚特兰大" // }, // "SanJose": { // "lat": "37.296933", // "lng": "-121.9574947", // "fullName": "圣荷西" // }, // "Jacksonville": { // "lat": "30.3446913", // "lng": "-82.0006437", // "fullName": "杰克逊维尔" // }, // "Memphis": { // "lat": "35.1288636", // "lng": "-90.2509716", // "fullName": "孟菲斯" // }, // "Charlotte": { // "lat": "35.2030728", // "lng": "-80.97961", // "fullName": "夏洛特" // }, // "FortWorth": { // "lat": "32.800501", // "lng": "-97.5695047", // "fullName": "沃思堡" // }, // // // "BD": { // "lat": "24", // "lng": "90", // "fullName": "BANGLADESH" // }, // "BE": { // "lat": "50.8333", // "lng": "4", // "fullName": "BELGIUM" // }, // "BF": { // "lat": "13", // "lng": "-2", // "fullName": "BURKINA FASO" // }, // "BG": { // "lat": "43", // "lng": "25", // "fullName": "BULGARIA" // }, // "BA": { // "lat": "44", // "lng": "18", // "fullName": "BOSNIA AND HERZEGOVINA" // }, // "BB": { // "lat": "13.1667", // "lng": "-59.5333", // "fullName": "BARBADOS" // }, // "WF": { // "lat": "-13.3", // "lng": "-176.2", // "fullName": "WALLIS AND FUTUNA" // }, // "BM": { // "lat": "32.3333", // "lng": "-64.75", // "fullName": "BERMUDA" // }, // "BN": { // "lat": "4.5", // "lng": "114.6667", // "fullName": "BRUNEI DARUSSALAM" // }, // "BO": { // "lat": "-17", // "lng": "-65", // "fullName": "BOLIVIA, PLURINATIONAL STATE OF" // }, // "BH": { // "lat": "26", // "lng": "50.55", // "fullName": "BAHRAIN" // }, // "BI": { // "lat": "-3.5", // "lng": "30", // "fullName": "BURUNDI" // }, // "BJ": { // "lat": "9.5", // "lng": "2.25", // "fullName": "BENIN" // }, // "BT": { // "lat": "27.5", // "lng": "90.5", // "fullName": "BHUTAN" // }, // "JM": { // "lat": "18.25", // "lng": "-77.5", // "fullName": "JAMAICA" // }, // "BV": { // "lat": "-54.4333", // "lng": "3.4", // "fullName": "BOUVET ISLAND" // }, // "BW": { // "lat": "-22", // "lng": "24", // "fullName": "BOTSWANA" // }, // "WS": { // "lat": "-13.5833", // "lng": "-172.3333", // "fullName": "SAMOA" // }, // "BR": { // "lat": "-10", // "lng": "-55", // "fullName": "BRAZIL" // }, // "BS": { // "lat": "24.25", // "lng": "-76", // "fullName": "BAHAMAS" // }, // "JE": { // "lat": "49.21", // "lng": "-2.13", // "fullName": "JERSEY" // }, // "BY": { // "lat": "53", // "lng": "28", // "fullName": "BELARUS" // }, // "BZ": { // "lat": "17.25", // "lng": "-88.75", // "fullName": "BELIZE" // }, // "RU": { // "lat": "60", // "lng": "100", // "fullName": "RUSSIAN FEDERATION" // }, // "RW": { // "lat": "-2", // "lng": "30", // "fullName": "RWANDA" // }, // "RS": { // "lat": "44", // "lng": "21", // "fullName": "SERBIA" // }, // "TL": { // "lat": "-8.55", // "lng": "125.5167", // "fullName": "TIMOR-LESTE" // }, // "RE": { // "lat": "-21.1", // "lng": "55.6", // "fullName": "RÉUNION" // }, // "TM": { // "lat": "40", // "lng": "60", // "fullName": "TURKMENISTAN" // }, // "TJ": { // "lat": "39", // "lng": "71", // "fullName": "TAJIKISTAN" // }, // "RO": { // "lat": "46", // "lng": "25", // "fullName": "ROMANIA" // }, // "TK": { // "lat": "-9", // "lng": "-172", // "fullName": "TOKELAU" // }, // "GW": { // "lat": "12", // "lng": "-15", // "fullName": "GUINEA-BISSAU" // }, // "GU": { // "lat": "13.4667", // "lng": "144.7833", // "fullName": "GUAM" // }, // "GT": { // "lat": "15.5", // "lng": "-90.25", // "fullName": "GUATEMALA" // }, // "GS": { // "lat": "-54.5", // "lng": "-37", // "fullName": "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS" // }, // "GR": { // "lat": "39", // "lng": "22", // "fullName": "GREECE" // }, // "GQ": { // "lat": "2", // "lng": "10", // "fullName": "EQUATORIAL GUINEA" // }, // "GP": { // "lat": "16.25", // "lng": "-61.5833", // "fullName": "GUADELOUPE" // }, // "JP": { // "lat": "36", // "lng": "138", // "fullName": "JAPAN" // }, // "GY": { // "lat": "5", // "lng": "-59", // "fullName": "GUYANA" // }, // "GG": { // "lat": "49.5", // "lng": "-2.56", // "fullName": "GUERNSEY" // }, // "GF": { // "lat": "4", // "lng": "-53", // "fullName": "FRENCH GUIANA" // }, // "GE": { // "lat": "42", // "lng": "43.5", // "fullName": "GEORGIA" // }, // "GD": { // "lat": "12.1167", // "lng": "-61.6667", // "fullName": "GRENADA" // }, // "GB": { // "lat": "54", // "lng": "-2", // "fullName": "UNITED KINGDOM" // }, // "GA": { // "lat": "-1", // "lng": "11.75", // "fullName": "GABON" // }, // "GN": { // "lat": "11", // "lng": "-10", // "fullName": "GUINEA" // }, // "GM": { // "lat": "13.4667", // "lng": "-16.5667", // "fullName": "GAMBIA" // }, // "GL": { // "lat": "72", // "lng": "-40", // "fullName": "GREENLAND" // }, // "GI": { // "lat": "36.1833", // "lng": "-5.3667", // "fullName": "GIBRALTAR" // }, // "GH": { // "lat": "8", // "lng": "-2", // "fullName": "GHANA" // }, // "OM": { // "lat": "21", // "lng": "57", // "fullName": "OMAN" // }, // "TN": { // "lat": "34", // "lng": "9", // "fullName": "TUNISIA" // }, // "JO": { // "lat": "31", // "lng": "36", // "fullName": "JORDAN" // }, // "HR": { // "lat": "45.1667", // "lng": "15.5", // "fullName": "CROATIA" // }, // "HT": { // "lat": "19", // "lng": "-72.4167", // "fullName": "HAITI" // }, // "HU": { // "lat": "47", // "lng": "20", // "fullName": "HUNGARY" // }, // "HK": { // "lat": "22.25", // "lng": "114.1667", // "fullName": "HONG KONG" // }, // "HN": { // "lat": "15", // "lng": "-86.5", // "fullName": "HONDURAS" // }, // "HM": { // "lat": "-53.1", // "lng": "72.5167", // "fullName": "HEARD ISLAND AND MCDONALD ISLANDS" // }, // "VE": { // "lat": "8", // "lng": "-66", // "fullName": "VENEZUELA, BOLIVARIAN REPUBLIC OF" // }, // "PR": { // "lat": "18.25", // "lng": "-66.5", // "fullName": "PUERTO RICO" // }, // "PS": { // "lat": "32", // "lng": "35.25", // "fullName": "PALESTINIAN TERRITORY, OCCUPIED" // }, // "PW": { // "lat": "7.5", // "lng": "134.5", // "fullName": "PALAU" // }, // "PT": { // "lat": "39.5", // "lng": "-8", // "fullName": "PORTUGAL" // }, // "KN": { // "lat": "17.3333", // "lng": "-62.75", // "fullName": "SAINT KITTS AND NEVIS" // }, // "PY": { // "lat": "-23", // "lng": "-58", // "fullName": "PARAGUAY" // }, // "IQ": { // "lat": "33", // "lng": "44", // "fullName": "IRAQ" // }, // "PA": { // "lat": "9", // "lng": "-80", // "fullName": "PANAMA" // }, // "PF": { // "lat": "-15", // "lng": "-140", // "fullName": "FRENCH POLYNESIA" // }, // "PG": { // "lat": "-6", // "lng": "147", // "fullName": "PAPUA NEW GUINEA" // }, // "PE": { // "lat": "-10", // "lng": "-76", // "fullName": "PERU" // }, // "PK": { // "lat": "30", // "lng": "70", // "fullName": "PAKISTAN" // }, // "PH": { // "lat": "13", // "lng": "122", // "fullName": "PHILIPPINES" // }, // "PN": { // "lat": "-24.7", // "lng": "-127.4", // "fullName": "PITCAIRN" // }, // "PL": { // "lat": "52", // "lng": "20", // "fullName": "POLAND" // }, // "PM": { // "lat": "46.8333", // "lng": "-56.3333", // "fullName": "SAINT PIERRE AND MIQUElng" // }, // "ZM": { // "lat": "-15", // "lng": "30", // "fullName": "ZAMBIA" // }, // "EH": { // "lat": "24.5", // "lng": "-13", // "fullName": "WESTERN SAHARA" // }, // "EE": { // "lat": "59", // "lng": "26", // "fullName": "ESTONIA" // }, // "EG": { // "lat": "27", // "lng": "30", // "fullName": "EGYPT" // }, // "ZA": { // "lat": "-29", // "lng": "24", // "fullName": "SOUTH AFRICA" // }, // "EC": { // "lat": "-2", // "lng": "-77.5", // "fullName": "ECUADOR" // }, // "IT": { // "lat": "42.8333", // "lng": "12.8333", // "fullName": "ITALY" // }, // "VN": { // "lat": "16", // "lng": "106", // "fullName": "VIET NAM" // }, // "SB": { // "lat": "-8", // "lng": "159", // "fullName": "SOLOMON ISLANDS" // }, // "ET": { // "lat": "8", // "lng": "38", // "fullName": "ETHIOPIA" // }, // "SO": { // "lat": "10", // "lng": "49", // "fullName": "SOMALIA" // }, // "ZW": { // "lat": "-20", // "lng": "30", // "fullName": "ZIMBABWE" // }, // "SA": { // "lat": "25", // "lng": "45", // "fullName": "SAUDI ARABIA" // }, // "ES": { // "lat": "40", // "lng": "-4", // "fullName": "SPAIN" // }, // "ER": { // "lat": "15", // "lng": "39", // "fullName": "ERITREA" // }, // "ME": { // "lat": "42", // "lng": "19", // "fullName": "MONTENEGRO" // }, // "MD": { // "lat": "47", // "lng": "29", // "fullName": "MOLDOVA, REPUBLIC OF" // }, // "MG": { // "lat": "-20", // "lng": "47", // "fullName": "MADAGASCAR" // }, // "MA": { // "lat": "32", // "lng": "-5", // "fullName": "MOROCCO" // }, // "MC": { // "lat": "43.7333", // "lng": "7.4", // "fullName": "MONACO" // }, // "UZ": { // "lat": "41", // "lng": "64", // "fullName": "UZBEKISTAN" // }, // "MM": { // "lat": "22", // "lng": "98", // "fullName": "MYANMAR" // }, // "ML": { // "lat": "17", // "lng": "-4", // "fullName": "MALI" // }, // "MO": { // "lat": "22.1667", // "lng": "113.55", // "fullName": "MACAO" // }, // "MN": { // "lat": "46", // "lng": "105", // "fullName": "MONGOLIA" // }, // "MH": { // "lat": "9", // "lng": "168", // "fullName": "MARSHALL ISLANDS" // }, // "MK": { // "lat": "41.8333", // "lng": "22", // "fullName": "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF" // }, // "MU": { // "lat": "-20.2833", // "lng": "57.55", // "fullName": "MAURITIUS" // }, // "MT": { // "lat": "35.8333", // "lng": "14.5833", // "fullName": "MALTA" // }, // "MW": { // "lat": "-13.5", // "lng": "34", // "fullName": "MALAWI" // }, // "MV": { // "lat": "3.25", // "lng": "73", // "fullName": "MALDIVES" // }, // "MQ": { // "lat": "14.6667", // "lng": "-61", // "fullName": "MARTINIQUE" // }, // "MP": { // "lat": "15.2", // "lng": "145.75", // "fullName": "NORTHERN MARIANA ISLANDS" // }, // "MS": { // "lat": "16.75", // "lng": "-62.2", // "fullName": "MONTSERRAT" // }, // "MR": { // "lat": "20", // "lng": "-12", // "fullName": "MAURITANIA" // }, // "IM": { // "lat": "54.23", // "lng": "-4.55", // "fullName": "ISLE OF MAN" // }, // "UG": { // "lat": "1", // "lng": "32", // "fullName": "UGANDA" // }, // "MY": { // "lat": "2.5", // "lng": "112.5", // "fullName": "MALAYSIA" // }, // "MX": { // "lat": "23", // "lng": "-102", // "fullName": "MEXICO" // }, // "IL": { // "lat": "31.5", // "lng": "34.75", // "fullName": "ISRAEL" // }, // "FR": { // "lat": "46", // "lng": "2", // "fullName": "FRANCE" // }, // "AW": { // "lat": "12.5", // "lng": "-69.9667", // "fullName": "ARUBA" // }, // "SH": { // "lat": "-15.9333", // "lng": "-5.7", // "fullName": "SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA" // }, // "SJ": { // "lat": "78", // "lng": "20", // "fullName": "SVALBARD AND JAN MAYEN" // }, // "FI": { // "lat": "64", // "lng": "26", // "fullName": "FINLAND" // }, // "FJ": { // "lat": "-18", // "lng": "175", // "fullName": "FIJI" // }, // "FK": { // "lat": "-51.75", // "lng": "-59", // "fullName": "FALKLAND ISLANDS (MALVINAS)" // }, // "FM": { // "lat": "6.9167", // "lng": "158.25", // "fullName": "MICRONESIA, FEDERATED STATES OF" // }, // "FO": { // "lat": "62", // "lng": "-7", // "fullName": "FAROE ISLANDS" // }, // "NI": { // "lat": "13", // "lng": "-85", // "fullName": "NICARAGUA" // }, // "NL": { // "lat": "52.5", // "lng": "5.75", // "fullName": "NETHERLANDS" // }, // "NO": { // "lat": "62", // "lng": "10", // "fullName": "NORWAY" // }, // "NA": { // "lat": "-22", // "lng": "17", // "fullName": "NAMIBIA" // }, // "VU": { // "lat": "-16", // "lng": "167", // "fullName": "VANUATU" // }, // "NC": { // "lat": "-21.5", // "lng": "165.5", // "fullName": "NEW CALEDONIA" // }, // "NE": { // "lat": "16", // "lng": "8", // "fullName": "NIGER" // }, // "NF": { // "lat": "-29.0333", // "lng": "167.95", // "fullName": "NORFOLK ISLAND" // }, // "NG": { // "lat": "10", // "lng": "8", // "fullName": "NIGERIA" // }, // "NZ": { // "lat": "-41", // "lng": "174", // "fullName": "NEW ZEALAND" // }, // "NP": { // "lat": "28", // "lng": "84", // "fullName": "NEPAL" // }, // "NR": { // "lat": "-0.5333", // "lng": "166.9167", // "fullName": "NAURU" // }, // "NU": { // "lat": "-19.0333", // "lng": "-169.8667", // "fullName": "NIUE" // }, // "CK": { // "lat": "-21.2333", // "lng": "-159.7667", // "fullName": "COOK ISLANDS" // }, // "CI": { // "lat": "8", // "lng": "-5", // "fullName": "CÔTE D'IVOIRE" // }, // "CH": { // "lat": "47", // "lng": "8", // "fullName": "SWITZERLAND" // }, // "CO": { // "lat": "4", // "lng": "-72", // "fullName": "COLOMBIA" // }, // "CN": { // "lat": "35", // "lng": "105", // "fullName": "CHINA" // }, // "CM": { // "lat": "6", // "lng": "12", // "fullName": "CAMEROON" // }, // "CL": { // "lat": "-30", // "lng": "-71", // "fullName": "CHILE" // }, // "CC": { // "lat": "-12.5", // "lng": "96.8333", // "fullName": "COCOS (KEELING) ISLANDS" // }, // "CA": { // "lat": "60", // "lng": "-95", // "fullName": "CANADA" // }, // "CG": { // "lat": "-1", // "lng": "15", // "fullName": "CONGO" // }, // "CF": { // "lat": "7", // "lng": "21", // "fullName": "CENTRAL AFRICAN REPUBLIC" // }, // "CD": { // "lat": "0", // "lng": "25", // "fullName": "CONGO, THE DEMOCRATIC REPUBLIC OF THE" // }, // "CZ": { // "lat": "49.75", // "lng": "15.5", // "fullName": "CZECH REPUBLIC" // }, // "CY": { // "lat": "35", // "lng": "33", // "fullName": "CYPRUS" // }, // "CX": { // "lat": "-10.5", // "lng": "105.6667", // "fullName": "CHRISTMAS ISLAND" // }, // "CR": { // "lat": "10", // "lng": "-84", // "fullName": "COSTA RICA" // }, // "CV": { // "lat": "16", // "lng": "-24", // "fullName": "CAPE VERDE" // }, // "CU": { // "lat": "21.5", // "lng": "-80", // "fullName": "CUBA" // }, // "SZ": { // "lat": "-26.5", // "lng": "31.5", // "fullName": "SWAZILAND" // }, // "SY": { // "lat": "35", // "lng": "38", // "fullName": "SYRIAN ARAB REPUBLIC" // }, // "KG": { // "lat": "41", // "lng": "75", // "fullName": "KYRGYZSTAN" // }, // "KE": { // "lat": "1", // "lng": "38", // "fullName": "KENYA" // }, // "SR": { // "lat": "4", // "lng": "-56", // "fullName": "SURINAME" // }, // "KI": { // "lat": "1.4167", // "lng": "173", // "fullName": "KIRIBATI" // }, // "KH": { // "lat": "13", // "lng": "105", // "fullName": "CAMBODIA" // }, // "SV": { // "lat": "13.8333", // "lng": "-88.9167", // "fullName": "EL SALVADOR" // }, // "KM": { // "lat": "-12.1667", // "lng": "44.25", // "fullName": "COMOROS" // }, // "ST": { // "lat": "1", // "lng": "7", // "fullName": "SAO TOME AND PRINCIPE" // }, // "SK": { // "lat": "48.6667", // "lng": "19.5", // "fullName": "SLOVAKIA" // }, // "KR": { // "lat": "37", // "lng": "127.5", // "fullName": "KOREA, REPUBLIC OF" // }, // "SI": { // "lat": "46", // "lng": "15", // "fullName": "SLOVENIA" // }, // "KP": { // "lat": "40", // "lng": "127", // "fullName": "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF" // }, // "KW": { // "lat": "29.3375", // "lng": "47.6581", // "fullName": "KUWAIT" // }, // "SN": { // "lat": "14", // "lng": "-14", // "fullName": "SENEGAL" // }, // "SM": { // "lat": "43.7667", // "lng": "12.4167", // "fullName": "SAN MARINO" // }, // "SL": { // "lat": "8.5", // "lng": "-11.5", // "fullName": "SIERRA LEONE" // }, // "SC": { // "lat": "-4.5833", // "lng": "55.6667", // "fullName": "SEYCHELLES" // }, // "KZ": { // "lat": "48", // "lng": "68", // "fullName": "KAZAKHSTAN" // }, // "KY": { // "lat": "19.5", // "lng": "-80.5", // "fullName": "CAYMAN ISLANDS" // }, // "SG": { // "lat": "1.3667", // "lng": "103.8", // "fullName": "SINGAPORE" // }, // "SE": { // "lat": "62", // "lng": "15", // "fullName": "SWEDEN" // }, // "SD": { // "lat": "15", // "lng": "30", // "fullName": "SUDAN" // }, // "DO": { // "lat": "19", // "lng": "-70.6667", // "fullName": "DOMINICAN REPUBLIC" // }, // "DM": { // "lat": "15.4167", // "lng": "-61.3333", // "fullName": "DOMINICA" // }, // "DJ": { // "lat": "11.5", // "lng": "43", // "fullName": "DJIBOUTI" // }, // "DK": { // "lat": "56", // "lng": "10", // "fullName": "DENMARK" // }, // "VG": { // "lat": "18.5", // "lng": "-64.5", // "fullName": "VIRGIN ISLANDS, BRITISH" // }, // "DE": { // "lat": "51", // "lng": "9", // "fullName": "GERMANY" // }, // "YE": { // "lat": "15", // "lng": "48", // "fullName": "YEMEN" // }, // "DZ": { // "lat": "28", // "lng": "3", // "fullName": "ALGERIA" // }, // "US": { // "lat": "38", // "lng": "-97", // "fullName": "UNITED STATES" // }, // "US1": { // "lat": "45", // "lng": "-108", // "fullName": "UNITED STATES 1" // }, // "US2": { // "lat": "36", // "lng": "-102", // "fullName": "UNITED STATES 2" // }, // "UY": { // "lat": "-33", // "lng": "-56", // "fullName": "URUGUAY" // }, // "YT": { // "lat": "-12.8333", // "lng": "45.1667", // "fullName": "MAYOTTE" // }, // "UM": { // "lat": "19.2833", // "lng": "166.6", // "fullName": "UNITED STATES MINOR OUTLYING ISLANDS" // }, // "LB": { // "lat": "33.8333", // "lng": "35.8333", // "fullName": "LEBANON" // }, // "LC": { // "lat": "13.8833", // "lng": "-61.1333", // "fullName": "SAINT LUCIA" // }, // "LA": { // "lat": "18", // "lng": "105", // "fullName": "LAO PEOPLE'S DEMOCRATIC REPUBLIC" // }, // "TV": { // "lat": "-8", // "lng": "178", // "fullName": "TUVALU" // }, // "TT": { // "lat": "11", // "lng": "-61", // "fullName": "TRINIDAD AND TOBAGO" // }, // "TR": { // "lat": "39", // "lng": "35", // "fullName": "TURKEY" // }, // "LK": { // "lat": "7", // "lng": "81", // "fullName": "SRI LANKA" // }, // "LI": { // "lat": "47.1667", // "lng": "9.5333", // "fullName": "LIECHTENSTEIN" // }, // "LV": { // "lat": "57", // "lng": "25", // "fullName": "LATVIA" // }, // "TO": { // "lat": "-20", // "lng": "-175", // "fullName": "TONGA" // }, // "LT": { // "lat": "56", // "lng": "24", // "fullName": "LITHUANIA" // }, // "LU": { // "lat": "49.75", // "lng": "6.1667", // "fullName": "LUXEMBOURG" // }, // "LR": { // "lat": "6.5", // "lng": "-9.5", // "fullName": "LIBERIA" // }, // "LS": { // "lat": "-29.5", // "lng": "28.5", // "fullName": "LESOTHO" // }, // "TH": { // "lat": "15", // "lng": "100", // "fullName": "THAILAND" // }, // "TF": { // "lat": "-43", // "lng": "67", // "fullName": "FRENCH SOUTHERN TERRITORIES" // }, // "TG": { // "lat": "8", // "lng": "1.1667", // "fullName": "TOGO" // }, // "TD": { // "lat": "15", // "lng": "19", // "fullName": "CHAD" // }, // "TC": { // "lat": "21.75", // "lng": "-71.5833", // "fullName": "TURKS AND CAICOS ISLANDS" // }, // "LY": { // "lat": "25", // "lng": "17", // "fullName": "LIBYA" // }, // "VA": { // "lat": "41.9", // "lng": "12.45", // "fullName": "HOLY SEE (VATICAN CITY STATE)" // }, // "VC": { // "lat": "13.25", // "lng": "-61.2", // "fullName": "SAINT VINCENT AND THE GRENADINES" // }, // "AE": { // "lat": "24", // "lng": "54", // "fullName": "UNITED ARAB EMIRATES" // }, // "AD": { // "lat": "42.5", // "lng": "1.6", // "fullName": "ANDORRA" // }, // "AG": { // "lat": "17.05", // "lng": "-61.8", // "fullName": "ANTIGUA AND BARBUDA" // }, // "AF": { // "lat": "33", // "lng": "65", // "fullName": "AFGHANISTAN" // }, // "AI": { // "lat": "18.25", // "lng": "-63.1667", // "fullName": "ANGUILLA" // }, // "VI": { // "lat": "18.3333", // "lng": "-64.8333", // "fullName": "VIRGIN ISLANDS, U.S." // }, // "IS": { // "lat": "65", // "lng": "-18", // "fullName": "ICELAND" // }, // "IR": { // "lat": "32", // "lng": "53", // "fullName": "IRAN, ISLAMIC REPUBLIC OF" // }, // "AM": { // "lat": "40", // "lng": "45", // "fullName": "ARMENIA" // }, // "AL": { // "lat": "41", // "lng": "20", // "fullName": "ALBANIA" // }, // "AO": { // "lat": "-12.5", // "lng": "18.5", // "fullName": "ANGOLA" // }, // "AN": { // "lat": "12.25", // "lng": "-68.75", // "fullName": "Netherlands Antilles" // }, // "AQ": { // "lat": "-90", // "lng": "0", // "fullName": "ANTARCTICA" // }, // "AS": { // "lat": "-14.3333", // "lng": "-170", // "fullName": "AMERICAN SAMOA" // }, // "AR": { // "lat": "-34", // "lng": "-64", // "fullName": "ARGENTINA" // }, // "AU": { // "lat": "-27", // "lng": "133", // "fullName": "AUSTRALIA" // }, // "AT": { // "lat": "47.3333", // "lng": "13.3333", // "fullName": "AUSTRIA" // }, // "IO": { // "lat": "-6", // "lng": "71.5", // "fullName": "BRITISH INDIAN OCEAN TERRITORY" // }, // "IN": { // "lat": "20", // "lng": "77", // "fullName": "INDIA" // }, // "TZ": { // "lat": "-6", // "lng": "35", // "fullName": "TANZANIA, UNITED REPUBLIC OF" // }, // "AZ": { // "lat": "40.5", // "lng": "47.5", // "fullName": "AZERBAIJAN" // }, // "IE": { // "lat": "53", // "lng": "-8", // "fullName": "IRELAND" // }, // "ID": { // "lat": "-5", // "lng": "120", // "fullName": "INDONESIA" // }, // "UA": { // "lat": "49", // "lng": "32", // "fullName": "UKRAINE" // }, // "QA": { // "lat": "25.5", // "lng": "51.25", // "fullName": "QATAR" // }, // "MZ": { // "lat": "-18.25", // "lng": "35", // "fullName": "MOZAMBIQUE" // }, // }
the_stack
'use strict'; import { request as http_request, ClientRequest, IncomingMessage } from 'http'; import { request as https_request, RequestOptions } from 'https'; import { Message, X509 } from 'azure-iot-common'; import dbg = require('debug'); const debug = dbg('azure-iot-http-base.Http'); /** * @private */ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** * @private */ export type HttpCallback = (err: Error, body?: string, response?: IncomingMessage) => void; /** * @private * * This interface defines optional HTTP request options that one can set on a per request basis. */ export interface HttpRequestOptions { /** * The TCP port to use when connecting to the HTTP server. Defaults to 80 for HTTP * traffic and 443 for HTTPS traffic. */ port?: number; /** * The request function to use when connecting to the HTTP server. Must be the 'request' * function from either the 'http' Node.js package or the 'https' Node.js package. */ request?: (options: RequestOptions | string, callback?: (res: IncomingMessage) => void) => ClientRequest; } /** * @private * @class module:azure-iot-http-base.Http * @classdesc Basic HTTP request/response functionality used by higher-level IoT Hub libraries. * You generally want to use these higher-level objects (such as [azure-iot-device-http.Http]{@link module:azure-iot-device-http.Http}) rather than this one. */ export class Http { private _options: any; /** * @method module:azure-iot-http-base.Http.buildRequest * @description Builds an HTTP request object using the parameters supplied by the caller. * * @param {String} method The HTTP verb to use (GET, POST, PUT, DELETE...). * @param {String} path The section of the URI that should be appended after the hostname. * @param {Object} httpHeaders An object containing the headers that should be used for the request. * @param {String} host Fully-Qualified Domain Name of the server to which the request should be sent to. * @param {Object} options X509 options or HTTP request options * @param {Function} done The callback to call when a response or an error is received. * * @returns An HTTP request object. */ /*Codes_SRS_NODE_HTTP_05_001: [buildRequest shall accept the following arguments: method - an HTTP verb, e.g., 'GET', 'POST', 'DELETE' path - the path to the resource, not including the hostname httpHeaders - an object whose properties represent the names and values of HTTP headers to include in the request host - the fully-qualified DNS hostname of the IoT hub options - [optional] the x509 certificate options or HTTP request options done - a callback that will be invoked when a completed response is returned from the server]*/ buildRequest (method: HttpMethod, path: string, httpHeaders: { [key: string]: string | string[] | number }, host: string | { socketPath: string }, options: X509 | HttpRequestOptions | HttpCallback, done?: HttpCallback): ClientRequest { // NOTE: The `options` parameter above, the way its structured prevents // this function from being called with *both* X509 options AND // HttpRequestOptions simultaneously. This is not strictly required at // this time. But when it is required, we may need to split the request // options out as its own parameter and then appropriately modify the // overload detection logic below. if (!done && (typeof options === 'function')) { done = options; options = undefined; } let requestOptions: HttpRequestOptions = null; if (options && this.isHttpRequestOptions(options)) { requestOptions = options as HttpRequestOptions; options = undefined; } let x509Options: X509 = null; if (options && this.isX509Options(options)) { x509Options = options as X509; options = undefined; } let httpOptions: RequestOptions = { path: path, method: method, headers: httpHeaders }; // Codes_SRS_NODE_HTTP_13_004: [ Use the request object from the `options` object if one has been provided or default to HTTPS request. ] let request = https_request; if (requestOptions && requestOptions.request) { request = requestOptions.request as any; } if (typeof(host) === 'string') { // Codes_SRS_NODE_HTTP_13_002: [ If the host argument is a string then assign its value to the host property of httpOptions. ] httpOptions.host = host; // Codes_SRS_NODE_HTTP_13_006: [ If the options object has a port property set then assign that to the port property on httpOptions. ] if (requestOptions && requestOptions.port) { httpOptions.port = requestOptions.port; } } else { // Codes_SRS_NODE_HTTP_13_003: [ If the host argument is an object then assign its socketPath property to the socketPath property of httpOptions. ] // this is a unix domain socket so use `socketPath` property in options // instead of `host` httpOptions.socketPath = host.socketPath; // Codes_SRS_NODE_HTTP_13_005: [ Use the request object from the http module when dealing with unix domain socket based HTTP requests. ] // unix domain sockets only work with the HTTP request function; https's // request function cannot handle UDS request = http_request; } /*Codes_SRS_NODE_HTTP_18_001: [ If the `options` object passed into `setOptions` has a value in `http.agent`, that value shall be passed into the `request` function as `httpOptions.agent` ]*/ if (this._options && this._options.http && this._options.http.agent) { httpOptions.agent = this._options.http.agent; } /*Codes_SRS_NODE_HTTP_16_001: [If `options` has x509 properties, the certificate, key and passphrase in the structure shall be used to authenticate the connection.]*/ if (x509Options) { httpOptions.cert = (x509Options as X509).cert; httpOptions.key = (x509Options as X509).key; httpOptions.passphrase = (x509Options as X509).passphrase; httpOptions.clientCertEngine = (x509Options as X509).clientCertEngine; } if (this._options && this._options.ca) { httpOptions.ca = this._options.ca; } let httpReq = request(httpOptions, (response: IncomingMessage): void => { let responseBody = ''; response.on('error', (err: Error): void => { done(err); }); response.on('data', (chunk: string | Buffer): void => { responseBody += chunk; }); response.on('end', (): void => { /*Codes_SRS_NODE_HTTP_05_005: [When an HTTP response is received, the callback function indicated by the done argument shall be invoked with the following arguments: err - the standard JavaScript Error object if status code >= 300, otherwise null body - the body of the HTTP response as a string response - the Node.js http.IncomingMessage object returned by the transport]*/ let err = (response.statusCode >= 300) ? new Error(response.statusMessage) : null; done(err, responseBody, response); }); }); /*Codes_SRS_NODE_HTTP_05_003: [If buildRequest encounters an error before it can send the request, it shall invoke the done callback function and pass the standard JavaScript Error object with a text description of the error (err.message).]*/ httpReq.on('error', done); /*Codes_SRS_NODE_HTTP_05_002: [buildRequest shall return a Node.js https.ClientRequest/http.ClientRequest object, upon which the caller must invoke the end method in order to actually send the request.]*/ return httpReq; } /** * @method module:azure-iot-http-base.Http.toMessage * @description Transforms the body of an HTTP response into a {@link module:azure-iot-common.Message} that can be treated by the client. * * @param {module:http.IncomingMessage} response A response as returned from the node.js http module * @param {Object} body The section of the URI that should be appended after the hostname. * * @returns {module:azure-iot-common.Message} A Message object. */ toMessage (response: IncomingMessage, body: Message.BufferConvertible): Message { let msg: Message; /*Codes_SRS_NODE_HTTP_05_006: [If the status code of the HTTP response < 300, toMessage shall create a new azure-iot-common.Message object with data equal to the body of the HTTP response.]*/ if (response.statusCode < 300) { msg = new Message(body); for (let item in response.headers) { if (item.search('iothub-') !== -1) { if (item.toLowerCase() === 'iothub-messageid') { /*Codes_SRS_NODE_HTTP_05_007: [If the HTTP response has an 'iothub-messageid' header, it shall be saved as the messageId property on the created Message.]*/ msg.messageId = response.headers[item] as any; } else if (item.toLowerCase() === 'iothub-to') { /*Codes_SRS_NODE_HTTP_05_008: [If the HTTP response has an 'iothub-to' header, it shall be saved as the to property on the created Message.]*/ msg.to = response.headers[item] as any; } else if (item.toLowerCase() === 'iothub-expiry') { /*Codes_SRS_NODE_HTTP_05_009: [If the HTTP response has an 'iothub-expiry' header, it shall be saved as the expiryTimeUtc property on the created Message.]*/ msg.expiryTimeUtc = response.headers[item] as any; } else if (item.toLowerCase() === 'iothub-correlationid') { /*Codes_SRS_NODE_HTTP_05_010: [If the HTTP response has an 'iothub-correlationid' header, it shall be saved as the correlationId property on the created Message.]*/ msg.correlationId = response.headers[item] as any; } else if (item.search('iothub-app-') !== -1) { /*Codes_SRS_NODE_HTTP_13_001: [ If the HTTP response has a header with the prefix iothub-app- then a new property with the header name and value as the key and value shall be added to the message. ]*/ msg.properties.add(item, response.headers[item] as string); } } else if (item.toLowerCase() === 'etag') { /*Codes_SRS_NODE_HTTP_05_011: [If the HTTP response has an 'etag' header, it shall be saved as the lockToken property on the created Message, minus any surrounding quotes.]*/ // Need to strip the quotes from the string const len = response.headers[item].length; msg.lockToken = (response.headers[item] as string).substring(1, len - 1); } } } return msg; } /** * @private */ setOptions(options: any): void { this._options = options; } /** * @private */ isX509Options(options: any): boolean { return !!options && typeof(options) === 'object' && (options.cert || options.key || options.passphrase || options.certFile || options.keyFile || options.clientCertEngine); } /** * @private */ isHttpRequestOptions(options: any): boolean { return !!options && typeof(options) === 'object' && (typeof(options.port) === 'number' || typeof(options.request) === 'function'); } /** * @method module:azure-iot-http-base.Http#parseErrorBody * @description Parses the body of an error response and returns it as an object. * * @params {String} body The body of the HTTP error response * @returns {Object} An object with 2 properties: code and message. */ static parseErrorBody (body: string): { code: string, message: string } { let result = null; try { const jsonErr = JSON.parse(body); const errParts = jsonErr.Message.split(';'); const errMessage = errParts[1]; const errCode = errParts[0].split(':')[1]; if (!!errCode && !!errMessage) { result = { message: errMessage, code: errCode }; } } catch (err) { if (err instanceof SyntaxError) { debug('Could not parse error body: Invalid JSON'); } else if (err instanceof TypeError) { debug('Could not parse error body: Unknown body format'); } else { throw err; } } return result; } }
the_stack
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { OrgsAPIClientInterface } from './orgs-api-client.interface'; import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from '../../types'; import * as models from '../../models'; export const USE_DOMAIN = new InjectionToken<string>('OrgsAPIClient_USE_DOMAIN'); export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('OrgsAPIClient_USE_HTTP_OPTIONS'); type APIHttpOptions = HttpOptions & { headers: HttpHeaders; params: HttpParams; }; @Injectable() export class OrgsAPIClient implements OrgsAPIClientInterface { readonly options: APIHttpOptions; readonly domain: string = `https://api.github.com`; constructor( private readonly http: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { if (domain != null) { this.domain = domain; } this.options = { headers: new HttpHeaders(options && options.headers ? options.headers : {}), params: new HttpParams(options && options.params ? options.params : {}), ...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}), ...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {}) }; } /** * Get an Organization. * Response generated for [ 200 ] HTTP response code. */ getOrgsOrg( args: Exclude<OrgsAPIClientInterface['getOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Organization>; getOrgsOrg( args: Exclude<OrgsAPIClientInterface['getOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Organization>>; getOrgsOrg( args: Exclude<OrgsAPIClientInterface['getOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Organization>>; getOrgsOrg( args: Exclude<OrgsAPIClientInterface['getOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Organization | HttpResponse<models.Organization> | HttpEvent<models.Organization>> { const path = `/orgs/${args.org}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Organization>(`${this.domain}${path}`, options); } /** * Edit an Organization. * Response generated for [ 200 ] HTTP response code. */ patchOrgsOrg( args: Exclude<OrgsAPIClientInterface['patchOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Organization>; patchOrgsOrg( args: Exclude<OrgsAPIClientInterface['patchOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Organization>>; patchOrgsOrg( args: Exclude<OrgsAPIClientInterface['patchOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Organization>>; patchOrgsOrg( args: Exclude<OrgsAPIClientInterface['patchOrgsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Organization | HttpResponse<models.Organization> | HttpEvent<models.Organization>> { const path = `/orgs/${args.org}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.patch<models.Organization>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * List public events for an organization. * Response generated for [ 200 ] HTTP response code. */ getOrgsOrgEvents( args: Exclude<OrgsAPIClientInterface['getOrgsOrgEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Events>; getOrgsOrgEvents( args: Exclude<OrgsAPIClientInterface['getOrgsOrgEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Events>>; getOrgsOrgEvents( args: Exclude<OrgsAPIClientInterface['getOrgsOrgEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Events>>; getOrgsOrgEvents( args: Exclude<OrgsAPIClientInterface['getOrgsOrgEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Events | HttpResponse<models.Events> | HttpEvent<models.Events>> { const path = `/orgs/${args.org}/events`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Events>(`${this.domain}${path}`, options); } /** * List issues. * List all issues for a given organization for the authenticated user. * * Response generated for [ 200 ] HTTP response code. */ getOrgsOrgIssues( args: Exclude<OrgsAPIClientInterface['getOrgsOrgIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Issues>; getOrgsOrgIssues( args: Exclude<OrgsAPIClientInterface['getOrgsOrgIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Issues>>; getOrgsOrgIssues( args: Exclude<OrgsAPIClientInterface['getOrgsOrgIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Issues>>; getOrgsOrgIssues( args: Exclude<OrgsAPIClientInterface['getOrgsOrgIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Issues | HttpResponse<models.Issues> | HttpEvent<models.Issues>> { const path = `/orgs/${args.org}/issues`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('filter' in args) { options.params = options.params.set('filter', String(args.filter)); } if ('state' in args) { options.params = options.params.set('state', String(args.state)); } if ('labels' in args) { options.params = options.params.set('labels', String(args.labels)); } if ('sort' in args) { options.params = options.params.set('sort', String(args.sort)); } if ('direction' in args) { options.params = options.params.set('direction', String(args.direction)); } if ('since' in args) { options.params = options.params.set('since', String(args.since)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Issues>(`${this.domain}${path}`, options); } /** * Members list. * List all users who are members of an organization. A member is a user tha * belongs to at least 1 team in the organization. If the authenticated user * is also an owner of this organization then both concealed and public members * will be returned. If the requester is not an owner of the organization the * query will be redirected to the public members list. * * Response generated for [ 200 ] HTTP response code. */ getOrgsOrgMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getOrgsOrgMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getOrgsOrgMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getOrgsOrgMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/orgs/${args.org}/members`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * Remove a member. * Removing a user from this list will remove them from all teams and they * will no longer have any access to the organization's repositories. * * Response generated for [ 204 ] HTTP response code. */ deleteOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/orgs/${args.org}/members/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Check if a user is, publicly or privately, a member of the organization. * Response generated for [ 204 ] HTTP response code. */ getOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getOrgsOrgMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/orgs/${args.org}/members/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * Public members list. * Members of an organization can choose to have their membership publicized * or not. * * Response generated for [ 200 ] HTTP response code. */ getOrgsOrgPublicMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getOrgsOrgPublicMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getOrgsOrgPublicMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getOrgsOrgPublicMembers( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/orgs/${args.org}/public_members`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * Conceal a user's membership. * Response generated for [ 204 ] HTTP response code. */ deleteOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['deleteOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/orgs/${args.org}/public_members/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Check public membership. * Response generated for [ 204 ] HTTP response code. */ getOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['getOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/orgs/${args.org}/public_members/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * Publicize a user's membership. * Response generated for [ 204 ] HTTP response code. */ putOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['putOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['putOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['putOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; putOrgsOrgPublicMembersUsername( args: Exclude<OrgsAPIClientInterface['putOrgsOrgPublicMembersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/orgs/${args.org}/public_members/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.put<void>(`${this.domain}${path}`, null, options); } /** * List repositories for the specified org. * Response generated for [ 200 ] HTTP response code. */ getOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['getOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repos>; getOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['getOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repos>>; getOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['getOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repos>>; getOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['getOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> { const path = `/orgs/${args.org}/repos`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('type' in args) { options.params = options.params.set('type', String(args.type)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Repos>(`${this.domain}${path}`, options); } /** * Create a new repository for the authenticated user. OAuth users must supply * repo scope. * * Response generated for [ 201 ] HTTP response code. */ postOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['postOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repos>; postOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['postOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repos>>; postOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['postOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repos>>; postOrgsOrgRepos( args: Exclude<OrgsAPIClientInterface['postOrgsOrgReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> { const path = `/orgs/${args.org}/repos`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.post<models.Repos>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * List teams. * Response generated for [ 200 ] HTTP response code. */ getOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['getOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Teams>; getOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['getOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Teams>>; getOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['getOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Teams>>; getOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['getOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Teams | HttpResponse<models.Teams> | HttpEvent<models.Teams>> { const path = `/orgs/${args.org}/teams`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Teams>(`${this.domain}${path}`, options); } /** * Create team. * In order to create a team, the authenticated user must be an owner of organization. * * Response generated for [ 201 ] HTTP response code. */ postOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['postOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Team>; postOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['postOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Team>>; postOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['postOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Team>>; postOrgsOrgTeams( args: Exclude<OrgsAPIClientInterface['postOrgsOrgTeamsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Team | HttpResponse<models.Team> | HttpEvent<models.Team>> { const path = `/orgs/${args.org}/teams`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.post<models.Team>(`${this.domain}${path}`, JSON.stringify(args.body), options); } }
the_stack
import { EventBase } from "../events/EventBase"; import { assertNever, isArray, isDefined, isFunction, isNullOrUndefined } from "../typeChecks"; import type { WorkerClientMessages, WorkerClientMethodCallMessage, WorkerClientPropertySetMessage, WorkerServerErrorMessage, WorkerServerEventMessage, WorkerServerMessages, WorkerServerProgressMessage, WorkerServerPropertyChangedMessage, WorkerServerPropertyInitializedMessage, WorkerServerReturnMessage } from "./WorkerMessages"; import { GET_PROPERTY_VALUES_METHOD, WorkerClientMessageType, WorkerServerMessageType } from "./WorkerMessages"; type workerServerMethod = (taskID: number, ...params: any[]) => Promise<void>; type createTransferableCallback<T> = (returnValue: T) => Transferable[]; export class WorkerServer { private methods = new Map<string, workerServerMethod>(); private properties = new Map<string, PropertyDescriptor>(); /** * Creates a new worker thread method call listener. * @param self - the worker scope in which to listen. */ constructor(private self: DedicatedWorkerGlobalScope) { this.addMethodInternal(GET_PROPERTY_VALUES_METHOD, () => { for (const [name, prop] of this.properties) { this.onPropertyInitialized(name, prop.get()); } return Promise.resolve(); }); this.self.onmessage = (evt: MessageEvent<WorkerClientMessages>): void => { const data = evt.data; switch (data.type) { case WorkerClientMessageType.PropertySet: this.setProperty(data); break; case WorkerClientMessageType.MethodCall: this.callMethod(data); break; default: assertNever(data); } }; } private setProperty(data: WorkerClientPropertySetMessage) { const prop = this.properties.get(data.propertyName); if (prop) { try { prop.set(data.value); } catch (exp) { this.onError(data.taskID, `property invocation error: ${data.propertyName}(${exp.message})`); } } else { this.onError(data.taskID, "property not found: " + data.propertyName); } } private callMethod(data: WorkerClientMethodCallMessage) { const method = this.methods.get(data.methodName); if (method) { try { if (isArray(data.params)) { method(data.taskID, ...data.params); } else if (isDefined(data.params)) { method(data.taskID, data.params); } else { method(data.taskID); } } catch (exp) { this.onError(data.taskID, `method invocation error: ${data.methodName}(${exp.message})`); } } else { this.onError(data.taskID, "method not found: " + data.methodName); } } private postMessage(message: WorkerServerMessages, transferables?: Transferable[]): void { if (isDefined(transferables)) { this.self.postMessage(message, transferables); } else { this.self.postMessage(message); } } /** * Report an error back to the calling thread. * @param taskID - the invocation ID of the method that errored. * @param errorMessage - what happened? */ private onError(taskID: number, errorMessage: string): void { const message: WorkerServerErrorMessage = { type: WorkerServerMessageType.Error, taskID, errorMessage }; this.postMessage(message); } /** * Report progress through long-running invocations. If your invocable * functions don't report progress, this can be safely ignored. * @param taskID - the invocation ID of the method that is updating. * @param soFar - how much of the process we've gone through. * @param total - the total amount we need to go through. * @param msg - an optional message to include as part of the progress update. */ private onProgress(taskID: number, soFar: number, total: number, msg?: string): void { const message: WorkerServerProgressMessage = { type: WorkerServerMessageType.Progress, taskID, soFar, total, msg }; this.postMessage(message); } /** * Return back to the client. * @param taskID - the invocation ID of the method that is returning. * @param returnValue - the (optional) value to return. * @param transferReturnValue - a mapping function to extract any Transferable objects from the return value. */ private onReturn<T>(taskID: number, returnValue: T, transferReturnValue: createTransferableCallback<T>): void { let message: WorkerServerReturnMessage = null; if (returnValue === undefined) { message = { type: WorkerServerMessageType.Return, taskID }; } else { message = { type: WorkerServerMessageType.Return, taskID, returnValue }; } if (isDefined(transferReturnValue)) { const transferables = transferReturnValue(returnValue); this.postMessage(message, transferables); } else { this.postMessage(message); } } private onEvent<T>(eventName: string, evt: Event, makePayload?: (evt: Event) => T, transferReturnValue?: createTransferableCallback<T>): void { let message: WorkerServerEventMessage = null; if (isDefined(makePayload)) { message = { type: WorkerServerMessageType.Event, eventName, data: makePayload(evt) }; } else { message = { type: WorkerServerMessageType.Event, eventName }; } if (message.data !== undefined && isDefined(transferReturnValue)) { const transferables = transferReturnValue(message.data); this.postMessage(message, transferables); } else { this.postMessage(message); } } private onPropertyInitialized(propertyName: string, value: any): void { const message: WorkerServerPropertyInitializedMessage = { type: WorkerServerMessageType.PropertyInit, propertyName, value }; this.postMessage(message); } private onPropertyChanged(propertyName: string, value: any): void { const message: WorkerServerPropertyChangedMessage = { type: WorkerServerMessageType.Property, propertyName, value }; this.postMessage(message); } private addMethodInternal<T>(methodName: string, asyncFunc: Function, transferReturnValue?: createTransferableCallback<T>) { if (this.methods.has(methodName)) { throw new Error(`${methodName} method has already been mapped.`); } this.methods.set(methodName, async (taskID: number, ...params: any[]) => { const onProgress = this.onProgress.bind(this, taskID); try { // Even functions returning void and functions returning bare, unPromised values, can be awaited. // This creates a convenient fallback where we don't have to consider the exact return type of the function. const returnValue = await asyncFunc(...params, onProgress); this.onReturn(taskID, returnValue, transferReturnValue); } catch (exp) { console.error(exp); this.onError(taskID, exp.message); } }); } addProperty(obj: any, name: string): void { if (this.properties.has(name)) { throw new Error(`${name} property has already been mapped.`); } let prop = Object.getOwnPropertyDescriptor(obj, name); if (isNullOrUndefined(prop)) { const proto = Object.getPrototypeOf(obj); const protoProp = Object.getOwnPropertyDescriptor(proto, name); prop = { get: protoProp.get.bind(obj), set: protoProp.set.bind(obj) }; } this.properties.set(name, prop); Object.defineProperty(obj, name, { get: prop.get.bind(prop), set: (v: string) => { prop.set(v); this.onPropertyChanged(name, v); } }); } /** * Registers a function call for cross-thread invocation. * @param methodName - the name of the method to use during invocations. * @param obj - the object on which to find the method. */ addMethod<T>(methodName: string, obj: any): void; /** * Registers a function call for cross-thread invocation. * @param methodName - the name of the method to use during invocations. * @param obj - the object on which to find the method. * @param transferReturnValue - an (optional) function that reports on which values in the `returnValue` should be transfered instead of copied. */ addMethod<T>(methodName: string, obj: any, transferReturnValue: createTransferableCallback<T>): void; /** * Registers a function call for cross-thread invocation. * @param methodName - the name of the method to use during invocations. * @param asyncFuncOrObject - the function to execute when the method is invoked. */ addMethod<T>(methodName: string, asyncFunc: (...args: any[]) => Promise<T>): void; /** * Registers a function call for cross-thread invocation. * @param methodName - the name of the method to use during invocations. * @param asyncFuncOrObject - the function to execute when the method is invoked. * @param transferReturnValue - an (optional) function that reports on which values in the `returnValue` should be transfered instead of copied. */ addMethod<T>(methodName: string, asyncFunc: (...args: any[]) => Promise<T>, transferReturnValue: createTransferableCallback<T>): void; addMethod<T>(methodName: string, asyncFuncOrObject: (...args: any[]) => Promise<T> | object, transferReturnValue?: createTransferableCallback<T>): void { if (methodName === GET_PROPERTY_VALUES_METHOD) { throw new Error(`"${GET_PROPERTY_VALUES_METHOD}" is the name of an internal method for WorkerServers and cannot be overridden.`); } let method: Function = null; if (isFunction(asyncFuncOrObject)) { method = asyncFuncOrObject; } else { method = asyncFuncOrObject[methodName]; if (!isFunction(method)) { throw new Error(`${methodName} is not a method in the given object.`); } method = method.bind(asyncFuncOrObject); } this.addMethodInternal<T>(methodName, method, transferReturnValue); } addEvent<U extends EventBase, T>(object: U, type: string): void; addEvent<U extends EventBase, T>(object: U, type: string, makePayload: (evt: Event) => T): void; addEvent<U extends EventBase, T>(object: U, type: string, makePayload: (evt: Event) => T, transferReturnValue: createTransferableCallback<T>): void; addEvent<U extends EventBase, T>(object: U, type: string, makePayload?: (evt: Event) => T, transferReturnValue?: createTransferableCallback<T>): void { object.addEventListener(type, (evt: Event) => this.onEvent(type, evt, makePayload, transferReturnValue)); } }
the_stack
import { createFormValidation, BaseFormValidation } from '../baseFormValidation'; import { ValidationConstraints, FieldValidationResult, FieldValidationConstraint } from '../entities'; import { ValidationEngine } from '../validationEngine'; describe('formValidation tests', () => { describe('Group#1 => BaseFormValidation tests', () => { it('Spec#1 => should return an instance of Formvalidation', () => { // Arrange const validationConstraints = {}; // Act const formValidation = new BaseFormValidation(validationConstraints); // Assert expect(formValidation).to.be.an('object').that.is.not.null; expect(formValidation).to.be.an.instanceOf(BaseFormValidation); }); it('Spec#2 => should have an exposed method "isFormDirty" that calls ValidationEngine.isFormDirty', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const isFormDirty = sinon.stub(ValidationEngine.prototype, 'isFormDirty', () => { }); const validationConstraints = {}; // Act const formValidation = new BaseFormValidation(validationConstraints); formValidation.isFormDirty(); // Assert expect(isFormDirty.calledOnce).to.be.true; })); it('Spec#3 => should have an exposed method "validateField" that calls ValidationEngine.fireFieldValidations', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const fireFieldValidations = sinon.stub(ValidationEngine.prototype, 'fireFieldValidations', () => { }); const validationConstraints = {}; const viewModel = {}; const key = 'fullname'; const value = ''; const eventsFilter = undefined; // Act const formValidation = new BaseFormValidation(validationConstraints); formValidation.validateField(viewModel, key, value, eventsFilter); // Assert expect(fireFieldValidations.calledOnce).to.be.true; })); it('Spec#4 => should have an exposed method "validateForm" that calls ValidationEngine.validateForm', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validateForm = sinon.stub(ValidationEngine.prototype, 'validateForm', () => { }); const validationConstraints = {}; const viewModel = {}; // Act const formValidation = new BaseFormValidation(validationConstraints); formValidation.validateForm(viewModel); // Assert expect(validateForm.calledOnce).to.be.true; })); it('Spec#5 => should have an exposed method "isValidationInProgress" that calls ValidationEngine.isValidationInProgress', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const isValidationInProgress = sinon.stub(ValidationEngine.prototype, 'isValidationInProgress', () => { }); const validationConstraints = {}; // Act const formValidation = new BaseFormValidation(validationConstraints); formValidation.isValidationInProgress(); // Assert expect(isValidationInProgress.calledOnce).to.be.true; })); }); describe('Group#2 => createFormValidation tests', () => { it('Spec#1 => should return an instance of BaseFormValidation', () => { // Arrange const validationConstraints = {}; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(formValidation).to.be.an('object').that.is.an.instanceOf(BaseFormValidation); }); }); describe('Group#3 => createFormValidation ValidationConstraints.global object boundaries', () => { it('Spec #1 => should not add global validations with null value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #2 => should not add global validations with undefined value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #3 => should not add global validations with number value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #4 => should not add global validations with string value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #5 => should not add global validations with function value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #6 => should not add global validations with boolean value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #7 => should not add global validations with symbol value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const validationConstraints = null; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #8 => should not add global validations if global object is not an array of functions', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); const validationConstraints1 = { global: null }; const validationConstraints2 = { global: [null] }; // Act createFormValidation(validationConstraints1); createFormValidation(validationConstraints2); // Assert expect(addFormValidation.called).to.be.false; })); it('Spec #9 => should not add global validations if global object is an array of functions', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFormValidation = sinon.stub(ValidationEngine.prototype, 'addFormValidation', () => { }); const validationConstraints = { global: [ (vm: any) => new FieldValidationResult(), (vm: any) => new FieldValidationResult(), (vm: any) => new FieldValidationResult(), ] }; // Act createFormValidation(validationConstraints); // Assert expect(addFormValidation.calledThrice).to.be.true; })); }); describe('Group #4 => createFormValidation ValidationConstraints.fields object boundaries', () => { it('should not add a field validations given a non object', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validationConstraints: ValidationConstraints = { fields: ('test' as any) }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.called).to.be.false; })); it('should not add field validations given null value', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validationConstraints: ValidationConstraints = { fields: null }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.called).to.be.false; })); it('should not add field validations given a FieldValidationConstraint not being an array ', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validationConstraints: ValidationConstraints = { fields: { fullname: ('test' as any) } }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.called).to.be.false; })); it('should not add field validations given a FieldValidationConstraint array of non objects', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validation1 = () => new FieldValidationResult(); const validationConstraints: ValidationConstraints = { fields: { fullname: ([undefined, 'foo'] as any), } }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.calledOnce).to.be.false; })); it('should add field validations given an FieldValidationConstraint with {validator: <function>}', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validation1 = () => new FieldValidationResult(); const validation2 = () => new FieldValidationResult(); const eventsFilter = undefined; const customParams = undefined; const validationConstraints: ValidationConstraints = { fields: { property1: [ { validator: validation1 }, ], property2: [ { validator: validation2 }, ] } }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.calledTwice).to.be.true; expect(addFieldValidation.calledWithExactly('property1', validation1, eventsFilter, customParams)).to.be.true; expect(addFieldValidation.calledWithExactly('property2', validation2, eventsFilter, customParams)).to.be.true; })); it('should add multiple validations given a property haveing multiple FieldValidationConstraints', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validation1 = () => new FieldValidationResult(); const validation2 = () => new FieldValidationResult(); const eventsFilter = undefined; const customParams = undefined; const validationConstraints: ValidationConstraints = { fields: { property1: [ { validator: validation1 }, { validator: validation2 }, ] } }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.calledTwice).to.be.true; expect(addFieldValidation.calledWithExactly('property1', validation1, eventsFilter, customParams)).to.be.true; expect(addFieldValidation.calledWithExactly('property1', validation2, eventsFilter, customParams)).to.be.true; })); it('should pass FieldValidationConstraints to ValidationEngine', sinon.test(function () { // Arrange const sinon: sinon.SinonStatic = this; const addFieldValidation = sinon.stub(ValidationEngine.prototype, 'addFieldValidation', () => { }); const validation1 = () => new FieldValidationResult(); const customParams = { foo: 'bar' }; const eventsFilter = { onBlur: true }; const validationConstraints: ValidationConstraints = { fields: { property1: [ { validator: validation1, eventsFilter, customParams, }, ] } }; // Act const formValidation = createFormValidation(validationConstraints); // Assert expect(addFieldValidation.calledWithExactly('property1', validation1, eventsFilter, customParams)).to.be.true; })); }); });
the_stack
import { JEST_MATCHER_TO_MAX_ARGS, JEST_MOCK_PROPERTIES } from '../utils/consts' import finale from '../utils/finale' import { getRequireOrImportName, hasRequireOrImport, removeRequireAndImport, } from '../utils/imports' import logger from '../utils/logger' import { findParentCallExpression, findParentOfType, findParentVariableDeclaration, } from '../utils/recast-helpers' const matcherRenaming = { toExist: 'toBeTruthy', toNotExist: 'toBeFalsy', toNotBe: 'not.toBe', toNotEqual: 'not.toEqual', toNotThrow: 'not.toThrow', toBeA: 'toBeInstanceOf', toBeAn: 'toBeInstanceOf', toNotBeA: 'not.toBeInstanceOf', toNotBeAn: 'not.toBeInstanceOf', toNotMatch: 'not.toMatch', toBeFewerThan: 'toBeLessThan', toBeLessThanOrEqualTo: 'toBeLessThanOrEqual', toBeMoreThan: 'toBeGreaterThan', toBeGreaterThanOrEqualTo: 'toBeGreaterThanOrEqual', toInclude: 'toContain', toExclude: 'not.toContain', toNotContain: 'not.toContain', toNotInclude: 'not.toContain', toNotHaveBeenCalled: 'not.toHaveBeenCalled', } const matchersToBe = new Set(['toBeA', 'toBeAn', 'toNotBeA', 'toNotBeAn']) const matchersWithKey = new Set([ 'toContainKey', 'toExcludeKey', 'toIncludeKey', 'toNotContainKey', 'toNotIncludeKey', ]) const matchersWithKeys = new Set([ 'toContainKeys', 'toExcludeKeys', 'toIncludeKeys', 'toNotContainKeys', 'toNotIncludeKeys', ]) const expectSpyFunctions = new Set(['createSpy', 'spyOn', 'isSpy', 'restoreSpies']) const unsupportedSpyFunctions = new Set(['isSpy', 'restoreSpies']) const unsupportedExpectProperties = new Set(['extend']) const EXPECT = 'expect' function splitChainedMatcherPath(j, path) { if (path.parentPath.parentPath.node.type !== 'MemberExpression') { return } const pStatement = findParentOfType(path, 'ExpressionStatement') const pStatementNode = pStatement.node.original const expectCallExpression = path.node.object function splitChain(callExpression) { const next = callExpression.callee.object if (!next) { return } j(path) .closest(j.ExpressionStatement) .insertAfter( j.expressionStatement( j.callExpression( j.memberExpression( j.callExpression(expectCallExpression.callee, [ ...expectCallExpression.arguments, ]), callExpression.callee.property ), callExpression.arguments ) ) ) splitChain(next) } splitChain(pStatementNode.expression) pStatement.prune() } export default function expectTransformer(fileInfo, api, options) { const j = api.jscodeshift const ast = j(fileInfo.source) const { standaloneMode } = options if (!hasRequireOrImport(j, ast, EXPECT) && !options.skipImportDetection) { // No expect require/import were found return fileInfo.source } const expectFunctionName = getRequireOrImportName(j, ast, EXPECT) || EXPECT if (!standaloneMode) { removeRequireAndImport(j, ast, EXPECT) } const logWarning = (msg, node) => logger(fileInfo, msg, node) function balanceMatcherNodeArguments(matcherNode, matcher, path) { const newJestMatcherName = matcher.name.replace('not.', '') const maxArgs = JEST_MATCHER_TO_MAX_ARGS[newJestMatcherName] if (typeof maxArgs === 'undefined') { logWarning(`Unknown matcher "${newJestMatcherName}"`, path) return } if (matcherNode.arguments.length > maxArgs) { // Try to remove assertion message const lastArg = matcherNode.arguments[matcherNode.arguments.length - 1] if (lastArg.type === 'Literal') { matcherNode.arguments.pop() } } if (matcherNode.arguments.length <= maxArgs) { return } logWarning( `Too many arguments given to "${newJestMatcherName}". Expected max ${maxArgs} but got ${matcherNode.arguments.length}`, path ) } const getMatchers = () => ast.find(j.MemberExpression, { object: { type: 'CallExpression', callee: { type: 'Identifier', name: expectFunctionName }, }, property: { type: 'Identifier' }, }) const splitChainedMatchers = () => getMatchers().forEach((path) => { splitChainedMatcherPath(j, path) }) const updateMatchers = () => getMatchers().forEach((path) => { if (!standaloneMode) { path.parentPath.node.callee.object.callee.name = EXPECT } const matcherNode = path.parentPath.node const matcher = path.node.property const matcherName = matcher.name const matcherArgs = matcherNode.arguments const expectArgs = path.node.object.arguments const isNot = matcherName.indexOf('Not') !== -1 || matcherName.indexOf('Exclude') !== -1 if (matcherRenaming[matcherName]) { matcher.name = matcherRenaming[matcherName] } if (matchersToBe.has(matcherName)) { if (matcherArgs[0].type === 'Literal') { expectArgs[0] = j.unaryExpression('typeof', expectArgs[0]) matcher.name = isNot ? 'not.toBe' : 'toBe' } } if (matchersWithKey.has(matcherName)) { expectArgs[0] = j.template.expression`Object.keys(${expectArgs[0]})` matcher.name = isNot ? 'not.toContain' : 'toContain' } if (matchersWithKeys.has(matcherName)) { const keys = matcherArgs[0] matcherArgs[0] = j.identifier('e') expectArgs[0] = j.template.expression`Object.keys(${expectArgs[0]})` matcher.name = isNot ? 'not.toContain' : 'toContain' j(path.parentPath).replaceWith(j.template.expression`\ ${keys}.forEach(e => { ${matcherNode} })`) } if (matcherName === 'toMatch' || matcherName === 'toNotMatch') { // expect toMatch handles string, reg exp and object. const { name, type } = matcherArgs[0] if (type === 'ObjectExpression' || type === 'Identifier') { matcher.name = isNot ? 'not.toMatchObject' : 'toMatchObject' if (type === 'Identifier') { logWarning(`Use "toMatch" if "${name}" is not an object`, path) } } } balanceMatcherNodeArguments(matcherNode, matcher, path) }) const updateSpies = () => { ast .find(j.CallExpression, { callee: { type: 'Identifier', name: (name) => expectSpyFunctions.has(name), }, }) .forEach(({ value }) => { value.callee = j.memberExpression( j.identifier(expectFunctionName), j.identifier(value.callee.name) ) }) // Update expect.createSpy calls and warn about restoreSpies ast .find(j.MemberExpression, { object: { type: 'Identifier', name: expectFunctionName, }, property: { type: 'Identifier' }, }) .forEach((path) => { const { name } = path.value.property if (name === 'createSpy') { path.value.property.name = 'fn' } if (unsupportedSpyFunctions.has(name)) { logWarning(`"${path.value.property.name}" is currently not supported`, path) } }) // Warn about expect.spyOn calls with variable assignment ast .find(j.MemberExpression, { object: { type: 'Identifier', name: expectFunctionName, }, property: { type: 'Identifier', name: 'spyOn' }, }) .forEach((path) => { const parentAssignment = findParentOfType(path, 'VariableDeclarator') || findParentOfType(path, 'AssignmentExpression') if (!parentAssignment) { logWarning( `"${path.value.property.name}" without variable assignment might not work as expected (see https://facebook.github.io/jest/docs/jest-object.html#jestspyonobject-methodname)`, path ) } }) // Update mock chain calls const updateSpyProperty = (path, property) => { if (!property) { return } if (property.name === 'andReturn') { const callExpression = findParentCallExpression(path, property.name).value callExpression.arguments = [ j.arrowFunctionExpression([j.identifier('()')], callExpression.arguments[0]), ] } if (property.name === 'andThrow') { const callExpression = findParentCallExpression(path, property.name).value const throughExpression = callExpression.arguments[0] callExpression.arguments = [ j.arrowFunctionExpression( [j.identifier('()')], j.blockStatement([j.throwStatement(throughExpression)]) ), ] } if (property.name === 'andCallThrough') { const callExpression = findParentCallExpression(path, property.name) const innerCallExpression = callExpression.value.callee.object j(callExpression).replaceWith(innerCallExpression) } const propertyNameMap = { andCall: 'mockImplementation', andReturn: 'mockImplementation', andThrow: 'mockImplementation', calls: 'mock.calls', reset: 'mockClear', restore: 'mockReset', } const newPropertyName = propertyNameMap[property.name] if (newPropertyName) { property.name = newPropertyName } // Remap spy.calls[x].arguments const potentialArgumentsPath = path.parentPath.parentPath const potentialArgumentsNode = potentialArgumentsPath.value if ( property.name === 'mock.calls' && potentialArgumentsNode.property && potentialArgumentsNode.property.name === 'arguments' ) { const variableName = path.value.object.name const callsProperty = path.parentPath.value.property if (potentialArgumentsPath.parentPath.value.type !== 'MemberExpression') { // spy.calls[x].arguments => spy.mock.calls[x] potentialArgumentsPath.replace( j.memberExpression( j.memberExpression(j.identifier(variableName), j.identifier('mock.calls')), callsProperty, true ) ) return } // spy.calls[x].arguments[y] => spy.mock.calls[x][y] const outherNode = path.parentPath.parentPath.parentPath const argumentsProperty = outherNode.value.property outherNode.replace( j.memberExpression( j.memberExpression( j.memberExpression(j.identifier(variableName), j.identifier('mock.calls')), callsProperty, true ), argumentsProperty, true ) ) } } const spyVariables = [] ast .find(j.MemberExpression, { object: { type: 'Identifier', name: expectFunctionName, }, property: { type: 'Identifier', name: (name) => JEST_MOCK_PROPERTIES.has(name), }, }) .forEach((path) => { const spyVariable = findParentVariableDeclaration(path) if (spyVariable) { spyVariables.push(spyVariable.value.id.name) } const { property } = path.parentPath.parentPath.value updateSpyProperty(path, property) }) // Update spy variable methods ast .find(j.MemberExpression, { object: { type: 'Identifier', name: (name) => spyVariables.indexOf(name) >= 0, }, }) .forEach((path) => { const { property } = path.value let spyProperty = null if (property.type === 'Identifier') { // spy.calls.length spyProperty = property } if (property.type === 'Literal') { // spies[0].calls.length spyProperty = path.parentPath.value.property } if (spyProperty) { updateSpyProperty(path, spyProperty) } }) } const checkForUnsupportedFeatures = () => ast .find(j.MemberExpression, { object: { name: expectFunctionName, }, property: { name: (name) => unsupportedExpectProperties.has(name), }, }) .forEach((path) => { logWarning(`"${path.value.property.name}" is currently not supported`, path) }) splitChainedMatchers() updateMatchers() updateSpies() checkForUnsupportedFeatures() return finale(fileInfo, j, ast, options, expectFunctionName) }
the_stack
module Cats.Gui.Editor { var Range: ace.Range = ace.require( "ace/range" ).Range; var modelist = ace.require( 'ace/ext/modelist' ); var autoCompletePopup = new AutoCompletePopup(); var registryEntryName = "SourceEditor"; function restoreState( state: SourceEditorState ) { var editor = new SourceEditor( state.fileName ); editor.moveToPosition( state.pos ); return editor; } Cats.Editor.RegisterEditor( registryEntryName, restoreState ); interface SourceEditorState { fileName: string; pos: Position; } /** * Wrapper around the ACE editor. The rest of the code base should not use * ACE editor directly so it can be changed for another editor if required. */ export class SourceEditor extends FileEditor { private status = {}; private unsavedChanges = false; private aceEditor: ace.Editor; private mouseMoveTimer: number; private outlineTimer: number private updateSourceTimer: number; private pendingWorkerUpdate = false; private editSession: EditSession; private pendingPosition: ace.Position; private selectedTextMarker: any; private widget: qx.ui.core.Widget; private contextMenu: SourceEditorContextMenu; constructor( fileName?: string) { super( fileName ); this.createEditSession(); this.createWidget(); this.contextMenu = new SourceEditorContextMenu( this ); this.widget.setContextMenu(this.contextMenu) IDE.on( "config", () => { this.configureEditor(); }); } get project() { return IDE.getProject(this.filePath); } private createWidget() { var widget = new qx.ui.core.Widget(); widget.setDecorator( null ); widget.setFont( null ); widget.setAppearance( null ); widget.addListenerOnce( "appear", () => { var container = widget.getContentElement().getDomElement(); container.style.lineHeight = "normal"; this.aceEditor = this.createAceEditor( container ); this.configureEditor(); if ( this.pendingPosition ) this.moveToPosition( this.pendingPosition ); }, this ); widget.addListener( "appear", () => { // this.session.activate(); this.informWorld(); if ( this.aceEditor ) this.aceEditor.focus(); }); // session.on("errors", this.showErrors, this); widget.addListener( "resize", () => { this.resizeHandler(); }); this.widget = widget; } private createEditSession() { this.editSession = new EditSession( this); this.editSession.on( "changeAnnotation", () => { this.emit( "errors", this.editSession.getMaxAnnotationLevel() ); }); this.editSession.on( "changeOverwrite", () => { this.informWorld(); }); this.editSession.on( "change", () => { this.setHasUnsavedChanges( true ); }); } getAceEditor() { return this.aceEditor; } setHasUnsavedChanges( value: boolean ) { if ( value === this.unsavedChanges ) return; this.unsavedChanges = value; this.emit( "changed", value ); } getState(): SourceEditorState { return { fileName: this.filePath, pos: this.getPosition() }; } static RestoreState( state: SourceEditorState ) { var editor = new SourceEditor( state.fileName ); editor.moveToPosition( state.pos ); return editor; } executeCommand( name:string, ...args:any[] ): any { switch ( name ) { case 'toggleInvisibles': this.aceEditor.setShowInvisibles( !this.aceEditor.getShowInvisibles() ); break; case 'formatText': this.formatText(); break; default: this.aceEditor.execCommand( name ); break; } } /** * Is the file being part of a tsconfig project. This is used to determine * wehter all type of features specific to TS will be enabled. * */ hasProject() { return this.project != null; } getType() { return registryEntryName; } static SupportsFile( fileName: string ) { var name = OS.File.PATH.basename( fileName ); var mode = modelist.getModeForPath( name ); if ( mode && mode.supportsFile( name ) ) return true; return false; } /** * Get the Qooxdoo Widget that can be added to the parent */ getLayoutItem() { return this.widget; } private formatText() { var r:Range = null; if ( this.hasProject() ) { var range: ace.Range = this.aceEditor.selection.getRange(); if ( !range.isEmpty() ) r = { start: range.start, end: range.end }; this.project.iSense.getFormattedTextForRange( this.filePath, r, ( err: Error, result: string ) => { if ( !err ) this.setContent( result ); }); } } setMode(mode:string) { this.editSession.setMode(mode); this.informWorld(); } /** * Replace the current content of this editor with new content and indicate * wether the cursor should stay on the same position * */ setContent( content:string, keepPosition= true ) { var pos: ace.Position; if ( keepPosition ) pos = this.getPosition(); this.editSession.setValue( content ); if ( pos ) this.moveToPosition( pos ); } /** * Update the configuaration of the editor. * */ private configureEditor() { var config = IDE.config; if ( config.fontSize ) this.aceEditor.setFontSize( config.fontSize + "px" ); if ( config.editor && config.editor.rightMargin ) this.aceEditor.setPrintMarginColumn( config.editor.rightMargin ); if ( IDE.theme ) this.aceEditor.setTheme( IDE.theme.ace ); } /** * Inform the world about current status of the editor * */ informWorld() { var value = this.getPosition(); var label = ( value.row + 1 ) + ":" + ( value.column + 1 ); this.status = { overwrite: this.editSession.getOverwrite(), mode: OS.File.PATH.basename( this.editSession.mode ).toUpperCase(), position: label }; this.emit( "status", this.status ); } replace( range: ace.Range, content: string ) { this.editSession.replace( range, content ); } getLine( row = this.getPosition().row ) { return this.editSession.getLine( row ); } /** * Get the content of the editor * */ getContent() { return this.editSession.getValue(); } /** * Make sure the ace editor is resized when the Qooxdoo container is resized. * */ private resizeHandler() { if ( !this.widget.isSeeable() ) { this.addListenerOnce( "appear", () => { this.resizeEditor(); }); } else { this.resizeEditor(); } } private resizeEditor() { setTimeout( () => { this.aceEditor.resize(); }, 100 ); } private clearSelectedTextMarker() { if ( this.selectedTextMarker ) { this.editSession.removeMarker( this.selectedTextMarker ); this.selectedTextMarker = null; } } private addTempMarker( r: Cats.Range ) { this.clearSelectedTextMarker(); var range: ace.Range = new Range( r.start.row, r.start.column, r.end.row, r.end.column ); this.selectedTextMarker = this.editSession.addMarker( range, "ace_selected-word", "text" ); } moveToPosition( pos: Cats.Range ):void; moveToPosition( pos: ace.Position ):void; moveToPosition( pos: any ) { if ( !this.aceEditor ) { this.pendingPosition = pos; } else { this.aceEditor.clearSelection(); super.moveToPosition( pos ); if ( pos ) { if ( pos.start ) { this.aceEditor.moveCursorToPosition( pos.start ); } else { this.aceEditor.moveCursorToPosition( pos ); } } setTimeout( () => { this.aceEditor.centerSelection(); if ( pos && pos.start ) this.addTempMarker( pos ); }, 100 ); } } /** * Get the position of the cursor within the content. * */ getPosition() { if (this.aceEditor) return this.aceEditor.getCursorPosition(); } /** * Get the Position based on mouse x,y coordinates */ getPositionFromScreenOffset( ev: MouseEvent ): ace.Position { var x = ev.offsetX; var y = ev.offsetY; // var cursor = this.aceEditor.renderer.pixelToScreenCoordinates(x, y); // IDE.console.log(JSON.stringify(cursor)); // var docPos2 = this.aceEditor.getSession().screenToDocumentPosition(cursor.row, cursor.col); // IDE.console.log(JSON.stringify(docPos2)); var r = this.aceEditor.renderer; // var offset = (x + r.scrollLeft - r.$padding) / r.characterWidth; var offset = ( x - r.$padding ) / r.characterWidth; // @BUG: Quickfix for strange issue with top var correction = r.scrollTop ? 7 : 0; var row = Math.floor( ( y + r.scrollTop - correction ) / r.lineHeight ); var col = Math.round( offset ); var docPos = this.aceEditor.getSession().screenToDocumentPosition( row, col ); // IDE.console.log(JSON.stringify(docPos)); return docPos; } /** * Perform code autocompletion. */ showAutoComplete( memberCompletionOnly = false ) { // Any pending changes that are not yet send to the worker? if (this.hasProject()) { this.project.iSense.updateScript( this.filePath, this.getContent() ); } autoCompletePopup.complete( memberCompletionOnly, this, this.aceEditor ); } private liveAutoComplete( e ) { if (! this.hasProject()) return; var text = e.args || ""; if ( ( e.command.name === "insertstring" ) && ( text === "." ) ) { this.showAutoComplete( true ); } } /** * Create a new isntance of the ACE editor and append is to a dom element * */ private createAceEditor( rootElement: HTMLElement ): ace.Editor { var editor: ace.Editor = ace.edit( rootElement ); editor["$blockScrolling"] = Infinity; // surpresses ACE warning editor.setSession( this.editSession ); editor.on( "changeSelection", () => { this.clearSelectedTextMarker(); this.informWorld(); }); new TSTooltip( this ); new TSHelper( this, this.editSession ); editor.commands.on( 'afterExec', ( e ) => { this.liveAutoComplete( e ); }); editor.setOptions( { enableSnippets: true }); editor.commands.addCommands( [ { name: "autoComplete", bindKey: { win: "Ctrl-Space", mac: "Ctrl-Space" }, exec: () => { this.showAutoComplete(); } }, { name: "gotoDeclaration", bindKey: { win: "F12", mac: "F12" }, exec: () => { this.contextMenu.gotoDeclaration(); } }, { name: "save", bindKey: { win: "Ctrl-S", mac: "Command-S" }, exec: () => { this.save(); } } ] ); return editor; } hasUnsavedChanges() { return this.unsavedChanges; } /** * Persist this session to the file system. This overrides the NOP in the base class */ save() { this.editSession.save(); } } }
the_stack
import React, { Component } from 'react'; import { registerComponent, Components } from '../../lib/vulcan-lib'; import { withUpdateCurrentUser, WithUpdateCurrentUserProps } from '../hooks/useUpdateCurrentUser'; import { userEmailAddressIsVerified } from '../../lib/collections/users/helpers'; import { rssTermsToUrl } from "../../lib/rss_urls"; import { CopyToClipboard } from 'react-copy-to-clipboard'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; import withMobileDialog from '@material-ui/core/withMobileDialog'; import withUser from '../common/withUser'; import { withTracking } from "../../lib/analyticsEvents"; import { forumTypeSetting } from '../../lib/instanceSettings'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import { forumSelect } from '../../lib/forumTypeUtils'; const isEAForum = forumTypeSetting.get() === "EAForum"; const styles = (theme: ThemeType): JssStyles => ({ thresholdSelector: { display: "flex", flexDirection: "row", justifyContent: "space-evenly" }, estimate: { maxWidth: "500px" }, content: { padding: `0 ${theme.spacing.unit * 3}px` }, tabbar: { marginBottom: theme.spacing.unit * 3 }, viewSelector: { width: "100%", marginBottom: theme.spacing.unit * 2 }, RSSLink: { marginTop: theme.spacing.unit * 2 }, errorMsg: { color: theme.palette.text.error, }, link: { textDecoration: "underline" }, }); const thresholds = forumSelect({ LessWrong: [2, 30, 45, 75, 125], AlignmentForum: [2, 30, 45], EAForum: [2, 30, 75, 125, 200], // We default you off pretty low, you can add more once you get more high // karma posts default: [2, 30, 45, 75] }) /** * Calculated based on the average number of words posted per post on LW2 as of * August 2018. */ function timePerWeekFromPosts(posts: number) { const minutes = posts * 11 if (minutes < 60) { return `${minutes} minutes` } return `${Math.round(minutes / 60)} hours` } /** Posts per week as of May 2022 */ const postsPerWeek = forumSelect({ EAForum: { 2: 119, 30: 24, 45: 20, 75: 10, 125: 4, 200: 1, }, // (JP) I eyeballed these, you could query your db for better numbers LessWrong: { 2: 80, 30: 16, 45: 13, 75: 7, 125: 2, }, AlignmentForum: { 2: 10, 30: 2, 45: 1, }, }); const viewNames = { 'frontpage': 'Frontpage', 'curated': 'Curated Content', 'community': 'All Posts', 'pending': 'pending posts', 'rejected': 'rejected posts', 'scheduled': 'scheduled posts', 'all_drafts': 'all drafts', } interface ExternalProps { method: any, view: any, fullScreen?: boolean, onClose: any, open: boolean, } interface SubscribeDialogProps extends ExternalProps, WithUserProps, WithStylesProps, WithTrackingProps, WithUpdateCurrentUserProps { } interface SubscribeDialogState { view: any, method: any, threshold: string, copiedRSSLink: boolean, subscribedByEmail: boolean, } class SubscribeDialog extends Component<SubscribeDialogProps,SubscribeDialogState> { constructor(props: SubscribeDialogProps) { super(props); this.state = { threshold: "30", method: this.props.method, copiedRSSLink: false, subscribedByEmail: false, view: (this.props.method === "email" && !this.emailFeedExists(this.props.view)) ? "curated" : this.props.view, }; } rssTerms() { const view = this.state.view; let terms: any = { view: `${view}-rss` }; if (view === "community" || view === "frontpage") terms.karmaThreshold = this.state.threshold; return terms; } autoselectRSSLink(event) { event.target.select(); } sendVerificationEmail() { const { updateCurrentUser, currentUser } = this.props; if (!currentUser) return; void updateCurrentUser({ whenConfirmationEmailSent: new Date() }); } subscribeByEmail() { let mutation: Partial<DbUser> = { emailSubscribedToCurated: true } const { currentUser, updateCurrentUser, captureEvent } = this.props; if (!currentUser) return; if (isEAForum && !userEmailAddressIsVerified(currentUser)) { // Combine mutations into a single update call. // (This reduces the number of server-side callback // invocations. In a past version this worked around // a bug, now it's just a performance optimization.) mutation = {...mutation, whenConfirmationEmailSent: new Date()}; } void updateCurrentUser(mutation) this.setState({ subscribedByEmail: true }); captureEvent("subscribedByEmail") } emailSubscriptionEnabled() { return this.props.currentUser && this.props.currentUser.email } emailFeedExists(view) { if (view === "curated") return true; return false; } isAlreadySubscribed() { if (this.state.view === "curated" && this.props.currentUser && this.props.currentUser.emailSubscribedToCurated) return true; return false; } selectMethod(method) { this.setState({ copiedRSSLink: false, subscribedByEmail: false, method }) } selectThreshold(threshold) { this.setState({ copiedRSSLink: false, subscribedByEmail: false, threshold }) } selectView(view) { this.setState({ copiedRSSLink: false, subscribedByEmail: false, view }) } render() { const { classes, fullScreen, onClose, open, currentUser } = this.props; const { view, threshold, method, copiedRSSLink, subscribedByEmail } = this.state; const { LWDialog } = Components; const viewSelector = <FormControl key="viewSelector" className={classes.viewSelector}> <InputLabel htmlFor="subscribe-dialog-view">Feed</InputLabel> <Select value={view} onChange={ event => this.selectView(event.target.value) } disabled={method === "email" && !currentUser} inputProps={{ id: "subscribe-dialog-view" }} > {/* TODO: Forum digest */} {!isEAForum && <MenuItem value="curated">Curated</MenuItem>} <MenuItem value="frontpage" disabled={method === "email"}>Frontpage</MenuItem> <MenuItem value="community" disabled={method === "email"}>All Posts</MenuItem> </Select> </FormControl> return ( <LWDialog fullScreen={fullScreen} open={open} onClose={onClose} > {!isEAForum && <Tabs value={method} indicatorColor="primary" textColor="primary" onChange={ (event, value) => this.selectMethod(value) } className={classes.tabbar} fullWidth > <Tab label="RSS" key="tabRSS" value="rss" /> <Tab label="Email" key="tabEmail" value="email" /> </Tabs>} <DialogContent className={classes.content}> { method === "rss" && <React.Fragment> {viewSelector} {(view === "community" || view === "frontpage") && <div> <DialogContentText>Generate a RSS link to posts in {viewNames[view]} of this karma and above.</DialogContentText> <RadioGroup value={threshold} onChange={ (event, value) => this.selectThreshold(value) } className={classes.thresholdSelector} > { thresholds.map(t => t.toString()).map(threshold => <FormControlLabel control={<Radio />} label={threshold} value={threshold} key={`labelKarmaThreshold${threshold}`} className={classes.thresholdButton} /> ) } </RadioGroup> <DialogContentText className={classes.estimate}> That's roughly { postsPerWeek[threshold] } posts per week ({ timePerWeekFromPosts(postsPerWeek[threshold]) } of reading) </DialogContentText> </div>} <TextField className={classes.RSSLink} label="RSS Link" onFocus={this.autoselectRSSLink} onClick={this.autoselectRSSLink} value={rssTermsToUrl(this.rssTerms())} key="rssLinkTextField" fullWidth /> </React.Fragment> } { method === "email" && [ viewSelector, !!currentUser ? ( [ !this.emailFeedExists(view) && <DialogContentText key="dialogNoFeed" className={classes.errorMsg}> Sorry, there's currently no email feed for {viewNames[view]}. </DialogContentText>, subscribedByEmail && !userEmailAddressIsVerified(currentUser) && !isEAForum && <DialogContentText key="dialogCheckForVerification" className={classes.infoMsg}> We need to confirm your email address. We sent a link to {currentUser.email}; click the link to activate your subscription. </DialogContentText> ] ) : ( <DialogContentText key="dialogPleaseLogIn" className={classes.errorMsg}> You need to <a className={classes.link} href="/login">log in</a> to subscribe via Email </DialogContentText> ) ] } </DialogContent> <DialogActions> { method === "rss" && <CopyToClipboard text={rssTermsToUrl(this.rssTerms())} onCopy={ (text, result) => { this.setState({ copiedRSSLink: result }) this.props.captureEvent("rssLinkCopied") }} > <Button color="primary">{copiedRSSLink ? "Copied!" : "Copy Link"}</Button> </CopyToClipboard> } { method === "email" && (this.isAlreadySubscribed() ? <Button color="primary" disabled={true}> You are already subscribed to this feed. </Button> : <Button color="primary" onClick={ () => this.subscribeByEmail() } disabled={!this.emailFeedExists(view) || subscribedByEmail || !currentUser} >{subscribedByEmail ? "Subscribed!" : "Subscribe to Feed"}</Button> ) } <Button onClick={onClose}>Close</Button> </DialogActions> </LWDialog> ); } } const SubscribeDialogComponent = registerComponent<ExternalProps>("SubscribeDialog", SubscribeDialog, { styles, hocs: [ withMobileDialog(), withUser, withUpdateCurrentUser, withTracking, ] }); declare global { interface ComponentTypes { SubscribeDialog: typeof SubscribeDialogComponent } }
the_stack
import { dirname, resolve } from 'path' import { openSync, closeSync } from 'fs' import * as knex from 'knex' import Model from './model' import { runQuery } from './helpers' import { toKnexSchema } from './schema-helpers' import { pureConnect } from './sqljs-handler' import { invariant, makeDirPath } from './util' import { Pool } from 'generic-pool' import { Database } from 'sql.js' import * as hooks from './hooks' import * as types from './types' const ensureExists = (atPath: string) => { try { closeSync(openSync(atPath, 'wx')) } catch {} } const initOptions = (path: string, options: types.TrilogyOptions) => ({ ...{ client: 'sqlite3' as const, dir: process.cwd() }, ...types.TrilogyOptions.check(options), ...{ connection: { filename: path } } }) /** * Initialize a new datastore instance, creating a SQLite database file at * the provided path if it does not yet exist, or reading it if it does. * * It's recommended to use the {@link connect} function to create instances * rather than instantiating this class directly. * * @remarks * If path is exactly `':memory:'`, no file will be created and a memory-only * store will be used. This doesn't persist any of the data. */ export class Trilogy { /** * Indicates whether the database is using the `sqlite3` client (`true`) or * the `sql.js` (`false`) backend. */ isNative: boolean /** * The knex instance used for building queries. */ knex: knex /** * Normalized configuration of this trilogy instance. */ options: types.Defined<types.TrilogyOptions> & { connection: { filename: string } } /** * Connection pool for managing a sql.js instance. * * @internal */ pool?: Pool<Database> private _definitions: Map<string, Model<any>> /** * @param path File path or `':memory:'` for in-memory storage * @param options Configuration for this trilogy instance */ constructor (path: string, options: types.TrilogyOptions = {}) { invariant(path, 'trilogy constructor must be provided a file path') const obj = this.options = initOptions(path, options) if (path === ':memory:') { obj.connection.filename = path } else { obj.connection.filename = resolve(obj.dir, path) // ensure the directory exists makeDirPath(dirname(obj.connection.filename)) } this.isNative = obj.client === 'sqlite3' if (path !== ':memory:') { ensureExists(obj.connection.filename) } const config = { client: 'sqlite3', useNullAsDefault: true } if (this.isNative) { this.knex = knex(({ ...config, connection: obj.connection } as knex.Config)) } else { this.knex = knex(config) this.pool = pureConnect(this) } this._definitions = new Map() } /** * Array of all model names defined on the instance. */ get models () { return [...this._definitions.keys()] } /** * Define a new model with the provided schema, or return the existing * model if one is already defined with the given name. * * @param name Name of the model * @param schema Object defining the schema of the model * @param options Configuration for this model instance */ async model <D extends types.ReturnDict = types.LooseObject> ( name: string, schema: types.SchemaRaw<D>, options: types.ModelOptions = {} ): Promise<Model<D>> { if (this._definitions.has(name)) { return this._definitions.get(name) as Model<D> } const model = new Model<D>(this, name, schema, options) this._definitions.set(name, model) const opts = toKnexSchema( model, types.ModelOptions.check(options) ) const check = this.knex.schema.hasTable(name) const query = this.knex.schema.createTable(name, opts) if (this.isNative) { if (!await check) { // tslint:disable-next-line:await-promise await query } } else { if (!await runQuery(this, check, { needResponse: true })) { await runQuery(this, query) } } return model } /** * Synchronously retrieve a model if it exists. If that model doesn't exist * an error will be thrown. * * @param name Name of the model * * @throws if `name` has not already been defined */ getModel <D extends types.ReturnDict = types.LooseObject> (name: string): Model<D> | never { return invariant( this._definitions.get(name) as Model<D>, `no model defined by the name '${name}'` ) } /** * First checks if the model's been defined with trilogy, then runs an * existence query on the database, returning `true` if the table exists * or `false` if it doesn't. * * @param name Name of the model */ async hasModel (name: string): Promise<boolean> { if (!this._definitions.has(name)) { return false } const query = this.knex.schema.hasTable(name) return runQuery(this, query, { needResponse: true }) } /** * Removes the specified model from trilogy's definition and the database. * * @param name Name of the model to remove */ async dropModel (name: string): Promise<boolean> { if (!this._definitions.has(name)) { return false } const query = this.knex.schema.dropTableIfExists(name) await runQuery(this, query, { needResponse: true }) this._definitions.delete(name) return true } /** * Allows running any arbitrary query generated by trilogy's `knex` instance. * If the result is needed, pass `true` as the second argument, otherwise the * number of affected rows will be returned ( if applicable ). * * @param query Any query built with `knex` * @param [needResponse] Whether to return the result of the query */ async raw <T = any> (query: knex.QueryBuilder | knex.Raw, needResponse?: boolean): Promise<T> { return runQuery(this, query, { needResponse }) } /** * Drains the connection pools and releases connections to any open database * files. This should always be called at the end of your program to * gracefully shut down, and only once since the connection can't be reopened. */ async close () { if (this.isNative) { return this.knex.destroy() } else { return this.pool!.drain() } } /** * Create an object on the given model. `object` should match the model's * defined schema but values will cast into types as needed. * * @param modelName Name of the existing model where the object will be created * @param object Data to insert * @param options */ async create <T = types.LooseObject> ( modelName: string, object: types.LooseObject, options?: types.LooseObject ): Promise<T> async create ( modelName: string, object: types.LooseObject, options?: types.LooseObject ) { const model = this.getModel(modelName) return model.create(object, options) } /** * Find all objects matching a given criteria. * * @param location Model name and an optional column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ async find <T = types.LooseObject> ( location: string, criteria?: types.Criteria, options?: types.FindOptions ): Promise<T[]> async find ( location: string, criteria?: types.Criteria, options?: types.FindOptions ) { const [table, column] = location.split('.', 2) const model = this.getModel(table) if (column) { return model.findIn(column, criteria, options) } else { return model.find(criteria, options) } } /** * Find a single object matching a given criteria. The first matching * object is returned. * * @param location Model name and an optional column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ async findOne <T = types.LooseObject> ( location: string, criteria?: types.Criteria, options?: types.FindOptions ): Promise<T> async findOne ( location: string, criteria?: types.Criteria, options?: types.FindOptions ) { const [table, column] = location.split('.', 2) const model = this.getModel(table) if (column) { return model.findOneIn(column, criteria, options) } else { return model.findOne(criteria, options) } } /** * Find a matching object based on the given criteria, or create it if it * doesn't exist. When creating the object, a merged object created from * `criteria` and `creation` will be used, with the properties from * `creation` taking precedence. * * @param modelName Name of the model * @param criteria Criteria to search for * @param creation Data used to create the object if it doesn't exist * @param options */ async findOrCreate <T = types.LooseObject> ( modelName: string, criteria: types.Criteria, creation?: types.LooseObject, options?: types.FindOptions ): Promise<T> async findOrCreate ( modelName: string, criteria: types.Criteria, creation?: types.LooseObject, options?: types.FindOptions ) { const model = this.getModel(modelName) return model.findOrCreate(criteria, creation, options) } /** * Modify the properties of an existing object. While optional, if `data` * contains no properties no update queries will be run. * * @param modelName Name of the model * @param criteria Criteria used to restrict selection * @param data Updates to be made on matching objects * @param options */ async update ( modelName: string, criteria: types.Criteria, data: types.LooseObject, options?: types.UpdateOptions ) { const model = this.getModel(modelName) return model.update(criteria, data, options) } /** * Update an existing object or create it if it doesn't exist. If creation * is necessary a merged object created from `criteria` and `data` will be * used, with the properties from `data` taking precedence. * * @param modelName Name of the model * @param criteria Criteria used to restrict selection * @param data Updates to be made on matching objects * @param options */ async updateOrCreate ( modelName: string, criteria: types.Criteria, data: types.LooseObject, options?: types.CreateOptions & types.UpdateOptions ) { const model = this.getModel(modelName) return model.updateOrCreate(criteria, data, options) } /** * Works similarly to the `get` methods in lodash, underscore, etc. Returns * the value at `column` or, if it does not exist, the supplied `defaultValue`. * Essentially a useful shorthand for some `find` scenarios. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param defaultValue Value returned if the result doesn't exist */ async get <T = types.ReturnType> ( location: string, criteria: types.Criteria, defaultValue?: T ): Promise<T> async get ( location: string, criteria: types.Criteria, defaultValue?: any ): Promise<any> { const [table, column] = location.split('.', 2) invariant(column, 'property name is required, ex: `get("users.rank")`') const model = this.getModel(table) return model.get(column, criteria, defaultValue) } /** * Works similarly to the `set` methods in lodash, underscore, etc. Updates * the value at `column` to be `value` where the given criteria is met. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param value Value returned if the result doesn't exist */ async set <T> (location: string, criteria: types.Criteria, value: T) { const [table, column] = location.split('.', 2) invariant(column, 'property name is required, ex: `set("users.rank")`') const model = this.getModel(table) return model.set(column, criteria, value) } /** * Works exactly like `get` but bypasses getters and retrieves the raw database value. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param defaultValue Value returned if the result doesn't exist */ async getRaw <T> (location: string, criteria: types.Criteria, defaultValue: T): Promise<T> async getRaw (location: string, criteria: types.Criteria): Promise<types.ReturnType> async getRaw <T extends Record<string, unknown>, K extends keyof T = keyof T> ( location: string, criteria: types.Criteria ): Promise<T[K]> async getRaw ( location: string, criteria: types.Criteria, defaultValue?: any ): Promise<any> { const [table, column] = location.split('.', 2) invariant(column, 'property name is required, ex: `getRaw("users.rank")`') const model = this.getModel(table) return model.getRaw(column, criteria, defaultValue) } /** * Works exactly like `set` but bypasses setters when updating the target value. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param value Value returned if the result doesn't exist */ async setRaw <T> (location: string, criteria: types.Criteria, value: T) { const [table, column] = location.split('.', 2) invariant(column, 'property name is required, ex: `setRaw("users.rank")`') const model = this.getModel(table) return model.setRaw(column, criteria, value) } /** * Increment the value of a given model's property by the specified amount, * which defaults to `1` if not provided. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param amount */ async increment (location: string, criteria: types.Criteria, amount?: number) { const [table, column] = location.split('.', 2) const model = this.getModel(table) return model.increment(column, criteria, amount) } /** * Decrement the value of a given model's property by the specified amount, * which defaults to `1` if not provided. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param amount */ async decrement ( location: string, criteria: types.Criteria, amount?: number, allowNegative?: boolean ) { const [table, column] = location.split('.', 2) const model = this.getModel(table) return model.decrement(column, criteria, amount, allowNegative) } /** * Delete objects matching `criteria` from the given model. * * @remarks * If `criteria` is empty or absent, nothing will be done. This is a safeguard * against unintentionally deleting everything in the model. Use `clear` if * you really want to remove all rows. * * @param modelName Name of the model * @param criteria Criteria used to restrict selection */ async remove (modelName: string, criteria: types.Criteria) { const model = this.getModel(modelName) return model.remove(criteria) } /** * Delete all objects from the given model. * * @param modelName Name of the model */ async clear (modelName: string) { const model = this.getModel(modelName) return model.clear() } /** * Count the number of objects in the given model. * * @param location Model name and an optional column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ async count ( location?: string, criteria?: types.Criteria, options?: types.AggregateOptions ): Promise<number> { if (location == null && criteria == null && options == null) { const query = this.knex('sqlite_master') .whereNot('name', 'sqlite_sequence') .where({ type: 'table' }) .count('* as count') return runQuery(this, query, { needResponse: true }) .then(([{ count }]) => count) } const [table, column] = (location ?? '').split('.', 2) const model = this.getModel(table) return column ? model.countIn(column, criteria, options) : model.count(criteria, options) } /** * Find the minimum value contained in the model, comparing all values in * `column` that match the given criteria. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ async min (location: string, criteria: types.Criteria, options?: types.AggregateOptions) { const [table, column] = location.split('.', 2) invariant(column, 'property name is required, ex: `min("users.rank")`') const model = this.getModel(table) return model.min(column, criteria, options) } /** * Find the maximum value contained in the model, comparing all values in * `column` that match the given criteria. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ async max (location: string, criteria: types.Criteria, options?: types.AggregateOptions) { const [table, column] = location.split('.', 2) invariant(column, 'property name is required, ex: `max("users.rank")`') const model = this.getModel(table) return model.max(column, criteria, options) } /** * The `onQuery` hook is called each time a query is run on the database, * and receives the query in string form. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * @param options * * @returns Unsubscribe function that removes the subscriber when called */ onQuery ( ...args: | [hooks.OnQueryCallback, hooks.OnQueryOptions?] | [string, hooks.OnQueryCallback, hooks.OnQueryOptions?] ): types.Fn<[], boolean> { // tslint:disable-next-line:no-empty let fn: hooks.OnQueryCallback = () => {} let location = '' let options: hooks.OnQueryOptions = { includeInternal: false } if (args.length === 1) { fn = args[0] } if (args.length >= 2) { if (typeof args[0] === 'string') { location = args[0] } else if (typeof args[1] === 'function') { fn = args[0] } if (typeof args[1] === 'function') { fn = args[1] } else { options = { ...options, ...args[1] } } } if (args.length === 3) { options = args[2] || options } // console.log({ location, fn, options }) if (location !== '') { // all queries run on the model identified by `location` return this.getModel(location).onQuery(fn, options) } // all queries run across all defined models const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach(model => { unsubs[++i] = model.onQuery(fn, options) }) return () => unsubs.every(unsub => unsub()) } /** * Before an object is created, the beforeCreate hook is called with the * object. * * @remarks * This hook occurs before casting, so if a subscriber to this hook * modifies the incoming object those changes will be subject to casting. * It's also possible to prevent the object from being created entirely * by returning the EventCancellation symbol from a subscriber callback. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ beforeCreate <D extends types.ReturnDict = types.LooseObject> ( ...args: [hooks.BeforeCreateCallback<D>] | [string, hooks.BeforeCreateCallback<D>] ): types.Fn<[], boolean> { if (args.length === 2) { // all creations run on the model identified by `scope` const [location, fn] = args return this.getModel<D>(location).beforeCreate(fn) } else { // all creations run across all defined models const [fn] = args const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach(model => { unsubs[++i] = model.beforeCreate(fn) }) return () => unsubs.every(unsub => unsub()) } } /** * When an object is created, that object is returned to you and the * `afterCreate` hook is called with it. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ afterCreate <D extends types.ReturnDict = types.LooseObject> ( ...args: [hooks.AfterCreateCallback<D>] | [string, hooks.AfterCreateCallback<D>] ): types.Fn<[], boolean> { if (args.length === 2) { // all creations run on the model identified by `scope` const [location, fn] = args return this.getModel<D>(location).afterCreate(fn) } else { // all creations run across all defined models const [fn] = args const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach(model => { unsubs[++i] = model.afterCreate(fn) }) return () => unsubs.every(unsub => unsub()) } } /** * Prior to an object being updated the `beforeUpdate` hook is called with the * update delta, or the incoming changes to be made, as well as the criteria. * * @remarks * Casting occurs after this hook. A subscriber could choose to cancel the * update by returning the EventCancellation symbol or alter the selection * criteria. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ beforeUpdate <D extends types.ReturnDict = types.LooseObject> ( ...args: [hooks.BeforeUpdateCallback<D>] | [string, hooks.BeforeUpdateCallback<D>] ): types.Fn<[], boolean> { if (args.length === 2) { // all updates run on the model identified by `scope` const [location, fn] = args return this.getModel<D>(location).beforeUpdate(fn) } else { // all updates run across all defined models const [fn] = args const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach((model: Model<D>) => { unsubs[++i] = model.beforeUpdate(fn) }) return () => unsubs.every(unsub => unsub()) } } /** * Subscribers to the `afterUpdate` hook receive modified objects after they * are updated. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ afterUpdate <D extends types.ReturnDict = types.LooseObject> ( ...args: [hooks.AfterUpdateCallback<D>] | [string, hooks.AfterUpdateCallback<D>] ): types.Fn<[], boolean> { if (args.length === 2) { // all updates run on the model identified by `scope` const [location, fn] = args return this.getModel<D>(location).afterUpdate(fn) } else { // all updates run across all defined models const [fn] = args const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach(model => { unsubs[++i] = model.afterUpdate(fn) }) return () => unsubs.every(unsub => unsub()) } } /** * Before object removal, the criteria for selecting those objects is passed * to the `beforeRemove` hook. * * @remarks * Casting occurs after this hook. Subscribers can modify the selection * criteria or prevent the removal entirely by returning the `EventCancellation` * symbol. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ beforeRemove <D extends types.ReturnDict = types.LooseObject> ( ...args: [hooks.BeforeRemoveCallback<D>] | [string, hooks.BeforeRemoveCallback<D>] ): types.Fn<[], boolean> { if (args.length === 2) { // all removals run on the model identified by `scope` const [location, fn] = args return this.getModel<D>(location).beforeRemove(fn) } else { // all removals run across all defined models const [fn] = args const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach((model: Model<D>) => { unsubs[++i] = model.beforeRemove(fn) }) return () => unsubs.every(unsub => unsub()) } } /** * A list of any removed objects is passed to the `afterRemove` hook. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ afterRemove <D extends types.ReturnDict = types.LooseObject> ( ...args: [hooks.AfterRemoveCallback<D>] | [string, hooks.AfterRemoveCallback<D>] ): types.Fn<[], boolean> { if (args.length === 2) { // all removals run on the model identified by `scope` const [location, fn] = args return this.getModel<D>(location).afterRemove(fn) } else { // all removals run across all defined models const [fn] = args const unsubs: types.Fn<[], boolean>[] = Array.from(new Array(this._definitions.size)) let i = -1 this._definitions.forEach(model => { unsubs[++i] = model.afterRemove(fn) }) return () => unsubs.every(unsub => unsub()) } } } export { EventCancellation, OnQueryOptions, OnQueryCallback, BeforeCreateCallback, AfterCreateCallback, BeforeUpdateCallback, AfterUpdateCallback, BeforeRemoveCallback, AfterRemoveCallback, HookCallback } from './hooks' export { default as Model } from './model' export * from './types' /** * Initialize a new datastore instance, creating a SQLite database file at * the provided path if it does not yet exist, or reading it if it does. * * @param path File path or `':memory:'` for memory-only storage * @param options Configuration for this trilogy instance */ export const connect = (path: string, options?: types.TrilogyOptions) => new Trilogy(path, options)
the_stack
import { Component } from '../component'; import * as Configuration from '../../configuration'; import { Events, RenderTypes, DividerStatus } from '../../interfaces'; import { Tools } from '../../tools'; import { DOMUtils } from '../../services'; import { get } from 'lodash-es'; // D3 Imports import { min } from 'd3-array'; import { select } from 'd3-selection'; export class Heatmap extends Component { type = 'heatmap'; renderType = RenderTypes.SVG; private matrix = {}; private xBandwidth = 0; private yBandwidth = 0; private translationUnits = { x: 0, y: 0, }; init() { const eventsFragment = this.services.events; // Highlight correct cells on Axis item hovers eventsFragment.addEventListener( Events.Axis.LABEL_MOUSEOVER, this.handleAxisOnHover ); // Highlight correct cells on Axis item mouseouts eventsFragment.addEventListener( Events.Axis.LABEL_MOUSEOUT, this.handleAxisMouseOut ); // Highlight correct cells on Axis item focus eventsFragment.addEventListener( Events.Axis.LABEL_FOCUS, this.handleAxisOnHover ); // Highlight correct cells on Axis item blur eventsFragment.addEventListener( Events.Axis.LABEL_BLUR, this.handleAxisMouseOut ); } render(animate = true) { const svg = this.getComponentContainer({ withinChartClip: true }); // Lower the chart so the axes are always visible svg.lower(); const { cartesianScales } = this.services; this.matrix = this.model.getMatrix(); svg.html(''); if (Tools.getProperty(this.getOptions(), 'data', 'loading')) { return; } // determine x and y axis scale const mainXScale = cartesianScales.getMainXScale(); const mainYScale = cartesianScales.getMainYScale(); const domainIdentifier = cartesianScales.getDomainIdentifier(); const rangeIdentifier = cartesianScales.getRangeIdentifier(); // Get unique axis values & create a matrix const uniqueDomain = this.model.getUniqueDomain(); const uniqueRange = this.model.getUniqueRanges(); // Get matrix in the form of an array to create a single heatmap group const matrixArray = this.model.getMatrixAsArray(); // Get available chart area const xRange = mainXScale.range(); const yRange = mainYScale.range(); // Determine rectangle dimensions based on the number of unique domain and range this.xBandwidth = Math.abs( (xRange[1] - xRange[0]) / uniqueDomain.length ); this.yBandwidth = Math.abs( (yRange[1] - yRange[0]) / uniqueRange.length ); const patternID = this.services.domUtils.generateElementIDString( `heatmap-pattern-stripes` ); // Create a striped pattern for missing data svg.append('defs') .append('pattern') .attr('id', patternID) .attr('width', 3) .attr('height', 3) .attr('patternUnits', 'userSpaceOnUse') .attr('patternTransform', 'rotate(45)') .append('rect') .classed('pattern-fill', true) .attr('width', 0.5) .attr('height', 8); const rectangles = svg .selectAll() .data(matrixArray) .enter() .append('g') .attr('class', (d) => `heat-${d.index}`) .classed('cell', true) .attr( 'transform', (d) => `translate(${mainXScale(d[domainIdentifier])}, ${mainYScale( d[rangeIdentifier] )})` ) .append('rect') .attr('class', (d) => { return this.model.getColorClassName({ value: d.value, originalClassName: `heat-${d.index}`, }); }) .classed('heat', true) .classed('null-state', (d) => d.index === -1 || d.value === null ? true : false ) .attr('width', this.xBandwidth) .attr('height', this.yBandwidth) .style('fill', (d) => { // Check if a valid value exists if (d.index === -1 || d.value === null) { return `url(#${patternID})`; } return this.model.getFillColor(Number(d.value)); }) .attr('aria-label', (d) => d.value); // Cell highlight box this.createOuterBox( 'g.cell-highlight', this.xBandwidth, this.yBandwidth ); // Column highlight box this.createOuterBox( 'g.multi-cell.column-highlight', this.xBandwidth, Math.abs(yRange[1] - yRange[0]) ); // Row highlight box this.createOuterBox( 'g.multi-cell.row-highlight', Math.abs(xRange[1] - xRange[0]), this.yBandwidth ); if (this.determineDividerStatus()) { rectangles.style('stroke-width', '1px'); this.parent.select('g.cell-highlight').classed('cell-2', true); } this.addEventListener(); } /** * Generates a box using lines to create a hover effect * The lines have drop shadow in their respective direction * @param parentTag - tag name * @param xBandwidth - X length * @param yBandwidth - y length */ private createOuterBox(parentTag, xBandwidth, yBandwidth) { // Create a highlighter in the parent component so the shadow and the lines do not get clipped const highlight = DOMUtils.appendOrSelect(this.parent, parentTag) .classed('shadows', true) .classed('highlighter-hidden', true); DOMUtils.appendOrSelect(highlight, 'line.top') .attr('x1', -1) .attr('x2', xBandwidth + 1); DOMUtils.appendOrSelect(highlight, 'line.left') .attr('x1', 0) .attr('y1', -1) .attr('x2', 0) .attr('y2', yBandwidth + 1); DOMUtils.appendOrSelect(highlight, 'line.down') .attr('x1', -1) .attr('x2', xBandwidth + 1) .attr('y1', yBandwidth) .attr('y2', yBandwidth); DOMUtils.appendOrSelect(highlight, 'line.right') .attr('x1', xBandwidth) .attr('x2', xBandwidth) .attr('y1', -1) .attr('y2', yBandwidth + 1); } private determineDividerStatus(): boolean { // Add dividers if status is not off, will assume auto or on by default. const dividerStatus = Tools.getProperty( this.getOptions(), 'heatmap', 'divider', 'state' ); // Determine if cell divider should be displayed if (dividerStatus !== DividerStatus.OFF) { if ( (dividerStatus === DividerStatus.AUTO && Configuration.heatmap.minCellDividerDimension <= this.xBandwidth && Configuration.heatmap.minCellDividerDimension <= this.yBandwidth) || dividerStatus === DividerStatus.ON ) { return true; } } return false; } addEventListener() { const self = this; const { cartesianScales } = this.services; const options = this.getOptions(); const totalLabel = get(options, 'tooltip.totalLabel'); const domainIdentifier = cartesianScales.getDomainIdentifier(); const rangeIdentifier = cartesianScales.getRangeIdentifier(); const domainLabel = cartesianScales.getDomainLabel(); const rangeLabel = cartesianScales.getRangeLabel(); this.parent .selectAll('g.cell') .on('mouseover', function (event, datum) { const cell = select(this); const hoveredElement = cell.select('rect.heat'); const nullState = hoveredElement.classed('null-state'); // Dispatch event and tooltip only if value exists if (!nullState) { // Get transformation value of node const transform = Tools.getTranformOffsets( cell.attr('transform') ); select('g.cell-highlight') .attr( 'transform', `translate(${ transform.x + self.translationUnits.x }, ${transform.y + self.translationUnits.y})` ) .classed('highlighter-hidden', false); // Dispatch mouse over event self.services.events.dispatchEvent( Events.Heatmap.HEATMAP_MOUSEOVER, { event, element: hoveredElement, datum: datum, } ); // Dispatch tooltip show event self.services.events.dispatchEvent(Events.Tooltip.SHOW, { event, items: [ { label: domainLabel, value: datum[domainIdentifier], }, { label: rangeLabel, value: datum[rangeIdentifier], }, { label: totalLabel || 'Total', value: datum['value'], color: hoveredElement.style('fill'), }, ], }); } }) .on('mousemove', function (event, datum) { // Dispatch mouse move event self.services.events.dispatchEvent( Events.Heatmap.HEATMAP_MOUSEMOVE, { event, element: select(this), datum: datum, } ); // Dispatch tooltip move event self.services.events.dispatchEvent(Events.Tooltip.MOVE, { event, }); }) .on('click', function (event, datum) { // Dispatch mouse click event self.services.events.dispatchEvent( Events.Heatmap.HEATMAP_CLICK, { event, element: select(this), datum: datum, } ); }) .on('mouseout', function (event, datum) { const cell = select(this); const hoveredElement = cell.select('rect.heat'); const nullState = hoveredElement.classed('null-state'); select('g.cell-highlight').classed('highlighter-hidden', true); // Dispatch event and tooltip only if value exists if (!nullState) { // Dispatch mouse out event self.services.events.dispatchEvent( Events.Heatmap.HEATMAP_MOUSEOUT, { event, element: hoveredElement, datum: datum, } ); // Dispatch hide tooltip event self.services.events.dispatchEvent(Events.Tooltip.HIDE, { event, hoveredElement, }); } }); } // Highlight elements that match the hovered axis item handleAxisOnHover = (event: CustomEvent) => { const { detail } = event; const { datum } = detail; // Unique ranges and domains const ranges = this.model.getUniqueRanges(); const domains = this.model.getUniqueDomain(); // Labels const domainLabel = this.services.cartesianScales.getDomainLabel(); const rangeLabel = this.services.cartesianScales.getRangeLabel(); // Scales const mainXScale = this.services.cartesianScales.getMainXScale(); const mainYScale = this.services.cartesianScales.getMainYScale(); let label = '', sum = 0, minimum = 0, maximum = 0; // Check to see where datum belongs if (this.matrix[datum] !== undefined) { label = domainLabel; // Iterate through Object and get sum, min, and max ranges.forEach((element) => { let value = this.matrix[datum][element].value || 0; sum += value; minimum = value < minimum ? value : minimum; maximum = value > maximum ? value : maximum; }); } else { label = rangeLabel; domains.forEach((element) => { let value = this.matrix[element][datum].value || 0; sum += value; minimum = value < minimum ? value : minimum; maximum = value > maximum ? value : maximum; }); } if (mainXScale(datum) !== undefined) { this.parent .select('g.multi-cell.column-highlight') .classed('highlighter-hidden', false) .attr( 'transform', `translate(${mainXScale(datum)}, ${min( mainYScale.range() )})` ); } else if (mainYScale(datum) !== undefined) { this.parent .select('g.multi-cell.row-highlight') .classed('highlighter-hidden', false) .attr( 'transform', `translate(${min(mainXScale.range())},${mainYScale(datum)})` ); } // Dispatch tooltip show event this.services.events.dispatchEvent(Events.Tooltip.SHOW, { event: detail.event, hoveredElement: select(event.detail.element), items: [ { label: label, value: datum, bold: true, }, { label: 'Min', value: minimum, }, { label: 'Max', value: maximum, }, { label: 'Average', value: sum / domains.length, }, ], }); }; // Un-highlight all elements handleAxisMouseOut = (event: CustomEvent) => { // Hide column/row this.parent .selectAll('g.multi-cell') .classed('highlighter-hidden', true); // Dispatch hide tooltip event this.services.events.dispatchEvent(Events.Tooltip.HIDE, { event, }); }; // Remove event listeners destroy() { this.parent .selectAll('rect.heat') .on('mouseover', null) .on('mousemove', null) .on('click', null) .on('mouseout', null); // Remove legend listeners const eventsFragment = this.services.events; eventsFragment.removeEventListener( Events.Legend.ITEM_HOVER, this.handleAxisOnHover ); eventsFragment.removeEventListener( Events.Legend.ITEM_MOUSEOUT, this.handleAxisMouseOut ); } }
the_stack
import * as util from 'oav/dist/lib/generator/util' import { CacheItem, MockerCache, PayloadCache, buildItemOption, createLeafItem, createTrunkItem, reBuildExample } from 'oav/dist/lib/generator/exampleCache' import { ExampleRule, getRuleValidator } from 'oav/dist/lib/generator/exampleRule' import { JsonLoader } from 'oav/dist/lib/swagger/jsonLoader' import { LiveRequest } from 'oav/dist/lib/liveValidation/operationValidator' import { SpecItem } from '../responser' import { logger } from '../../common/utils' import { parse as parseUrl } from 'url' import Mocker from './mocker' export default class SwaggerMocker { private jsonLoader: JsonLoader private mocker: Mocker private spec: any private mockCache: MockerCache private exampleCache: PayloadCache private exampleRule?: ExampleRule public constructor( jsonLoader: JsonLoader, mockerCache: MockerCache, payloadCache: PayloadCache ) { this.jsonLoader = jsonLoader this.mocker = new Mocker() this.mockCache = mockerCache this.exampleCache = payloadCache } public setRule(exampleRule?: ExampleRule) { this.exampleRule = exampleRule } public mockForExample( example: any, specItem: SpecItem, spec: any, rp: string, liveRequest: LiveRequest ) { this.spec = spec if (Object.keys(example.responses).length === 0) { for (const statusCode of Object.keys(specItem.content.responses)) { if (statusCode !== 'default') { example.responses[`${statusCode}`] = {} } } } example.parameters = this.mockRequest(example.parameters, specItem.content.parameters, rp) example.responses = this.mockResponse(example.responses, specItem) this.patchResourceId(example.responses, liveRequest) this.patchUserAssignedIdentities(example.responses, liveRequest) } /** * Replaces mock resource IDs with IDs that match current resource. */ private patchResourceId(responses: any, liveRequest: LiveRequest) { const url = parseUrl(liveRequest.url) Object.keys(responses).forEach((key) => { if (responses[key]?.body?.id) { // put if (liveRequest.method.toLowerCase() === 'put') { responses[key].body.id = url.pathname } // get(get) or patch if ( liveRequest.method.toLowerCase() === 'get' || liveRequest.method.toLowerCase() === 'patch' ) { responses[key].body.id = url.pathname } } // get(list) if (responses[key]?.body?.value?.length) { responses[key]?.body?.value?.forEach((item: any) => { if (item.id) { const resourceName = item.name || 'resourceName' url.pathname = `${url.pathname}/${resourceName}` item.id = url.pathname } }) } }) } public static flattenPath(path: string): Record<string, string> { const items = path.split('/') const ret: Record<string, string> = {} for (let i = 2; i < items.length; i += 2) { if (items[i].length > 0) ret[items[i - 1].toLowerCase()] = items[i] } return ret } public static mockUserAssignedIdentities( obj: any, pathElements: Record<string, string>, inUserAssignedIdentities = false ): any { if (Array.isArray(obj)) { return obj.map((x) => this.mockUserAssignedIdentities(x, pathElements)) } else if (typeof obj === 'object') { const ret: Record<string, any> = {} // eslint-disable-next-line prefer-const for (let [key, item] of Object.entries(obj)) { if (inUserAssignedIdentities) { const subscription = pathElements.subscriptions || '00000000-0000-0000-0000-000000000000' const resourceGroup = pathElements.subscriptions || 'mockGroup' key = `/subscriptions/${subscription}/resourceGroups/${resourceGroup}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/${key}` } ret[key] = this.mockUserAssignedIdentities( item, pathElements, key.toLowerCase() === 'userassignedidentities' ) } return ret } return obj } private patchUserAssignedIdentities(responses: any, liveRequest: LiveRequest) { const url = parseUrl(liveRequest.url) const pathElements = SwaggerMocker.flattenPath(url.pathname!) Object.keys(responses).forEach((key) => { if (responses[key]?.body) { responses[key].body = SwaggerMocker.mockUserAssignedIdentities( responses[key].body, pathElements, false ) } }) } public getMockCachedObj(objName: string, schema: any, isRequest: boolean) { return this.mockCachedObj(objName, schema, undefined, new Set<string>(), isRequest) } private mockResponse(responseExample: any, specItem: any) { for (const statusCode of Object.keys(responseExample)) { const mockedResp = this.mockEachResponse( statusCode, responseExample[statusCode], specItem ) responseExample[statusCode] = mockedResp } return responseExample } private mockEachResponse(statusCode: string, responseExample: any, specItem: any) { const visited = new Set<string>() const validator = getRuleValidator(this.exampleRule).onResponseBody const responseSpec = specItem.content.responses[statusCode] if (validator && !validator({ schema: responseSpec })) { return undefined } return { headers: responseExample.hearders || this.mockHeaders(statusCode, specItem), body: 'schema' in responseSpec ? this.mockObj( 'response body', responseSpec.schema, responseExample.body || {}, visited, false ) || {} : undefined } } private mockHeaders(statusCode: string, specItem: any) { if (statusCode !== '201' && statusCode !== '202') { return undefined } const validator = getRuleValidator(this.exampleRule).onResponseHeader if (validator && !validator({ schema: specItem })) { return undefined } const headerAttr = util.getPollingAttr(specItem) if (!headerAttr) { return } return { [headerAttr]: 'LocationURl' } } private mockRequest(paramExample: any, paramSpec: any, rp: string) { const validator = getRuleValidator(this.exampleRule).onParameter for (const pName of Object.keys(paramSpec)) { const element = paramSpec[pName] const visited = new Set<string>() const paramEle = this.getDefSpec(element, visited) if (paramEle.name === 'resourceGroupName') { paramExample.resourceGroupName = `rg${rp}` } else if (paramEle.name === 'api-version') { paramExample['api-version'] = this.spec.info.version } else if ('schema' in paramEle) { // { // "name": "parameters", // "in": "body", // "required": false, // "schema": { // "$ref": "#/definitions/SignalRResource" // } // } if (!validator || validator({ schema: paramEle })) { paramExample[paramEle.name] = this.mockObj( paramEle.name, paramEle.schema, paramExample[paramEle.name] || {}, visited, true ) } } else { if (paramEle.name in paramExample) { continue } // { // "name": "api-version", // "in": "query", // "required": true, // "type": "string" // } if (!validator || validator({ schema: paramEle })) { paramExample[paramEle.name] = this.mockObj( paramEle.name, element, // use the original schema containing "$ref" which will hit the cached value paramExample[paramEle.name], new Set<string>(), true ) } } } return paramExample } private removeFromSet(schema: any, visited: Set<string>) { if ('$ref' in schema && visited.has(schema.$ref)) { visited.delete(schema.$ref) } } private getCache(schema: any) { if ('$ref' in schema) { for (const cache of [this.exampleCache, this.mockCache]) { if (cache.has(schema.$ref.split('#')[1])) { return cache.get(schema.$ref.split('#')[1]) } } } return undefined } private mockObj( objName: string, schema: any, example: any, visited: Set<string>, isRequest: boolean ) { const cache = this.mockCachedObj(objName, schema, example, visited, isRequest) const validator = getRuleValidator(this.exampleRule).onSchema return reBuildExample(cache, isRequest, schema, validator) } private mockCachedObj( objName: string, schema: any, example: any, visited: Set<string>, isRequest: boolean, discriminatorValue: string | undefined = undefined ) { if (!schema || typeof schema !== 'object') { logger.warn(`invalid schema.`) return undefined } // use visited set to avoid circular dependency if ('$ref' in schema && visited.has(schema.$ref)) { return undefined } const cache = this.getCache(schema) if (cache) { return cache } const definitionSpec = this.getDefSpec(schema, visited) if (util.isObject(definitionSpec)) { // circular inherit will not be handled const properties = this.getProperties(definitionSpec, visited) example = example || {} const discriminator = this.getDiscriminator(definitionSpec, visited) if ( discriminator && !discriminatorValue && properties && Object.keys(properties).includes(discriminator) ) { return ( this.mockForDiscriminator( definitionSpec, example, discriminator, isRequest, visited ) || undefined ) } else { Object.keys(properties).forEach((key: string) => { // the objName is the discriminator when discriminatorValue is specified. if (key === objName && discriminatorValue) { example[key] = createLeafItem( discriminatorValue, buildItemOption(properties[key]) ) } else { example[key] = this.mockCachedObj( key, properties[key], example[key], visited, isRequest, discriminatorValue ) } }) } if ('additionalProperties' in definitionSpec && definitionSpec.additionalProperties) { const newKey = util.randomKey() if (newKey in properties) { logger.error(`generate additionalProperties for ${objName} fail`) } else { example[newKey] = this.mockCachedObj( newKey, definitionSpec.additionalProperties, undefined, visited, isRequest, discriminatorValue ) } } } else if (definitionSpec.type === 'array') { example = example || [] const arrItem: any = this.mockCachedObj( `${objName}'s item`, definitionSpec.items, example[0], visited, isRequest ) example = this.mocker.mock(definitionSpec, objName, arrItem) } else { /** type === number or integer */ example = example ? example : this.mocker.mock(definitionSpec, objName) } // return value for primary type: string, number, integer, boolean // "aaaa" // removeFromSet: once we try all roads started from present node, we should remove it and backtrack this.removeFromSet(schema, visited) let cacheItem: CacheItem if (Array.isArray(example)) { const cacheChild: CacheItem[] = [] for (const item of example) { cacheChild.push(item) } cacheItem = createTrunkItem(cacheChild, buildItemOption(definitionSpec)) } else if (typeof example === 'object') { const cacheChild: { [index: string]: CacheItem } = {} for (const [key, item] of Object.entries(example)) { cacheChild[key] = item as CacheItem } cacheItem = createTrunkItem(cacheChild, buildItemOption(definitionSpec)) } else { cacheItem = createLeafItem(example, buildItemOption(definitionSpec)) } cacheItem.isMocked = true const requiredProperties = this.getRequiredProperties(definitionSpec) if (requiredProperties && requiredProperties.length > 0) { cacheItem.required = requiredProperties } this.mockCache.checkAndCache(schema, cacheItem) return cacheItem } /** * return all required properties of the object, including parent's properties defined by 'allOf' * It will not spread properties' properties. * @param definitionSpec */ private getRequiredProperties(definitionSpec: any) { let requiredProperties: string[] = Array.isArray(definitionSpec.required) ? definitionSpec.required : [] definitionSpec.allOf?.map((item: any) => { requiredProperties = [ ...requiredProperties, ...this.getRequiredProperties(this.getDefSpec(item, new Set<string>())) ] }) return requiredProperties } // TODO: handle discriminator without enum options private mockForDiscriminator( schema: any, example: any, discriminator: string, isRequest: boolean, visited: Set<string> ): any { const disDetail = this.getDefSpec(schema, visited) if (disDetail.discriminatorMap && Object.keys(disDetail.discriminatorMap).length > 0) { const properties = this.getProperties(disDetail, new Set<string>()) let discriminatorValue if (properties[discriminator] && Array.isArray(properties[discriminator].enum)) { discriminatorValue = properties[discriminator].enum[0] } else { discriminatorValue = Object.keys(disDetail.discriminatorMap)[0] } const discriminatorSpec = disDetail.discriminatorMap[discriminatorValue] if (!discriminatorSpec) { this.removeFromSet(schema, visited) return example } const cacheItem = this.mockCachedObj( discriminator, discriminatorSpec, {}, new Set<string>(), isRequest, discriminatorValue ) || undefined this.removeFromSet(schema, visited) return cacheItem } this.removeFromSet(schema, visited) return undefined } // { // "$ref": "#/parameters/ApiVersionParameter" // }, // to // { // "name": "api-version", // "in": "query", // "required": true, // "type": "string" // } private getDefSpec(schema: any, visited: Set<string>) { if ('$ref' in schema) { visited.add(schema.$ref) } const content = this.jsonLoader.resolveRefObj(schema) if (!content) { return undefined } return content } private getProperties(definitionSpec: any, visited: Set<string>) { let properties: any = {} definitionSpec.allOf?.map((item: any) => { properties = { ...properties, ...this.getProperties(this.getDefSpec(item, visited), visited) } this.removeFromSet(item, visited) }) return { ...properties, ...definitionSpec.properties } } private getDiscriminator(definitionSpec: any, visited: Set<string>) { let discriminator = undefined if (definitionSpec.discriminator) { return definitionSpec.discriminator } definitionSpec.allOf?.some((item: any) => { discriminator = this.getDiscriminator(this.getDefSpec(item, visited), visited) this.removeFromSet(item, visited) return !!discriminator }) return discriminator } }
the_stack
import * as Types from '../../constants/types/signup' import * as Constants from '../../constants/signup' import * as SignupGen from '../signup-gen' import {TypedState} from '../../constants/reducer' import HiddenString from '../../util/hidden-string' import {SagaLogger} from '../../util/saga' import {RPCError} from '../../util/errors' import * as RouteTreeGen from '../route-tree-gen' import {_testing} from '../signup' import reducer from '../../reducers/signup' const testLogger = new SagaLogger('TESTING' as any, 'TESTINGFCN') const makeTypedState = (signupState: Types.State): TypedState => ({signup: signupState} as any) describe('goBackAndClearErrors', () => { it('errors get cleaned and we go back a level', () => { const state = { ...Constants.makeState(), devicenameError: 'bad name', emailError: 'bad email', inviteCodeError: 'bad invite', nameError: 'bad name', signupError: new RPCError('bad signup', 0), usernameError: 'bad username', } const action = SignupGen.createGoBackAndClearErrors() const nextState = {signup: reducer(state, action)} expect(nextState.signup.devicenameError).toEqual('') expect(nextState.signup.emailError).toEqual('') expect(nextState.signup.inviteCodeError).toEqual('') expect(nextState.signup.nameError).toEqual('') expect(nextState.signup.signupError).toEqual(undefined) expect(nextState.signup.usernameError).toEqual('') expect(_testing.goBackAndClearErrors()).toEqual(RouteTreeGen.createNavigateUp()) }) }) describe('requestAutoInvite', () => { const state = Constants.makeState() it('makes a call to get an auto invite', () => { const action = SignupGen.createRequestAutoInvite() const nextState = makeTypedState(reducer(state, action)) expect(nextState).toEqual(makeTypedState(state)) }) it('fills inviteCode, shows invite screen', () => { const action = SignupGen.createRequestedAutoInvite({inviteCode: 'hello world'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.inviteCode).toEqual(action.payload.inviteCode) expect(_testing.showInviteScreen()).toEqual( RouteTreeGen.createNavigateAppend({path: ['signupInviteCode']}) ) }) it('goes to invite page on error', () => { const action = SignupGen.createRequestedAutoInvite({}) const nextState = makeTypedState(reducer(state, action)) expect(nextState).toEqual(makeTypedState(state)) expect(_testing.showInviteScreen()).toEqual( RouteTreeGen.createNavigateAppend({path: ['signupInviteCode']}) ) }) }) describe('requestInvite', () => { it('ignores if theres an error', () => { const state = {...Constants.makeState(), devicenameError: 'has an error'} const action = SignupGen.createRequestInvite({email: 'email@email.com', name: 'name'}) const nextState = makeTypedState(reducer(state, action)) expect(_testing.showInviteSuccessOnNoErrors(nextState)).toEqual(false) }) const state = Constants.makeState() it('saves email/name in store, shows invite success', () => { const action = SignupGen.createRequestInvite({email: 'email@email.com', name: 'name'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.email).toEqual(action.payload.email) expect(nextState.signup.name).toEqual(action.payload.name) expect(_testing.showInviteSuccessOnNoErrors(nextState)).toEqual( RouteTreeGen.createNavigateAppend({path: ['signupRequestInviteSuccess']}) ) }) it('shows error if it matches', () => { const preAction = SignupGen.createRequestInvite({email: 'email@email.com', name: 'name'}) const preNextState = makeTypedState(reducer(state, preAction)) const action = SignupGen.createRequestedInvite({ email: preNextState.signup.email, emailError: 'email error', name: preNextState.signup.name, nameError: 'name error', }) const nextState = makeTypedState(reducer(preNextState.signup, action)) expect(nextState.signup.emailError).toEqual(action.payload.emailError) expect(nextState.signup.nameError).toEqual(action.payload.nameError) }) it("ignore error if it doesn't match", () => { const preAction = SignupGen.createRequestInvite({email: 'email@email.com', name: 'name'}) const preNextState = makeTypedState(reducer(state, preAction)) const action = SignupGen.createRequestedInvite({ email: 'different email', emailError: 'email error', name: preNextState.signup.name, nameError: 'name error', }) const nextState = makeTypedState(reducer(preNextState.signup, action)) expect(nextState).toEqual(preNextState) }) }) describe('checkInviteCode', () => { const state = Constants.makeState() it('checks requestedAutoInvite', () => { const action = SignupGen.createRequestedAutoInvite({inviteCode: 'invite code'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.inviteCode).toEqual(action.payload.inviteCode) }) it('checks checkInviteCode', () => { const action = SignupGen.createCheckInviteCode({inviteCode: 'invite code'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.inviteCode).toEqual(action.payload.inviteCode) }) it('shows user email page on success', () => { const action = SignupGen.createCheckedInviteCode({inviteCode: 'working'}) const nextState = makeTypedState(reducer(state, action)) // leaves state alone expect(nextState).toEqual(makeTypedState(state)) // expect(_testing.showUserOnNoErrors(nextState)).toEqual( // RouteTreeGen.createNavigateAppend({ path: ['signupUsernameAndEmail']}) // ) }) it("shows error on fail: must match invite code. doesn't go to next screen", () => { const preAction = SignupGen.createRequestedAutoInvite({inviteCode: 'invite code'}) const preState = makeTypedState(reducer(state, preAction)) const action = SignupGen.createCheckedInviteCode({ error: 'bad invitecode', inviteCode: 'invite code', }) const nextState = makeTypedState(reducer(preState.signup, action)) expect(nextState.signup.inviteCodeError).toEqual(action.payload.error) expect(_testing.showUserOnNoErrors(nextState)).toEqual(false) }) it("ignores error if invite doesn't match", () => { const preAction = SignupGen.createRequestedAutoInvite({inviteCode: 'a different invite code'}) const preState = makeTypedState(reducer(state, preAction)) const action = SignupGen.createCheckedInviteCode({ error: 'bad invitecode', inviteCode: 'invite code', }) const nextState = makeTypedState(reducer(preState.signup, action)) expect(nextState).toEqual(preState) }) }) describe('checkUsername', () => { it("ignores if there's an error", () => { const state = {...Constants.makeState(), inviteCodeError: 'invite error'} expect(_testing.checkUsername(makeTypedState(state), null as any, testLogger)).resolves.toEqual(false) }) it('Updates store on success', () => { const state = Constants.makeState() const action = SignupGen.createCheckUsername({username: 'username'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.username).toEqual(action.payload.username) }) it('Locally checks simple problems', () => { const state = Constants.makeState() const action = SignupGen.createCheckUsername({username: 'a.bad.username'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.usernameError).toBeTruthy() expect(nextState.signup.username).toEqual(action.payload.username) }) }) describe('checkedUsername', () => { it("ignores if username doesn't match", () => { const state = {...Constants.makeState(), username: 'username'} const action = SignupGen.createCheckedUsername({ error: 'another problem', username: 'different username', }) const nextState = makeTypedState(reducer(state, action)) // doesn't update expect(nextState).toEqual(makeTypedState(state)) }) it('shows error', () => { const state = {...Constants.makeState(), username: 'username'} const action = SignupGen.createCheckedUsername({ error: 'another problem', username: state.username, }) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.usernameError).toEqual(action.payload.error) }) it('shows device name page on success', () => { const state = {...Constants.makeState(), username: 'username'} const action = SignupGen.createCheckedUsername({ error: '', username: state.username, }) const nextState = makeTypedState(reducer(state, action)) expect(_testing.showDeviceScreenOnNoErrors(nextState)).toEqual( RouteTreeGen.createNavigateAppend({path: ['signupEnterDevicename']}) ) }) }) describe('checkPassword', () => { it('passes must equal', () => { const state = Constants.makeState() const action = SignupGen.createCheckPassword({ pass1: new HiddenString('aaaaaaaaaaa'), pass2: new HiddenString('bbbbbbbbbb'), }) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.passwordError.stringValue()).toEqual('Passwords must match') }) it('passes must be long enough', () => { const state = Constants.makeState() const action = SignupGen.createCheckPassword({ pass1: new HiddenString('12345'), pass2: new HiddenString('12345'), }) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.passwordError.stringValue()).toEqual( 'Password must be at least 8 characters long' ) }) it('passes must have values', () => { const state = Constants.makeState() const action = SignupGen.createCheckPassword({pass1: new HiddenString(''), pass2: new HiddenString('')}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.passwordError.stringValue()).toEqual('Fields cannot be blank') }) it('passes get updated', () => { const state = Constants.makeState() const action = SignupGen.createCheckPassword({ pass1: new HiddenString('123456abcd'), pass2: new HiddenString('123456abcd'), }) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.passwordError.stringValue()).toEqual('') expect(nextState.signup.password.stringValue()).toEqual(action.payload.pass1.stringValue()) expect(nextState.signup.password.stringValue()).toEqual(action.payload.pass2.stringValue()) }) }) describe('deviceScreen', () => { it('trims name', () => { const state = Constants.makeState() const action = SignupGen.createCheckDevicename({devicename: ' a name \n'}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.devicename).toEqual('a name') }) it("ignores if devicename doesn't match", () => { const state = {...Constants.makeState(), devicename: 'a device'} const action = SignupGen.createCheckedDevicename({devicename: 'different name', error: 'an error'}) const nextState = makeTypedState(reducer(state, action)) // doesn't update expect(nextState).toEqual(makeTypedState(state)) }) it('shows error', () => { const state = {...Constants.makeState(), devicename: 'devicename'} const action = SignupGen.createCheckedDevicename({devicename: 'devicename', error: 'an error'}) const nextState = makeTypedState(reducer(makeTypedState(state).signup, action)) expect(nextState.signup.devicename).toEqual(action.payload.devicename) expect(nextState.signup.devicenameError).toEqual(action.payload.error) }) }) describe('actually sign up', () => { it('bails on devicenameError', () => { const state = {...Constants.makeState(), devicenameError: 'error'} expect(_testing.reallySignupOnNoErrors(makeTypedState(state)).next().value).toBeUndefined() }) it('bails on emailError', () => { const state = {...Constants.makeState(), emailError: 'error'} expect(_testing.reallySignupOnNoErrors(makeTypedState(state)).next().value).toBeUndefined() }) it('bails on inviteCodeError', () => { const state = {...Constants.makeState(), inviteCodeError: 'error'} expect(_testing.reallySignupOnNoErrors(makeTypedState(state)).next().value).toBeUndefined() }) it('bails on nameError', () => { const state = {...Constants.makeState(), nameError: 'error'} expect(_testing.reallySignupOnNoErrors(makeTypedState(state)).next().value).toBeUndefined() }) it('bails on usernameError', () => { const state = {...Constants.makeState(), usernameError: 'error'} expect(_testing.reallySignupOnNoErrors(makeTypedState(state)).next().value).toBeUndefined() }) it('bails on signupError', () => { const state = {...Constants.makeState(), signupError: new RPCError('error', 0)} expect(_testing.reallySignupOnNoErrors(makeTypedState(state)).next().value).toBeUndefined() }) const validSignup = { ...Constants.makeState(), devicename: 'a valid devicename', inviteCode: '1234566', username: 'testuser', } const signupError = new Error('Missing data for signup') it('bails on missing devicename', () => { expect(() => _testing.reallySignupOnNoErrors(makeTypedState({...validSignup, devicename: ''})).next() ).toThrow(signupError) }) it('bails on missing inviteCode', () => { expect(() => _testing.reallySignupOnNoErrors(makeTypedState({...validSignup, inviteCode: ''})).next() ).toThrow(signupError) }) it('bails on missing username', () => { expect(() => _testing.reallySignupOnNoErrors(makeTypedState({...validSignup, username: ''})).next() ).toThrow(signupError) }) it('updates error', () => { const state = Constants.makeState() const action = SignupGen.createSignedup({error: new RPCError('an error', 0)}) const nextState = makeTypedState(reducer(state, action)) expect(nextState.signup.signupError).toEqual(action.payload.error) expect(_testing.showErrorOrCleanupAfterSignup(nextState)).toEqual( RouteTreeGen.createNavigateAppend({path: ['signupError']}) ) }) it('after signup cleanup', () => { const state = Constants.makeState() const action = SignupGen.createSignedup() const nextState = makeTypedState(reducer(state, action)) expect(_testing.showErrorOrCleanupAfterSignup(nextState)).toEqual(SignupGen.createRestartSignup()) }) })
the_stack
import { data } from "./network"; import engine, { setupHelpers, updateCameraMode, focusActor } from "./engine"; import { Node } from "../../data/SceneNodes"; import { Component } from "../../data/SceneComponents"; import * as TreeView from "dnd-tree-view"; import * as ResizeHandle from "resize-handle"; const THREE = SupEngine.THREE; const ui: { canvasElt: HTMLCanvasElement; treeViewElt: HTMLDivElement; nodesTreeView: TreeView; newActorButton: HTMLButtonElement; newPrefabButton: HTMLButtonElement; renameNodeButton: HTMLButtonElement; duplicateNodeButton: HTMLButtonElement; deleteNodeButton: HTMLButtonElement; inspectorElt: HTMLDivElement; inspectorTbodyElt: HTMLTableSectionElement; transform: { positionElts: HTMLInputElement[]; orientationElts: HTMLInputElement[]; scaleElts: HTMLInputElement[]; }; visibleCheckbox: HTMLInputElement; layerSelect: HTMLSelectElement; prefabRow: HTMLTableRowElement; prefabInput: HTMLInputElement; prefabOpenElt: HTMLButtonElement; availableComponents: { [name: string]: string }; componentEditors: { [id: string]: { destroy(): void; config_setProperty(path: string, value: any): void; } }; newComponentButton: HTMLButtonElement; componentsElt: HTMLDivElement; cameraMode: string; cameraModeButton: HTMLButtonElement; cameraVerticalAxis: string; cameraVerticalAxisButton: HTMLButtonElement; cameraSpeedSlider: HTMLInputElement; camera2DZ: HTMLInputElement; gridCheckbox: HTMLInputElement; gridSize: number; gridStep: number; dropTimeout: NodeJS.Timer; actorDropElt: HTMLDivElement; componentDropElt: HTMLDivElement; } = {} as any; export default ui; // Hotkeys document.addEventListener("keydown", (event) => { if (document.querySelector(".dialog") != null) return; let activeElement = document.activeElement as HTMLElement; while (activeElement != null) { if (activeElement === ui.canvasElt || activeElement === ui.treeViewElt) break; activeElement = activeElement.parentElement; } if (activeElement == null) return; if (event.keyCode === 78 && (event.ctrlKey || event.metaKey)) { // Ctrl+N event.preventDefault(); event.stopPropagation(); onNewNodeClick(); } if (event.keyCode === 80 && (event.ctrlKey || event.metaKey)) { // Ctrl+P event.preventDefault(); event.stopPropagation(); onNewPrefabClick(); } if (event.keyCode === 113) { // F2 event.preventDefault(); event.stopPropagation(); onRenameNodeClick(); } if (event.keyCode === 68 && (event.ctrlKey || event.metaKey)) { // Ctrl+D event.preventDefault(); event.stopPropagation(); onDuplicateNodeClick(); } if (event.keyCode === 46) { // Delete event.preventDefault(); event.stopPropagation(); onDeleteNodeClick(); } }); const ignoredTagNames = [ "INPUT", "TEXTAREA", "SELECT", "BUTTON" ]; document.addEventListener("keydown", (event) => { if (document.querySelector("body > .dialog") != null) return; if (ignoredTagNames.indexOf((event.target as HTMLInputElement).tagName) !== -1) return; switch (event.keyCode) { case (window as any).KeyEvent.DOM_VK_E: (document.getElementById(`transform-mode-translate`) as HTMLInputElement).checked = true; engine.transformHandleComponent.setMode("translate"); break; case (window as any).KeyEvent.DOM_VK_R: (document.getElementById(`transform-mode-rotate`) as HTMLInputElement).checked = true; engine.transformHandleComponent.setMode("rotate"); break; case (window as any).KeyEvent.DOM_VK_T: (document.getElementById(`transform-mode-scale`) as HTMLInputElement).checked = true; engine.transformHandleComponent.setMode("scale"); break; case (window as any).KeyEvent.DOM_VK_L: const localElt = document.getElementById(`transform-space`) as HTMLInputElement; localElt.checked = !localElt.checked; engine.transformHandleComponent.setSpace(localElt.checked ? "local" : "world"); break; case (window as any).KeyEvent.DOM_VK_G: ui.gridCheckbox.checked = !ui.gridCheckbox.checked; engine.gridHelperComponent.setVisible(ui.gridCheckbox.checked); break; case (window as any).KeyEvent.DOM_VK_F: if (ui.nodesTreeView.selectedNodes.length !== 1) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; focusActor(nodeId); break; } }); ui.canvasElt = document.querySelector("canvas") as HTMLCanvasElement; ui.actorDropElt = document.querySelector(".render-area .drop-asset-container") as HTMLDivElement; ui.componentDropElt = document.querySelector(".transform-area .drop-asset-container") as HTMLDivElement; // Setup resizable panes new ResizeHandle(document.querySelector(".sidebar") as HTMLElement, "right"); new ResizeHandle(document.querySelector(".nodes-tree-view") as HTMLElement, "top"); // Setup tree view ui.treeViewElt = document.querySelector(".nodes-tree-view") as HTMLDivElement; ui.nodesTreeView = new TreeView(ui.treeViewElt, { dragStartCallback: () => true, dropCallback: onNodesTreeViewDrop }); ui.nodesTreeView.on("activate", onNodeActivate); ui.nodesTreeView.on("selectionChange", () => { setupSelectedNode(); }); ui.newActorButton = document.querySelector("button.new-actor") as HTMLButtonElement; ui.newActorButton.addEventListener("click", onNewNodeClick); ui.newPrefabButton = document.querySelector("button.new-prefab") as HTMLButtonElement; ui.newPrefabButton.addEventListener("click", onNewPrefabClick); ui.renameNodeButton = document.querySelector("button.rename-node") as HTMLButtonElement; ui.renameNodeButton.addEventListener("click", onRenameNodeClick); ui.duplicateNodeButton = document.querySelector("button.duplicate-node") as HTMLButtonElement; ui.duplicateNodeButton.addEventListener("click", onDuplicateNodeClick); ui.deleteNodeButton = document.querySelector("button.delete-node") as HTMLButtonElement; ui.deleteNodeButton.addEventListener("click", onDeleteNodeClick); // Inspector ui.inspectorElt = document.querySelector(".inspector") as HTMLDivElement; ui.inspectorTbodyElt = ui.inspectorElt.querySelector("tbody") as HTMLTableSectionElement; ui.transform = { positionElts: ui.inspectorElt.querySelectorAll(".transform .position input") as any, orientationElts: ui.inspectorElt.querySelectorAll(".transform .orientation input") as any, scaleElts: ui.inspectorElt.querySelectorAll(".transform .scale input") as any, }; ui.visibleCheckbox = ui.inspectorElt.querySelector(".visible input") as HTMLInputElement; ui.visibleCheckbox.addEventListener("change", onVisibleChange); ui.layerSelect = ui.inspectorElt.querySelector(".layer select") as HTMLSelectElement; ui.layerSelect.addEventListener("change", onLayerChange); ui.prefabRow = ui.inspectorElt.querySelector(".prefab") as HTMLTableRowElement; ui.prefabInput = ui.inspectorElt.querySelector(".prefab input") as HTMLInputElement; ui.prefabInput.addEventListener("input", onPrefabInput); ui.prefabOpenElt = ui.inspectorElt.querySelector(".prefab button") as HTMLButtonElement; ui.prefabOpenElt.addEventListener("click", (event) => { const selectedNode = ui.nodesTreeView.selectedNodes[0]; const node = data.sceneUpdater.sceneAsset.nodes.byId[selectedNode.dataset["id"]]; const id = node.prefab.sceneAssetId; SupClient.openEntry(id); }); for (const transformType in ui.transform) { const inputs: HTMLInputElement[] = (ui.transform as any)[transformType]; for (const input of inputs) input.addEventListener("change", onTransformInputChange); } ui.newComponentButton = document.querySelector("button.new-component") as HTMLButtonElement; ui.newComponentButton.addEventListener("click", onNewComponentClick); ui.cameraMode = "3D"; ui.cameraModeButton = document.getElementById("toggle-camera-button") as HTMLButtonElement; ui.cameraModeButton.addEventListener("click", onChangeCameraMode); ui.cameraVerticalAxis = "Y"; ui.cameraVerticalAxisButton = document.getElementById("toggle-camera-vertical-axis") as HTMLButtonElement; ui.cameraVerticalAxisButton.addEventListener("click", onChangeCameraVerticalAxis); ui.cameraSpeedSlider = document.getElementById("camera-speed-slider") as HTMLInputElement; ui.cameraSpeedSlider.addEventListener("input", onChangeCameraSpeed); ui.cameraSpeedSlider.value = engine.cameraControls.movementSpeed; ui.camera2DZ = document.getElementById("camera-2d-z") as HTMLInputElement; ui.camera2DZ.addEventListener("input", onChangeCamera2DZ); document.querySelector(".main .controls .transform-mode").addEventListener("click", onTransformModeClick); ui.componentsElt = ui.inspectorElt.querySelector(".components") as HTMLDivElement; ui.availableComponents = {}; let componentEditorPlugins: { [pluginName: string]: { path: string; content: SupClient.ComponentEditorPlugin; } }; export function start() { componentEditorPlugins = SupClient.getPlugins<SupClient.ComponentEditorPlugin>("componentEditors"); SupClient.setupHelpCallback(() => { window.parent.postMessage({ type: "openTool", name: "documentation", state: { section: "scene" } }, window.location.origin); }); const componentTypes = Object.keys(componentEditorPlugins); componentTypes.sort((a, b) => { const componentLabelA = SupClient.i18n.t(`componentEditors:${a}.label`); const componentLabelB = SupClient.i18n.t(`componentEditors:${b}.label`); return componentLabelA.localeCompare(componentLabelB); }); for (const componentType of componentTypes) ui.availableComponents[componentType] = SupClient.i18n.t(`componentEditors:${componentType}.label`); document.addEventListener("dragover", onDragOver); document.addEventListener("drop", onStopDrag); ui.actorDropElt.addEventListener("dragenter", onActorDragEnter); ui.actorDropElt.addEventListener("dragleave", onActorDragLeave); ui.actorDropElt.addEventListener("drop", onActorDrop); ui.componentDropElt.addEventListener("dragenter", onComponentDragEnter); ui.componentDropElt.addEventListener("dragleave", onComponentDragLeave); ui.componentDropElt.addEventListener("drop", onComponentDrop); (document.querySelector(".main .loading") as HTMLDivElement).hidden = true; (document.querySelector(".main .controls") as HTMLDivElement).hidden = false; (document.querySelector(".render-area") as HTMLDivElement).hidden = false; ui.newActorButton.disabled = false; ui.newPrefabButton.disabled = false; } // Transform function onTransformModeClick(event: any) { if (event.target.tagName !== "INPUT") return; if (event.target.id === "transform-space") { engine.transformHandleComponent.setSpace(event.target.checked ? "local" : "world"); } else { const transformSpaceCheckbox = document.getElementById("transform-space") as HTMLInputElement; transformSpaceCheckbox.disabled = event.target.value === "scale"; engine.transformHandleComponent.setMode(event.target.value); } } // Grid ui.gridCheckbox = document.getElementById("grid-visible") as HTMLInputElement; ui.gridCheckbox.addEventListener("change", onGridVisibleChange); ui.gridSize = 80; ui.gridStep = 1; document.getElementById("grid-step").addEventListener("input", onGridStepInput); function onGridStepInput(event: UIEvent) { const target = event.target as HTMLInputElement; let value = parseFloat(target.value); if (value !== 0 && value < 0.0001) { value = 0; target.value = "0"; } if (isNaN(value) || value <= 0) { (target as any).reportValidity(); return; } ui.gridStep = value; engine.gridHelperComponent.setup(ui.gridSize, ui.gridStep); } function onGridVisibleChange(event: UIEvent) { engine.gridHelperComponent.setVisible((event.target as HTMLInputElement).checked); } // Light document.getElementById("show-light").addEventListener("change", (event: any) => { if (event.target.checked) engine.gameInstance.threeScene.add(engine.ambientLight); else engine.gameInstance.threeScene.remove(engine.ambientLight); }); export function createNodeElement(node: Node) { const liElt = document.createElement("li"); liElt.dataset["id"] = node.id; const nameSpan = document.createElement("span"); nameSpan.classList.add("name"); if (node.prefab != null) nameSpan.classList.add("prefab"); nameSpan.textContent = node.name; liElt.appendChild(nameSpan); const visibleButton = document.createElement("button"); visibleButton.textContent = SupClient.i18n.t("sceneEditor:treeView.visible.hide"); visibleButton.classList.add("show"); visibleButton.addEventListener("click", (event: any) => { event.stopPropagation(); const actor = data.sceneUpdater.bySceneNodeId[event.target.parentElement.dataset["id"]].actor; actor.threeObject.visible = !actor.threeObject.visible; const visible = actor.threeObject.visible ? "hide" : "show"; visibleButton.textContent = SupClient.i18n.t(`sceneEditor:treeView.visible.${visible}`); if (actor.threeObject.visible) visibleButton.classList.add("show"); else visibleButton.classList.remove("show"); }); liElt.appendChild(visibleButton); return liElt; } function onNodesTreeViewDrop(event: DragEvent, dropLocation: TreeView.DropLocation, orderedNodes: HTMLLIElement[]) { if (orderedNodes == null) return false; const dropPoint = SupClient.getTreeViewDropPoint(dropLocation, data.sceneUpdater.sceneAsset.nodes); const nodeIds: string[] = []; for (const node of orderedNodes ) nodeIds.push(node.dataset["id"]); const sourceParentNode = data.sceneUpdater.sceneAsset.nodes.parentNodesById[nodeIds[0]]; const sourceChildren = (sourceParentNode != null && sourceParentNode.children != null) ? sourceParentNode.children : data.sceneUpdater.sceneAsset.nodes.pub; const sameParent = (sourceParentNode != null && dropPoint.parentId === sourceParentNode.id); let i = 0; for (const id of nodeIds) { data.projectClient.editAsset(SupClient.query.asset, "moveNode", id, dropPoint.parentId, dropPoint.index + i); if (!sameParent || sourceChildren.indexOf(data.sceneUpdater.sceneAsset.nodes.byId[id]) >= dropPoint.index) i++; } return false; } function onNodeActivate() { // Focus an actor by double clicking on treeview if (ui.nodesTreeView.selectedNodes.length !== 1) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; focusActor(nodeId); } export function setupSelectedNode() { setupHelpers(); // Clear component editors for (const componentId in ui.componentEditors) ui.componentEditors[componentId].destroy(); ui.componentEditors = {}; // Setup transform const nodeElt = ui.nodesTreeView.selectedNodes[0]; if (nodeElt == null || ui.nodesTreeView.selectedNodes.length !== 1) { ui.inspectorElt.hidden = true; ui.newActorButton.disabled = false; ui.newPrefabButton.disabled = false; ui.renameNodeButton.disabled = true; ui.duplicateNodeButton.disabled = true; ui.deleteNodeButton.disabled = true; return; } ui.inspectorElt.hidden = false; const node = data.sceneUpdater.sceneAsset.nodes.byId[nodeElt.dataset["id"]]; setInspectorPosition(node.position as THREE.Vector3); setInspectorOrientation(node.orientation as THREE.Quaternion); setInspectorScale(node.scale as THREE.Vector3); ui.visibleCheckbox.checked = node.visible; ui.layerSelect.value = node.layer.toString(); // If it's a prefab, disable various buttons const isPrefab = node.prefab != null; ui.newActorButton.disabled = isPrefab; ui.newPrefabButton.disabled = isPrefab; ui.renameNodeButton.disabled = false; ui.duplicateNodeButton.disabled = false; ui.deleteNodeButton.disabled = false; if (isPrefab) { if (ui.prefabRow.parentElement == null) ui.inspectorTbodyElt.appendChild(ui.prefabRow); setInspectorPrefabScene(node.prefab.sceneAssetId); } else if (ui.prefabRow.parentElement != null) ui.inspectorTbodyElt.removeChild(ui.prefabRow); // Setup component editors ui.componentsElt.innerHTML = ""; for (const component of node.components) { const componentElt = createComponentElement(node.id, component); ui.componentsElt.appendChild(componentElt); } ui.newComponentButton.disabled = isPrefab; } function roundForInspector(number: number) { return parseFloat(number.toFixed(3)); } export function setInspectorPosition(position: THREE.Vector3) { const values = [ roundForInspector(position.x).toString(), roundForInspector(position.y).toString(), roundForInspector(position.z).toString() ]; for (let i = 0; i < 3; i++) { // NOTE: This helps avoid clearing selection when possible if (ui.transform.positionElts[i].value !== values[i]) { ui.transform.positionElts[i].value = values[i]; } } } export function setInspectorOrientation(orientation: THREE.Quaternion) { const euler = new THREE.Euler().setFromQuaternion(orientation); const values = [ roundForInspector(THREE.Math.radToDeg(euler.x)).toString(), roundForInspector(THREE.Math.radToDeg(euler.y)).toString(), roundForInspector(THREE.Math.radToDeg(euler.z)).toString() ]; // Work around weird conversion from quaternion to euler conversion if (values[1] === "180" && values[2] === "180") { values[0] = roundForInspector(180 - THREE.Math.radToDeg(euler.x)).toString(); values[1] = "0"; values[2] = "0"; } for (let i = 0; i < 3; i++) { // NOTE: This helps avoid clearing selection when possible if (ui.transform.orientationElts[i].value !== values[i]) { ui.transform.orientationElts[i].value = values[i]; } } } export function setInspectorScale(scale: THREE.Vector3) { const values = [ roundForInspector(scale.x).toString(), roundForInspector(scale.y).toString(), roundForInspector(scale.z).toString() ]; for (let i = 0; i < 3; i++) { // NOTE: This helps avoid clearing selection when possible if (ui.transform.scaleElts[i].value !== values[i]) { ui.transform.scaleElts[i].value = values[i]; } } } export function setInspectorVisible(visible: boolean) { ui.visibleCheckbox.checked = visible; } export function setInspectorLayer(layer: number) { ui.layerSelect.value = layer.toString(); } export function setupInspectorLayers() { while (ui.layerSelect.childElementCount > data.gameSettingsResource.pub.customLayers.length + 1) ui.layerSelect.removeChild(ui.layerSelect.lastElementChild); let optionElt = ui.layerSelect.firstElementChild.nextElementSibling as HTMLOptionElement; for (let i = 0; i < data.gameSettingsResource.pub.customLayers.length; i++) { if (optionElt == null) { optionElt = document.createElement("option"); ui.layerSelect.appendChild(optionElt); } optionElt.value = (i + 1).toString(); // + 1 because "Default" is 0 optionElt.textContent = data.gameSettingsResource.pub.customLayers[i]; optionElt = optionElt.nextElementSibling as HTMLOptionElement; } } export function setInspectorPrefabScene(sceneAssetId: string) { if (sceneAssetId != null && data.projectClient.entries.byId[sceneAssetId] != null) { ui.prefabInput.value = data.projectClient.entries.getPathFromId(sceneAssetId); ui.prefabOpenElt.disabled = false; } else { ui.prefabInput.value = ""; ui.prefabOpenElt.disabled = true; } } function onNewNodeClick() { const options = { initialValue: SupClient.i18n.t("sceneEditor:treeView.newActor.initialValue"), validationLabel: SupClient.i18n.t("common:actions.create"), pattern: SupClient.namePattern, title: SupClient.i18n.t("common:namePatternDescription") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("sceneEditor:treeView.newActor.prompt"), options, (name) => { if (name == null) return; createNewNode(name, false); }); } function onNewPrefabClick() { const options = { initialValue: SupClient.i18n.t("sceneEditor:treeView.newPrefab.initialValue"), validationLabel: SupClient.i18n.t("common:actions.create"), pattern: SupClient.namePattern, title: SupClient.i18n.t("common:namePatternDescription") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("sceneEditor:treeView.newPrefab.prompt"), options, (name) => { if (name == null) return; createNewNode(name, true); }); } function createNewNode(name: string, prefab: boolean) { const options = SupClient.getTreeViewInsertionPoint(ui.nodesTreeView); const offset = new THREE.Vector3(0, 0, -10).applyQuaternion(engine.cameraActor.getGlobalOrientation(new THREE.Quaternion())); const position = new THREE.Vector3(); engine.cameraActor.getGlobalPosition(position).add(offset); if (options.parentId != null) { const parentMatrix = data.sceneUpdater.bySceneNodeId[options.parentId].actor.getGlobalMatrix(new THREE.Matrix4()); position.applyMatrix4(parentMatrix.getInverse(parentMatrix)); } (options as any).transform = { position }; (options as any).prefab = prefab; data.projectClient.editAsset(SupClient.query.asset, "addNode", name, options, (nodeId: string) => { ui.nodesTreeView.clearSelection(); ui.nodesTreeView.addToSelection(ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${nodeId}']`) as HTMLLIElement); setupSelectedNode(); }); } function onRenameNodeClick() { if (ui.nodesTreeView.selectedNodes.length !== 1) return; const selectedNode = ui.nodesTreeView.selectedNodes[0]; const node = data.sceneUpdater.sceneAsset.nodes.byId[selectedNode.dataset["id"]]; const options = { initialValue: node.name, validationLabel: SupClient.i18n.t("common:actions.rename"), pattern: SupClient.namePattern, title: SupClient.i18n.t("common:namePatternDescription") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("sceneEditor:treeView.renamePrompt"), options, (newName) => { if (newName == null) return; data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", node.id, "name", newName); }); } function onDuplicateNodeClick() { if (ui.nodesTreeView.selectedNodes.length !== 1) return; const selectedNode = ui.nodesTreeView.selectedNodes[0]; const node = data.sceneUpdater.sceneAsset.nodes.byId[selectedNode.dataset["id"]]; const options = { initialValue: node.name, validationLabel: SupClient.i18n.t("common:actions.duplicate"), pattern: SupClient.namePattern, title: SupClient.i18n.t("common:namePatternDescription") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("sceneEditor:treeView.duplicatePrompt"), options, (newName) => { if (newName == null) return; const options = SupClient.getTreeViewSiblingInsertionPoint(ui.nodesTreeView); data.projectClient.editAsset(SupClient.query.asset, "duplicateNode", newName, node.id, options.index, (nodeId: string) => { ui.nodesTreeView.clearSelection(); ui.nodesTreeView.addToSelection(ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${nodeId}']`) as HTMLLIElement); setupSelectedNode(); }); }); } function onDeleteNodeClick() { if (ui.nodesTreeView.selectedNodes.length === 0) return; const confirmLabel = SupClient.i18n.t("sceneEditor:treeView.deleteConfirm"); const validationLabel = SupClient.i18n.t("common:actions.delete"); new SupClient.Dialogs.ConfirmDialog(confirmLabel, { validationLabel }, (confirm) => { if (!confirm) return; for (const selectedNode of ui.nodesTreeView.selectedNodes) { data.projectClient.editAsset(SupClient.query.asset, "removeNode", selectedNode.dataset["id"]); } }); } function onTransformInputChange(event: any) { if (ui.nodesTreeView.selectedNodes.length !== 1) return; const transformType = event.target.parentElement.parentElement.parentElement.className; const inputs: HTMLInputElement[] = (ui.transform as any)[`${transformType}Elts`]; let value: { x: number; y: number; z: number; w?: number } = { x: parseFloat(inputs[0].value), y: parseFloat(inputs[1].value), z: parseFloat(inputs[2].value), }; if (transformType === "orientation") { const euler = new THREE.Euler(THREE.Math.degToRad(value.x), THREE.Math.degToRad(value.y), THREE.Math.degToRad(value.z)); const quaternion = new THREE.Quaternion().setFromEuler(euler); value = { x: quaternion.x, y: quaternion.y, z: quaternion.z, w: quaternion.w }; } const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", nodeId, transformType, value); } function onVisibleChange(event: any) { if (ui.nodesTreeView.selectedNodes.length !== 1) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", nodeId, "visible", event.target.checked); } function onLayerChange(event: any) { if (ui.nodesTreeView.selectedNodes.length !== 1) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", nodeId, "layer", parseInt(event.target.value, 10)); } function onPrefabInput(event: any) { if (ui.nodesTreeView.selectedNodes.length !== 1) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; if (event.target.value === "") { data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", nodeId, "prefab.sceneAssetId", null); } else { const entry = SupClient.findEntryByPath(data.projectClient.entries.pub, event.target.value); if (entry != null && entry.type === "scene") { data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", nodeId, "prefab.sceneAssetId", entry.id); } } } export function createComponentElement(nodeId: string, component: Component) { const componentElt = document.createElement("div"); componentElt.dataset["componentId"] = component.id; const template = document.getElementById("component-cartridge-template") as HTMLElement; const clone = document.importNode((template as any).content, true) as HTMLElement; clone.querySelector(".type").textContent = SupClient.i18n.t(`componentEditors:${component.type}.label`); const table = clone.querySelector(".settings") as HTMLElement; const editConfig = (command: string, ...args: any[]) => { let callback = (err: string) => { if (err != null) new SupClient.Dialogs.InfoDialog(err); }; // Override callback if one is given let lastArg = args[args.length - 1]; if (typeof lastArg === "function") callback = args.pop(); // Prevent setting a NaN value if (command === "setProperty" && typeof args[1] === "number" && isNaN(args[1])) return; data.projectClient.editAsset(SupClient.query.asset, "editComponent", nodeId, component.id, command, ...args, callback); }; const componentEditorPlugin = componentEditorPlugins[component.type].content; ui.componentEditors[component.id] = new componentEditorPlugin(table.querySelector("tbody") as HTMLTableSectionElement, component.config, data.projectClient, editConfig); const shrinkButton = clone.querySelector(".shrink-component"); shrinkButton.addEventListener("click", () => { if (table.style.display === "none") { table.style.display = ""; shrinkButton.textContent = "–"; } else { table.style.display = "none"; shrinkButton.textContent = "+"; } }); clone.querySelector(".delete-component").addEventListener("click", onDeleteComponentClick); componentElt.appendChild(clone); return componentElt; } function onNewComponentClick() { const selectLabel = SupClient.i18n.t("sceneEditor:inspector.newComponent.select"); const validationLabel = SupClient.i18n.t("sceneEditor:inspector.newComponent.validate"); new SupClient.Dialogs.SelectDialog(selectLabel, ui.availableComponents, { validationLabel, size: 12 }, (type) => { if (type == null) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; data.projectClient.editAsset(SupClient.query.asset, "addComponent", nodeId, type, null); }); } function onDeleteComponentClick(event: any) { const confirmLabel = SupClient.i18n.t("sceneEditor:inspector.deleteComponent.confirm"); const validationLabel = SupClient.i18n.t("sceneEditor:inspector.deleteComponent.validate"); new SupClient.Dialogs.ConfirmDialog(confirmLabel, { validationLabel }, (confirm) => { if (!confirm) return; const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; const componentId = event.target.parentElement.parentElement.dataset["componentId"]; data.projectClient.editAsset(SupClient.query.asset, "removeComponent", nodeId, componentId); }); } export function setCameraMode(mode: string) { engine.gameInstance.destroyComponent(engine.cameraControls); ui.cameraMode = mode; (document.querySelector(".controls .camera-vertical-axis") as HTMLDivElement).hidden = ui.cameraMode !== "3D"; (document.querySelector(".controls .camera-speed") as HTMLDivElement).hidden = ui.cameraMode !== "3D"; (document.querySelector(".controls .camera-2d-z") as HTMLDivElement).hidden = ui.cameraMode === "3D"; const axis = ui.cameraMode === "3D" ? ui.cameraVerticalAxis : "Y"; engine.cameraRoot.setLocalEulerAngles(new THREE.Euler(axis === "Y" ? 0 : Math.PI / 2, 0, 0)); updateCameraMode(); ui.cameraModeButton.textContent = ui.cameraMode; } function onChangeCameraMode(event: any) { setCameraMode(ui.cameraMode === "3D" ? "2D" : "3D"); } export function setCameraVerticalAxis(axis: string) { ui.cameraVerticalAxis = axis; engine.cameraRoot.setLocalEulerAngles(new THREE.Euler(axis === "Y" ? 0 : Math.PI / 2, 0, 0)); ui.cameraVerticalAxisButton.textContent = axis; } function onChangeCameraVerticalAxis(event: any) { setCameraVerticalAxis(ui.cameraVerticalAxis === "Y" ? "Z" : "Y"); } function onChangeCameraSpeed() { engine.cameraControls.movementSpeed = ui.cameraSpeedSlider.value; } function onChangeCamera2DZ() { const z = parseFloat(ui.camera2DZ.value); if (isNaN(z)) return; engine.cameraActor.threeObject.position.setZ(z); engine.cameraActor.threeObject.updateMatrixWorld(false); } // Drag'n'drop function onDragOver(event: DragEvent) { if (data == null || data.projectClient.entries == null) return; // NOTE: We can't use event.dataTransfer.getData() to do an early check here // because of browser security restrictions ui.actorDropElt.hidden = false; if (ui.nodesTreeView.selectedNodes.length === 1) { const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; const node = data.sceneUpdater.sceneAsset.nodes.byId[nodeId]; if (node.prefab == null) ui.componentDropElt.hidden = false; } // Ensure we're not hovering the nodes tree view or component area let ancestorElt = (event.target as HTMLElement).parentElement; let preventDefaultBehavior = true; while (ancestorElt != null) { if (ancestorElt === ui.componentsElt || ancestorElt === ui.treeViewElt || (ui.componentDropElt.hidden && ancestorElt === ui.prefabRow)) { preventDefaultBehavior = false; break; } ancestorElt = ancestorElt.parentElement; } if (preventDefaultBehavior) event.preventDefault(); if (ui.dropTimeout != null) clearTimeout(ui.dropTimeout); ui.dropTimeout = setTimeout(() => { onStopDrag(); }, 300); } function onStopDrag() { if (ui.dropTimeout != null) { clearTimeout(ui.dropTimeout); ui.dropTimeout = null; } ui.actorDropElt.hidden = true; ui.actorDropElt.querySelector(".drop-asset-text").classList.toggle("can-drop", false); ui.componentDropElt.hidden = true; ui.componentDropElt.querySelector(".drop-asset-text").classList.toggle("can-drop", false); } function onActorDragEnter(event: DragEvent) { ui.actorDropElt.querySelector(".drop-asset-text").classList.toggle("can-drop", true); } function onActorDragLeave(event: DragEvent) { ui.actorDropElt.querySelector(".drop-asset-text").classList.toggle("can-drop", false); } function onActorDrop(event: DragEvent) { if (data == null || data.projectClient.entries == null) return; // TODO: Support importing multiple assets at once const entryId = event.dataTransfer.getData("application/vnd.superpowers.entry").split(",")[0]; if (typeof entryId !== "string") return; const entry = data.projectClient.entries.byId[entryId]; const plugin = SupClient.getPlugins<SupClient.ImportIntoScenePlugin>("importIntoScene")[entry.type]; if (plugin == null || plugin.content.importActor == null) { const reason = SupClient.i18n.t("sceneEditor:errors.cantImportAssetTypeIntoScene"); new SupClient.Dialogs.InfoDialog(SupClient.i18n.t("sceneEditor:failures.importIntoScene", { reason })); return; } event.preventDefault(); const raycaster = new THREE.Raycaster(); const mousePosition = { x: (event.clientX / ui.canvasElt.clientWidth) * 2 - 1, y: -(event.clientY / ui.canvasElt.clientHeight) * 2 + 1 }; raycaster.setFromCamera(mousePosition, engine.cameraComponent.threeCamera); const plane = new THREE.Plane(); const offset = new THREE.Vector3(0, 0, -10).applyQuaternion(engine.cameraActor.getGlobalOrientation(new THREE.Quaternion())); const planePosition = engine.cameraActor.getGlobalPosition(new THREE.Vector3()).add(offset); plane.setFromNormalAndCoplanarPoint(offset.normalize(), planePosition); const position = raycaster.ray.intersectPlane(plane); const options = { transform: { position }, prefab: false }; plugin.content.importActor(entry, data.projectClient, options, (err: string, nodeId: string) => { if (err != null) { new SupClient.Dialogs.InfoDialog(SupClient.i18n.t("sceneEditor:failures.importIntoScene", { reason: err })); return; } ui.nodesTreeView.clearSelection(); const entryElt = ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${nodeId}']`) as HTMLLIElement; ui.nodesTreeView.addToSelection(entryElt); ui.nodesTreeView.scrollIntoView(entryElt); setupSelectedNode(); ui.canvasElt.focus(); }); } function onComponentDragEnter(event: DragEvent) { ui.componentDropElt.querySelector(".drop-asset-text").classList.toggle("can-drop", true); } function onComponentDragLeave(event: DragEvent) { ui.componentDropElt.querySelector(".drop-asset-text").classList.toggle("can-drop", false); } function onComponentDrop(event: DragEvent) { if (data == null || data.projectClient.entries == null) return; // TODO: Support importing multiple assets at once const entryId = event.dataTransfer.getData("application/vnd.superpowers.entry").split(",")[0]; if (typeof entryId !== "string") return; const entry = data.projectClient.entries.byId[entryId]; const plugin = SupClient.getPlugins<SupClient.ImportIntoScenePlugin>("importIntoScene")[entry.type]; if (plugin == null || plugin.content.importComponent == null) { const reason = SupClient.i18n.t("sceneEditor:errors.cantImportAssetTypeIntoScene"); new SupClient.Dialogs.InfoDialog(SupClient.i18n.t("sceneEditor:failures.importIntoScene", { reason })); return; } event.preventDefault(); const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"]; plugin.content.importComponent(entry, data.projectClient, nodeId, (err: string, nodeId: string) => { /* Ignore */ }); }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config'; interface Blob {} declare class CognitoIdentity extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: CognitoIdentity.Types.ClientConfiguration) config: Config & CognitoIdentity.Types.ClientConfiguration; /** * Creates a new identity pool. The identity pool is a store of user identity information that is specific to your AWS account. The limit on identity pools is 60 per account. The keys for SupportedLoginProviders are as follows: Facebook: graph.facebook.com Google: accounts.google.com Amazon: www.amazon.com Twitter: api.twitter.com Digits: www.digits.com You must use AWS Developer credentials to call this API. */ createIdentityPool(params: CognitoIdentity.Types.CreateIdentityPoolInput, callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityPool) => void): Request<CognitoIdentity.Types.IdentityPool, AWSError>; /** * Creates a new identity pool. The identity pool is a store of user identity information that is specific to your AWS account. The limit on identity pools is 60 per account. The keys for SupportedLoginProviders are as follows: Facebook: graph.facebook.com Google: accounts.google.com Amazon: www.amazon.com Twitter: api.twitter.com Digits: www.digits.com You must use AWS Developer credentials to call this API. */ createIdentityPool(callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityPool) => void): Request<CognitoIdentity.Types.IdentityPool, AWSError>; /** * Deletes identities from an identity pool. You can specify a list of 1-60 identities that you want to delete. You must use AWS Developer credentials to call this API. */ deleteIdentities(params: CognitoIdentity.Types.DeleteIdentitiesInput, callback?: (err: AWSError, data: CognitoIdentity.Types.DeleteIdentitiesResponse) => void): Request<CognitoIdentity.Types.DeleteIdentitiesResponse, AWSError>; /** * Deletes identities from an identity pool. You can specify a list of 1-60 identities that you want to delete. You must use AWS Developer credentials to call this API. */ deleteIdentities(callback?: (err: AWSError, data: CognitoIdentity.Types.DeleteIdentitiesResponse) => void): Request<CognitoIdentity.Types.DeleteIdentitiesResponse, AWSError>; /** * Deletes a user pool. Once a pool is deleted, users will not be able to authenticate with the pool. You must use AWS Developer credentials to call this API. */ deleteIdentityPool(params: CognitoIdentity.Types.DeleteIdentityPoolInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a user pool. Once a pool is deleted, users will not be able to authenticate with the pool. You must use AWS Developer credentials to call this API. */ deleteIdentityPool(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Returns metadata related to the given identity, including when the identity was created and any associated linked logins. You must use AWS Developer credentials to call this API. */ describeIdentity(params: CognitoIdentity.Types.DescribeIdentityInput, callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityDescription) => void): Request<CognitoIdentity.Types.IdentityDescription, AWSError>; /** * Returns metadata related to the given identity, including when the identity was created and any associated linked logins. You must use AWS Developer credentials to call this API. */ describeIdentity(callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityDescription) => void): Request<CognitoIdentity.Types.IdentityDescription, AWSError>; /** * Gets details about a particular identity pool, including the pool name, ID description, creation date, and current number of users. You must use AWS Developer credentials to call this API. */ describeIdentityPool(params: CognitoIdentity.Types.DescribeIdentityPoolInput, callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityPool) => void): Request<CognitoIdentity.Types.IdentityPool, AWSError>; /** * Gets details about a particular identity pool, including the pool name, ID description, creation date, and current number of users. You must use AWS Developer credentials to call this API. */ describeIdentityPool(callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityPool) => void): Request<CognitoIdentity.Types.IdentityPool, AWSError>; /** * Returns credentials for the provided identity ID. Any provided logins will be validated against supported login providers. If the token is for cognito-identity.amazonaws.com, it will be passed through to AWS Security Token Service with the appropriate role for the token. This is a public API. You do not need any credentials to call this API. */ getCredentialsForIdentity(params: CognitoIdentity.Types.GetCredentialsForIdentityInput, callback?: (err: AWSError, data: CognitoIdentity.Types.GetCredentialsForIdentityResponse) => void): Request<CognitoIdentity.Types.GetCredentialsForIdentityResponse, AWSError>; /** * Returns credentials for the provided identity ID. Any provided logins will be validated against supported login providers. If the token is for cognito-identity.amazonaws.com, it will be passed through to AWS Security Token Service with the appropriate role for the token. This is a public API. You do not need any credentials to call this API. */ getCredentialsForIdentity(callback?: (err: AWSError, data: CognitoIdentity.Types.GetCredentialsForIdentityResponse) => void): Request<CognitoIdentity.Types.GetCredentialsForIdentityResponse, AWSError>; /** * Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account. This is a public API. You do not need any credentials to call this API. */ getId(params: CognitoIdentity.Types.GetIdInput, callback?: (err: AWSError, data: CognitoIdentity.Types.GetIdResponse) => void): Request<CognitoIdentity.Types.GetIdResponse, AWSError>; /** * Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account. This is a public API. You do not need any credentials to call this API. */ getId(callback?: (err: AWSError, data: CognitoIdentity.Types.GetIdResponse) => void): Request<CognitoIdentity.Types.GetIdResponse, AWSError>; /** * Gets the roles for an identity pool. You must use AWS Developer credentials to call this API. */ getIdentityPoolRoles(params: CognitoIdentity.Types.GetIdentityPoolRolesInput, callback?: (err: AWSError, data: CognitoIdentity.Types.GetIdentityPoolRolesResponse) => void): Request<CognitoIdentity.Types.GetIdentityPoolRolesResponse, AWSError>; /** * Gets the roles for an identity pool. You must use AWS Developer credentials to call this API. */ getIdentityPoolRoles(callback?: (err: AWSError, data: CognitoIdentity.Types.GetIdentityPoolRolesResponse) => void): Request<CognitoIdentity.Types.GetIdentityPoolRolesResponse, AWSError>; /** * Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by GetId. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link. The OpenId token is valid for 15 minutes. This is a public API. You do not need any credentials to call this API. */ getOpenIdToken(params: CognitoIdentity.Types.GetOpenIdTokenInput, callback?: (err: AWSError, data: CognitoIdentity.Types.GetOpenIdTokenResponse) => void): Request<CognitoIdentity.Types.GetOpenIdTokenResponse, AWSError>; /** * Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by GetId. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link. The OpenId token is valid for 15 minutes. This is a public API. You do not need any credentials to call this API. */ getOpenIdToken(callback?: (err: AWSError, data: CognitoIdentity.Types.GetOpenIdTokenResponse) => void): Request<CognitoIdentity.Types.GetOpenIdTokenResponse, AWSError>; /** * Registers (or retrieves) a Cognito IdentityId and an OpenID Connect token for a user authenticated by your backend authentication process. Supplying multiple logins will create an implicit linked account. You can only specify one developer provider as part of the Logins map, which is linked to the identity pool. The developer provider is the "domain" by which Cognito will refer to your users. You can use GetOpenIdTokenForDeveloperIdentity to create a new identity and to link new logins (that is, user credentials issued by a public provider or developer provider) to an existing identity. When you want to create a new identity, the IdentityId should be null. When you want to associate a new login with an existing authenticated/unauthenticated identity, you can do so by providing the existing IdentityId. This API will create the identity in the specified IdentityPoolId. You must use AWS Developer credentials to call this API. */ getOpenIdTokenForDeveloperIdentity(params: CognitoIdentity.Types.GetOpenIdTokenForDeveloperIdentityInput, callback?: (err: AWSError, data: CognitoIdentity.Types.GetOpenIdTokenForDeveloperIdentityResponse) => void): Request<CognitoIdentity.Types.GetOpenIdTokenForDeveloperIdentityResponse, AWSError>; /** * Registers (or retrieves) a Cognito IdentityId and an OpenID Connect token for a user authenticated by your backend authentication process. Supplying multiple logins will create an implicit linked account. You can only specify one developer provider as part of the Logins map, which is linked to the identity pool. The developer provider is the "domain" by which Cognito will refer to your users. You can use GetOpenIdTokenForDeveloperIdentity to create a new identity and to link new logins (that is, user credentials issued by a public provider or developer provider) to an existing identity. When you want to create a new identity, the IdentityId should be null. When you want to associate a new login with an existing authenticated/unauthenticated identity, you can do so by providing the existing IdentityId. This API will create the identity in the specified IdentityPoolId. You must use AWS Developer credentials to call this API. */ getOpenIdTokenForDeveloperIdentity(callback?: (err: AWSError, data: CognitoIdentity.Types.GetOpenIdTokenForDeveloperIdentityResponse) => void): Request<CognitoIdentity.Types.GetOpenIdTokenForDeveloperIdentityResponse, AWSError>; /** * Lists the identities in a pool. You must use AWS Developer credentials to call this API. */ listIdentities(params: CognitoIdentity.Types.ListIdentitiesInput, callback?: (err: AWSError, data: CognitoIdentity.Types.ListIdentitiesResponse) => void): Request<CognitoIdentity.Types.ListIdentitiesResponse, AWSError>; /** * Lists the identities in a pool. You must use AWS Developer credentials to call this API. */ listIdentities(callback?: (err: AWSError, data: CognitoIdentity.Types.ListIdentitiesResponse) => void): Request<CognitoIdentity.Types.ListIdentitiesResponse, AWSError>; /** * Lists all of the Cognito identity pools registered for your account. You must use AWS Developer credentials to call this API. */ listIdentityPools(params: CognitoIdentity.Types.ListIdentityPoolsInput, callback?: (err: AWSError, data: CognitoIdentity.Types.ListIdentityPoolsResponse) => void): Request<CognitoIdentity.Types.ListIdentityPoolsResponse, AWSError>; /** * Lists all of the Cognito identity pools registered for your account. You must use AWS Developer credentials to call this API. */ listIdentityPools(callback?: (err: AWSError, data: CognitoIdentity.Types.ListIdentityPoolsResponse) => void): Request<CognitoIdentity.Types.ListIdentityPoolsResponse, AWSError>; /** * Retrieves the IdentityID associated with a DeveloperUserIdentifier or the list of DeveloperUserIdentifiers associated with an IdentityId for an existing identity. Either IdentityID or DeveloperUserIdentifier must not be null. If you supply only one of these values, the other value will be searched in the database and returned as a part of the response. If you supply both, DeveloperUserIdentifier will be matched against IdentityID. If the values are verified against the database, the response returns both values and is the same as the request. Otherwise a ResourceConflictException is thrown. You must use AWS Developer credentials to call this API. */ lookupDeveloperIdentity(params: CognitoIdentity.Types.LookupDeveloperIdentityInput, callback?: (err: AWSError, data: CognitoIdentity.Types.LookupDeveloperIdentityResponse) => void): Request<CognitoIdentity.Types.LookupDeveloperIdentityResponse, AWSError>; /** * Retrieves the IdentityID associated with a DeveloperUserIdentifier or the list of DeveloperUserIdentifiers associated with an IdentityId for an existing identity. Either IdentityID or DeveloperUserIdentifier must not be null. If you supply only one of these values, the other value will be searched in the database and returned as a part of the response. If you supply both, DeveloperUserIdentifier will be matched against IdentityID. If the values are verified against the database, the response returns both values and is the same as the request. Otherwise a ResourceConflictException is thrown. You must use AWS Developer credentials to call this API. */ lookupDeveloperIdentity(callback?: (err: AWSError, data: CognitoIdentity.Types.LookupDeveloperIdentityResponse) => void): Request<CognitoIdentity.Types.LookupDeveloperIdentityResponse, AWSError>; /** * Merges two users having different IdentityIds, existing in the same identity pool, and identified by the same developer provider. You can use this action to request that discrete users be merged and identified as a single user in the Cognito environment. Cognito associates the given source user (SourceUserIdentifier) with the IdentityId of the DestinationUserIdentifier. Only developer-authenticated users can be merged. If the users to be merged are associated with the same public provider, but as two different users, an exception will be thrown. You must use AWS Developer credentials to call this API. */ mergeDeveloperIdentities(params: CognitoIdentity.Types.MergeDeveloperIdentitiesInput, callback?: (err: AWSError, data: CognitoIdentity.Types.MergeDeveloperIdentitiesResponse) => void): Request<CognitoIdentity.Types.MergeDeveloperIdentitiesResponse, AWSError>; /** * Merges two users having different IdentityIds, existing in the same identity pool, and identified by the same developer provider. You can use this action to request that discrete users be merged and identified as a single user in the Cognito environment. Cognito associates the given source user (SourceUserIdentifier) with the IdentityId of the DestinationUserIdentifier. Only developer-authenticated users can be merged. If the users to be merged are associated with the same public provider, but as two different users, an exception will be thrown. You must use AWS Developer credentials to call this API. */ mergeDeveloperIdentities(callback?: (err: AWSError, data: CognitoIdentity.Types.MergeDeveloperIdentitiesResponse) => void): Request<CognitoIdentity.Types.MergeDeveloperIdentitiesResponse, AWSError>; /** * Sets the roles for an identity pool. These roles are used when making calls to GetCredentialsForIdentity action. You must use AWS Developer credentials to call this API. */ setIdentityPoolRoles(params: CognitoIdentity.Types.SetIdentityPoolRolesInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Sets the roles for an identity pool. These roles are used when making calls to GetCredentialsForIdentity action. You must use AWS Developer credentials to call this API. */ setIdentityPoolRoles(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Unlinks a DeveloperUserIdentifier from an existing identity. Unlinked developer users will be considered new identities next time they are seen. If, for a given Cognito identity, you remove all federated identities as well as the developer user identifier, the Cognito identity becomes inaccessible. You must use AWS Developer credentials to call this API. */ unlinkDeveloperIdentity(params: CognitoIdentity.Types.UnlinkDeveloperIdentityInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Unlinks a DeveloperUserIdentifier from an existing identity. Unlinked developer users will be considered new identities next time they are seen. If, for a given Cognito identity, you remove all federated identities as well as the developer user identifier, the Cognito identity becomes inaccessible. You must use AWS Developer credentials to call this API. */ unlinkDeveloperIdentity(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Unlinks a federated identity from an existing account. Unlinked logins will be considered new identities next time they are seen. Removing the last linked login will make this identity inaccessible. This is a public API. You do not need any credentials to call this API. */ unlinkIdentity(params: CognitoIdentity.Types.UnlinkIdentityInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Unlinks a federated identity from an existing account. Unlinked logins will be considered new identities next time they are seen. Removing the last linked login will make this identity inaccessible. This is a public API. You do not need any credentials to call this API. */ unlinkIdentity(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates a user pool. You must use AWS Developer credentials to call this API. */ updateIdentityPool(params: CognitoIdentity.Types.IdentityPool, callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityPool) => void): Request<CognitoIdentity.Types.IdentityPool, AWSError>; /** * Updates a user pool. You must use AWS Developer credentials to call this API. */ updateIdentityPool(callback?: (err: AWSError, data: CognitoIdentity.Types.IdentityPool) => void): Request<CognitoIdentity.Types.IdentityPool, AWSError>; } declare namespace CognitoIdentity { export type ARNString = string; export type AccessKeyString = string; export type AccountId = string; export type AmbiguousRoleResolutionType = "AuthenticatedRole"|"Deny"|string; export type ClaimName = string; export type ClaimValue = string; export interface CognitoIdentityProvider { /** * The provider name for an Amazon Cognito Identity User Pool. For example, cognito-idp.us-east-1.amazonaws.com/us-east-1_123456789. */ ProviderName?: CognitoIdentityProviderName; /** * The client ID for the Amazon Cognito Identity User Pool. */ ClientId?: CognitoIdentityProviderClientId; /** * TRUE if server-side token validation is enabled for the identity provider’s token. */ ServerSideTokenCheck?: CognitoIdentityProviderTokenCheck; } export type CognitoIdentityProviderClientId = string; export type CognitoIdentityProviderList = CognitoIdentityProvider[]; export type CognitoIdentityProviderName = string; export type CognitoIdentityProviderTokenCheck = boolean; export interface CreateIdentityPoolInput { /** * A string that you provide. */ IdentityPoolName: IdentityPoolName; /** * TRUE if the identity pool supports unauthenticated logins. */ AllowUnauthenticatedIdentities: IdentityPoolUnauthenticated; /** * Optional key:value pairs mapping provider names to provider app IDs. */ SupportedLoginProviders?: IdentityProviders; /** * The "domain" by which Cognito will refer to your users. This name acts as a placeholder that allows your backend and the Cognito service to communicate about the developer provider. For the DeveloperProviderName, you can use letters as well as period (.), underscore (_), and dash (-). Once you have set a developer provider name, you cannot change it. Please take care in setting this parameter. */ DeveloperProviderName?: DeveloperProviderName; /** * A list of OpendID Connect provider ARNs. */ OpenIdConnectProviderARNs?: OIDCProviderList; /** * An array of Amazon Cognito Identity user pools and their client IDs. */ CognitoIdentityProviders?: CognitoIdentityProviderList; /** * An array of Amazon Resource Names (ARNs) of the SAML provider for your identity pool. */ SamlProviderARNs?: SAMLProviderList; } export interface Credentials { /** * The Access Key portion of the credentials. */ AccessKeyId?: AccessKeyString; /** * The Secret Access Key portion of the credentials */ SecretKey?: SecretKeyString; /** * The Session Token portion of the credentials */ SessionToken?: SessionTokenString; /** * The date at which these credentials will expire. */ Expiration?: DateType; } export type DateType = Date; export interface DeleteIdentitiesInput { /** * A list of 1-60 identities that you want to delete. */ IdentityIdsToDelete: IdentityIdList; } export interface DeleteIdentitiesResponse { /** * An array of UnprocessedIdentityId objects, each of which contains an ErrorCode and IdentityId. */ UnprocessedIdentityIds?: UnprocessedIdentityIdList; } export interface DeleteIdentityPoolInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; } export interface DescribeIdentityInput { /** * A unique identifier in the format REGION:GUID. */ IdentityId: IdentityId; } export interface DescribeIdentityPoolInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; } export type DeveloperProviderName = string; export type DeveloperUserIdentifier = string; export type DeveloperUserIdentifierList = DeveloperUserIdentifier[]; export type ErrorCode = "AccessDenied"|"InternalServerError"|string; export interface GetCredentialsForIdentityInput { /** * A unique identifier in the format REGION:GUID. */ IdentityId: IdentityId; /** * A set of optional name-value pairs that map provider names to provider tokens. */ Logins?: LoginsMap; /** * The Amazon Resource Name (ARN) of the role to be assumed when multiple roles were received in the token from the identity provider. For example, a SAML-based identity provider. This parameter is optional for identity providers that do not support role customization. */ CustomRoleArn?: ARNString; } export interface GetCredentialsForIdentityResponse { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * Credentials for the provided identity ID. */ Credentials?: Credentials; } export interface GetIdInput { /** * A standard AWS account ID (9+ digits). */ AccountId?: AccountId; /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * A set of optional name-value pairs that map provider names to provider tokens. The available provider names for Logins are as follows: Facebook: graph.facebook.com Amazon Cognito Identity Provider: cognito-idp.us-east-1.amazonaws.com/us-east-1_123456789 Google: accounts.google.com Amazon: www.amazon.com Twitter: api.twitter.com Digits: www.digits.com */ Logins?: LoginsMap; } export interface GetIdResponse { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; } export interface GetIdentityPoolRolesInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; } export interface GetIdentityPoolRolesResponse { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId?: IdentityPoolId; /** * The map of roles associated with this pool. Currently only authenticated and unauthenticated roles are supported. */ Roles?: RolesMap; /** * How users for a specific identity provider are to mapped to roles. This is a String-to-RoleMapping object map. The string identifies the identity provider, for example, "graph.facebook.com" or "cognito-idp-east-1.amazonaws.com/us-east-1_abcdefghi:app_client_id". */ RoleMappings?: RoleMappingMap; } export interface GetOpenIdTokenForDeveloperIdentityInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * A set of optional name-value pairs that map provider names to provider tokens. Each name-value pair represents a user from a public provider or developer provider. If the user is from a developer provider, the name-value pair will follow the syntax "developer_provider_name": "developer_user_identifier". The developer provider is the "domain" by which Cognito will refer to your users; you provided this domain while creating/updating the identity pool. The developer user identifier is an identifier from your backend that uniquely identifies a user. When you create an identity pool, you can specify the supported logins. */ Logins: LoginsMap; /** * The expiration time of the token, in seconds. You can specify a custom expiration time for the token so that you can cache it. If you don't provide an expiration time, the token is valid for 15 minutes. You can exchange the token with Amazon STS for temporary AWS credentials, which are valid for a maximum of one hour. The maximum token duration you can set is 24 hours. You should take care in setting the expiration time for a token, as there are significant security implications: an attacker could use a leaked token to access your AWS resources for the token's duration. */ TokenDuration?: TokenDuration; } export interface GetOpenIdTokenForDeveloperIdentityResponse { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * An OpenID token. */ Token?: OIDCToken; } export interface GetOpenIdTokenInput { /** * A unique identifier in the format REGION:GUID. */ IdentityId: IdentityId; /** * A set of optional name-value pairs that map provider names to provider tokens. When using graph.facebook.com and www.amazon.com, supply the access_token returned from the provider's authflow. For accounts.google.com, an Amazon Cognito Identity Provider, or any other OpenId Connect provider, always include the id_token. */ Logins?: LoginsMap; } export interface GetOpenIdTokenResponse { /** * A unique identifier in the format REGION:GUID. Note that the IdentityId returned may not match the one passed on input. */ IdentityId?: IdentityId; /** * An OpenID token, valid for 15 minutes. */ Token?: OIDCToken; } export type HideDisabled = boolean; export type IdentitiesList = IdentityDescription[]; export interface IdentityDescription { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * A set of optional name-value pairs that map provider names to provider tokens. */ Logins?: LoginsList; /** * Date on which the identity was created. */ CreationDate?: DateType; /** * Date on which the identity was last modified. */ LastModifiedDate?: DateType; } export type IdentityId = string; export type IdentityIdList = IdentityId[]; export interface IdentityPool { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * A string that you provide. */ IdentityPoolName: IdentityPoolName; /** * TRUE if the identity pool supports unauthenticated logins. */ AllowUnauthenticatedIdentities: IdentityPoolUnauthenticated; /** * Optional key:value pairs mapping provider names to provider app IDs. */ SupportedLoginProviders?: IdentityProviders; /** * The "domain" by which Cognito will refer to your users. */ DeveloperProviderName?: DeveloperProviderName; /** * A list of OpendID Connect provider ARNs. */ OpenIdConnectProviderARNs?: OIDCProviderList; /** * A list representing an Amazon Cognito Identity User Pool and its client ID. */ CognitoIdentityProviders?: CognitoIdentityProviderList; /** * An array of Amazon Resource Names (ARNs) of the SAML provider for your identity pool. */ SamlProviderARNs?: SAMLProviderList; } export type IdentityPoolId = string; export type IdentityPoolName = string; export interface IdentityPoolShortDescription { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId?: IdentityPoolId; /** * A string that you provide. */ IdentityPoolName?: IdentityPoolName; } export type IdentityPoolUnauthenticated = boolean; export type IdentityPoolsList = IdentityPoolShortDescription[]; export type IdentityProviderId = string; export type IdentityProviderName = string; export type IdentityProviderToken = string; export type IdentityProviders = {[key: string]: IdentityProviderId}; export interface ListIdentitiesInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * The maximum number of identities to return. */ MaxResults: QueryLimit; /** * A pagination token. */ NextToken?: PaginationKey; /** * An optional boolean parameter that allows you to hide disabled identities. If omitted, the ListIdentities API will include disabled identities in the response. */ HideDisabled?: HideDisabled; } export interface ListIdentitiesResponse { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId?: IdentityPoolId; /** * An object containing a set of identities and associated mappings. */ Identities?: IdentitiesList; /** * A pagination token. */ NextToken?: PaginationKey; } export interface ListIdentityPoolsInput { /** * The maximum number of identities to return. */ MaxResults: QueryLimit; /** * A pagination token. */ NextToken?: PaginationKey; } export interface ListIdentityPoolsResponse { /** * The identity pools returned by the ListIdentityPools action. */ IdentityPools?: IdentityPoolsList; /** * A pagination token. */ NextToken?: PaginationKey; } export type LoginsList = IdentityProviderName[]; export type LoginsMap = {[key: string]: IdentityProviderToken}; export interface LookupDeveloperIdentityInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * A unique ID used by your backend authentication process to identify a user. Typically, a developer identity provider would issue many developer user identifiers, in keeping with the number of users. */ DeveloperUserIdentifier?: DeveloperUserIdentifier; /** * The maximum number of identities to return. */ MaxResults?: QueryLimit; /** * A pagination token. The first call you make will have NextToken set to null. After that the service will return NextToken values as needed. For example, let's say you make a request with MaxResults set to 10, and there are 20 matches in the database. The service will return a pagination token as a part of the response. This token can be used to call the API again and get results starting from the 11th match. */ NextToken?: PaginationKey; } export interface LookupDeveloperIdentityResponse { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * This is the list of developer user identifiers associated with an identity ID. Cognito supports the association of multiple developer user identifiers with an identity ID. */ DeveloperUserIdentifierList?: DeveloperUserIdentifierList; /** * A pagination token. The first call you make will have NextToken set to null. After that the service will return NextToken values as needed. For example, let's say you make a request with MaxResults set to 10, and there are 20 matches in the database. The service will return a pagination token as a part of the response. This token can be used to call the API again and get results starting from the 11th match. */ NextToken?: PaginationKey; } export interface MappingRule { /** * The claim name that must be present in the token, for example, "isAdmin" or "paid". */ Claim: ClaimName; /** * The match condition that specifies how closely the claim value in the IdP token must match Value. */ MatchType: MappingRuleMatchType; /** * A brief string that the claim must match, for example, "paid" or "yes". */ Value: ClaimValue; /** * The role ARN. */ RoleARN: ARNString; } export type MappingRuleMatchType = "Equals"|"Contains"|"StartsWith"|"NotEqual"|string; export type MappingRulesList = MappingRule[]; export interface MergeDeveloperIdentitiesInput { /** * User identifier for the source user. The value should be a DeveloperUserIdentifier. */ SourceUserIdentifier: DeveloperUserIdentifier; /** * User identifier for the destination user. The value should be a DeveloperUserIdentifier. */ DestinationUserIdentifier: DeveloperUserIdentifier; /** * The "domain" by which Cognito will refer to your users. This is a (pseudo) domain name that you provide while creating an identity pool. This name acts as a placeholder that allows your backend and the Cognito service to communicate about the developer provider. For the DeveloperProviderName, you can use letters as well as period (.), underscore (_), and dash (-). */ DeveloperProviderName: DeveloperProviderName; /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; } export interface MergeDeveloperIdentitiesResponse { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; } export type OIDCProviderList = ARNString[]; export type OIDCToken = string; export type PaginationKey = string; export type QueryLimit = number; export interface RoleMapping { /** * The role mapping type. Token will use cognito:roles and cognito:preferred_role claims from the Cognito identity provider token to map groups to roles. Rules will attempt to match claims from the token to map to a role. */ Type: RoleMappingType; /** * If you specify Token or Rules as the Type, AmbiguousRoleResolution is required. Specifies the action to be taken if either no rules match the claim value for the Rules type, or there is no cognito:preferred_role claim and there are multiple cognito:roles matches for the Token type. */ AmbiguousRoleResolution?: AmbiguousRoleResolutionType; /** * The rules to be used for mapping users to roles. If you specify Rules as the role mapping type, RulesConfiguration is required. */ RulesConfiguration?: RulesConfigurationType; } export type RoleMappingMap = {[key: string]: RoleMapping}; export type RoleMappingType = "Token"|"Rules"|string; export type RoleType = string; export type RolesMap = {[key: string]: ARNString}; export interface RulesConfigurationType { /** * An array of rules. You can specify up to 25 rules per identity provider. Rules are evaluated in order. The first one to match specifies the role. */ Rules: MappingRulesList; } export type SAMLProviderList = ARNString[]; export type SecretKeyString = string; export type SessionTokenString = string; export interface SetIdentityPoolRolesInput { /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * The map of roles associated with this pool. For a given role, the key will be either "authenticated" or "unauthenticated" and the value will be the Role ARN. */ Roles: RolesMap; /** * How users for a specific identity provider are to mapped to roles. This is a string to RoleMapping object map. The string identifies the identity provider, for example, "graph.facebook.com" or "cognito-idp-east-1.amazonaws.com/us-east-1_abcdefghi:app_client_id". Up to 25 rules can be specified per identity provider. */ RoleMappings?: RoleMappingMap; } export type String = string; export type TokenDuration = number; export interface UnlinkDeveloperIdentityInput { /** * A unique identifier in the format REGION:GUID. */ IdentityId: IdentityId; /** * An identity pool ID in the format REGION:GUID. */ IdentityPoolId: IdentityPoolId; /** * The "domain" by which Cognito will refer to your users. */ DeveloperProviderName: DeveloperProviderName; /** * A unique ID used by your backend authentication process to identify a user. */ DeveloperUserIdentifier: DeveloperUserIdentifier; } export interface UnlinkIdentityInput { /** * A unique identifier in the format REGION:GUID. */ IdentityId: IdentityId; /** * A set of optional name-value pairs that map provider names to provider tokens. */ Logins: LoginsMap; /** * Provider names to unlink from this identity. */ LoginsToRemove: LoginsList; } export interface UnprocessedIdentityId { /** * A unique identifier in the format REGION:GUID. */ IdentityId?: IdentityId; /** * The error code indicating the type of error that occurred. */ ErrorCode?: ErrorCode; } export type UnprocessedIdentityIdList = UnprocessedIdentityId[]; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2014-06-30"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the CognitoIdentity client. */ export import Types = CognitoIdentity; } export = CognitoIdentity;
the_stack
import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; import * as sinon from 'sinon'; import {describe, it} from 'mocha'; import {LongrunningDescriptor} from '../../src'; import * as operationProtos from '../../protos/operations'; import {GaxCallPromise} from '../../src/apitypes'; import * as gax from '../../src/gax'; import {GoogleError} from '../../src/googleError'; import * as longrunning from '../../src/longRunningCalls/longrunning'; import {OperationsClient} from '../../src/operationsClient'; import * as utils from './utils'; import {AnyDecoder} from '../../src/longRunningCalls/longRunningDescriptor'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const FAKE_STATUS_CODE_1 = (utils as any).FAKE_STATUS_CODE_1; const RESPONSE_VAL = 'response'; const RESPONSE = { typyeUrl: 'mock.proto.message', value: Buffer.from(RESPONSE_VAL), }; const METADATA_VAL = 'metadata'; const METADATA = { typeUrl: 'mock.proto.Message', value: Buffer.from(METADATA_VAL), }; const OPERATION_NAME = 'operation_name'; const SUCCESSFUL_OP = { result: 'response', name: OPERATION_NAME, metadata: METADATA, done: true, error: null, response: RESPONSE, }; const PENDING_OP = { result: null, name: OPERATION_NAME, metadata: METADATA, done: false, error: null, response: null, }; const ERROR = { code: FAKE_STATUS_CODE_1, message: 'operation error', }; const ERROR_OP = { result: 'error', name: OPERATION_NAME, metadata: METADATA, done: true, error: ERROR, response: null, }; const BAD_OP = { name: OPERATION_NAME, metadata: METADATA, done: true, }; const mockDecoder = (val: {}) => { return val.toString(); }; function createApiCall(func: Function, client?: OperationsClient) { const descriptor = new LongrunningDescriptor( client!, mockDecoder as unknown as AnyDecoder, mockDecoder as unknown as AnyDecoder ); return utils.createApiCall(func, {descriptor}) as GaxCallPromise; } interface SpyableOperationsClient extends OperationsClient { getOperation: sinon.SinonSpy & longrunning.Operation; cancelOperation: sinon.SinonSpy; cancelGetOperationSpy: sinon.SinonSpy; } describe('longrunning', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any function mockOperationsClient(opts?: any): SpyableOperationsClient { opts = opts || {}; let remainingCalls = opts.expectedCalls ? opts.expectedCalls : null; const cancelGetOperationSpy = sinon.spy(); const getOperationSpy = sinon.spy(() => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let resolver: any; const promise = new Promise(resolve => { resolver = resolve; }); // eslint-disable-next-line @typescript-eslint/no-explicit-any (promise as any).cancel = cancelGetOperationSpy; if (remainingCalls && remainingCalls > 1) { resolver([PENDING_OP]); --remainingCalls; } else if (!opts.dontResolve) { resolver([opts.finalOperation || SUCCESSFUL_OP]); } return promise; }); const cancelOperationSpy = sinon.spy(() => { return Promise.resolve(); }); return { getOperationInternal: getOperationSpy, getOperation: getOperationSpy, cancelOperation: cancelOperationSpy, cancelGetOperationSpy, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any; } describe('createApiCall', () => { it('longrunning call resolves to the correct datatypes', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const defaultInitialRetryDelayMillis = 100; const defaultRetryDelayMultiplier = 1.3; const defaultMaxRetryDelayMillis = 60000; const defaultTotalTimeoutMillis = null; const apiCall = createApiCall(func); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; const rawResponse = responses[1]; assert(operation instanceof Object); assert(operation.hasOwnProperty('backoffSettings')); assert.strictEqual( operation.backoffSettings.initialRetryDelayMillis, defaultInitialRetryDelayMillis ); assert.strictEqual( operation.backoffSettings.retryDelayMultiplier, defaultRetryDelayMultiplier ); assert.strictEqual( operation.backoffSettings.maxRetryDelayMillis, defaultMaxRetryDelayMillis ); assert.strictEqual( operation.backoffSettings.totalTimeoutMillis, defaultTotalTimeoutMillis ); assert(operation.hasOwnProperty('longrunningDescriptor')); assert.strictEqual(operation.name, OPERATION_NAME); assert.strictEqual(operation.done, false); assert.deepStrictEqual(operation.latestResponse, PENDING_OP); assert.strictEqual(operation.result, null); assert.strictEqual(operation.metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, PENDING_OP); done(); }) .catch(done); }); }); describe('operation', () => { it('returns an Operation with correct values', done => { const client = mockOperationsClient(); const desc = new LongrunningDescriptor( client as OperationsClient, mockDecoder as unknown as AnyDecoder, mockDecoder as unknown as AnyDecoder ); const initialRetryDelayMillis = 1; const retryDelayMultiplier = 2; const maxRetryDelayMillis = 3; const totalTimeoutMillis = 4; const unusedRpcValue = 0; const backoff = gax.createBackoffSettings( initialRetryDelayMillis, retryDelayMultiplier, maxRetryDelayMillis, unusedRpcValue, unusedRpcValue, unusedRpcValue, totalTimeoutMillis ); const operation = longrunning.operation( SUCCESSFUL_OP as {} as operationProtos.google.longrunning.Operation, desc, backoff ); assert(operation instanceof Object); assert(operation.hasOwnProperty('backoffSettings')); assert.strictEqual( operation.backoffSettings.initialRetryDelayMillis, initialRetryDelayMillis ); assert.strictEqual( operation.backoffSettings.retryDelayMultiplier, retryDelayMultiplier ); assert.strictEqual( operation.backoffSettings.maxRetryDelayMillis, maxRetryDelayMillis ); assert.strictEqual( operation.backoffSettings.totalTimeoutMillis, totalTimeoutMillis ); assert(operation.hasOwnProperty('longrunningDescriptor')); assert.strictEqual(operation.name, OPERATION_NAME); assert.strictEqual(operation.done, true); assert.deepStrictEqual(operation.response, RESPONSE); assert.strictEqual(operation.result, RESPONSE_VAL); assert.strictEqual(operation.metadata, METADATA_VAL); assert.deepStrictEqual(operation.latestResponse, SUCCESSFUL_OP); done(); }); }); describe('Operation', () => { describe('getOperation', () => { it('does not make an api call if cached op is finished', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, SUCCESSFUL_OP); }; const client = mockOperationsClient(); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; operation.getOperation((err, result, metadata, rawResponse) => { if (err) { done(err); } assert.strictEqual(result, RESPONSE_VAL); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, SUCCESSFUL_OP); assert.strictEqual(client.getOperation.callCount, 0); done(); }); }) .catch(done); }); it('makes an api call to get the updated operation', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const client = mockOperationsClient(); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; operation.getOperation((err, result, metadata, rawResponse) => { if (err) { done(err); } assert.strictEqual(result, RESPONSE_VAL); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, SUCCESSFUL_OP); assert.strictEqual(client.getOperation.callCount, 1); done(); }); }) .catch(error => { done(error); }); }); it('does not return a promise when given a callback.', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const client = mockOperationsClient(); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; assert.strictEqual( operation.getOperation((err, result, metadata, rawResponse) => { if (err) { done(err); } assert.strictEqual(result, RESPONSE_VAL); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, SUCCESSFUL_OP); assert.strictEqual(client.getOperation.callCount, 1); done(); }), undefined ); }) .catch(error => { done(error); }); }); it('returns a promise that resolves to the correct data', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const client = mockOperationsClient(); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; return operation.getOperation(); }) .then((responses: {[name: string]: {}}) => { const result = responses[0]; const metadata = responses[1]; const rawResponse = responses[2]; assert.strictEqual(result, RESPONSE_VAL); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, SUCCESSFUL_OP); assert.strictEqual(client.getOperation.callCount, 1); done(); }) .catch(error => { done(error); }); }); it('returns a promise that rejects an operation error.', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, ERROR_OP); }; const client = mockOperationsClient(); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; return operation.getOperation(); }) .then(() => { done(new Error('Should not get here.')); }) .catch(error => { assert(error instanceof Error); done(); }); }); }); describe('promise', () => { it('resolves to the correct data', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const expectedCalls = 3; const client = mockOperationsClient({expectedCalls}); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; return operation.promise(); }) .then(responses => { const [result, metadata, rawResponse] = responses as Array<{}>; assert.strictEqual(result, RESPONSE_VAL); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, SUCCESSFUL_OP); assert.strictEqual(client.getOperation.callCount, expectedCalls); done(); }) .catch(err => { done(err); }); }); it('resolves if operation completes immediately', async () => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, SUCCESSFUL_OP); }; const client = mockOperationsClient({expectedCalls: 0}); const apiCall = createApiCall(func, client); const [operation] = (await apiCall({})) as unknown as [ longrunning.Operation ]; assert.notStrictEqual(operation, null); const [finalResult] = (await operation!.promise()) as unknown as [ string ]; assert.strictEqual(finalResult, RESPONSE_VAL); }); it('resolves error', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const expectedCalls = 3; const client = mockOperationsClient({ expectedCalls, finalOperation: ERROR_OP, }); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; return operation.promise(); }) .then(() => { done(new Error('should not get here')); }) .catch(err => { assert.strictEqual(client.getOperation.callCount, expectedCalls); assert.strictEqual(err.code, FAKE_STATUS_CODE_1); assert.strictEqual(err.message, 'operation error'); done(); }); }); it('does not hang on invalid API response', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const client = mockOperationsClient({finalOperation: BAD_OP}); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; const promise = operation.promise() as Promise<[{}, {}, {}]>; return promise; }) .then(([response, metadata, rawResponse]) => { assert.deepStrictEqual(response, {}); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, BAD_OP); done(); }) .catch(done); }); }); describe('cancel', () => { it('cancels the Operation and the current api call', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const client = mockOperationsClient({ dontResolve: true, }); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; const p = operation.promise(); operation.cancel().then(() => { assert.strictEqual(client.cancelOperation.called, true); assert.strictEqual(client.cancelGetOperationSpy.called, true); done(); }); return p; }) .then(() => { done(new Error('should not get here')); }) .catch(err => { done(err); }); }); }); describe('polling', () => { it('succesful operation emits complete', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const expectedCalls = 3; const client = mockOperationsClient({ expectedCalls, }); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; operation.on('complete', (result, metadata, rawResponse) => { assert.strictEqual(result, RESPONSE_VAL); assert.strictEqual(metadata, METADATA_VAL); assert.deepStrictEqual(rawResponse, SUCCESSFUL_OP); assert.strictEqual(client.getOperation.callCount, expectedCalls); done(); }); operation.on('error', () => { done('should not get here'); }); }) .catch(err => { done(err); }); }); it('operation error emits an error', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const expectedCalls = 3; const client = mockOperationsClient({ expectedCalls, finalOperation: ERROR_OP, }); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; operation.on('complete', () => { done(new Error('Should not get here.')); }); operation.on('error', err => { assert.strictEqual(client.getOperation.callCount, expectedCalls); assert.strictEqual(err.code, FAKE_STATUS_CODE_1); assert.strictEqual(err.message, 'operation error'); done(); }); }) .catch(err => { done(err); }); }); it('emits progress on updated operations.', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const updatedMetadataVal = 'updated'; const updatedMetadata = { typeUrl: 'mock.proto.Message', value: Buffer.from(updatedMetadataVal), }; const updatedOp = { result: null, name: OPERATION_NAME, metadata: updatedMetadata, done: false, error: null, response: null, }; const expectedCalls = 3; const client = mockOperationsClient({ expectedCalls, finalOperation: updatedOp, }); const apiCall = createApiCall(func, client); apiCall({}) .then(responses => { const operation = responses[0] as longrunning.Operation; operation.on('complete', () => { done(new Error('Should not get here.')); }); operation.on('progress', (metadata, rawResponse) => { assert.strictEqual(client.getOperation.callCount, expectedCalls); assert.strictEqual(metadata, updatedMetadataVal); assert.deepStrictEqual(rawResponse, updatedOp); assert.deepStrictEqual(operation.metadata, metadata); assert.strictEqual(operation.metadata, updatedMetadataVal); // Shows that progress only happens on updated operations since // this will produce a test error if done is called multiple // times, and the same pending operation was polled thrice. operation.removeAllListeners(); done(); }); }) .catch(err => { done(err); }); }); it('times out when polling', done => { const func = ( argument: {}, metadata: {}, options: {}, callback: Function ) => { callback(null, PENDING_OP); }; const client = mockOperationsClient({ finalOperation: PENDING_OP, }); const apiCall = createApiCall(func, client); // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore incomplete options apiCall( {}, { longrunning: gax.createBackoffSettings(1, 1, 1, 0, 0, 0, 1), } ) .then(responses => { const operation = responses[0] as longrunning.Operation; operation.on('complete', () => { done(new Error('Should not get here.')); }); operation.on('error', err => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); assert.strictEqual( err!.message, 'Total timeout exceeded before ' + 'any response was received' ); done(); }); }) .catch(err => { done(err); }); }); }); }); });
the_stack
'use strict'; import cp = require('child_process'); import path = require('path'); import vscode = require('vscode'); import { promptForMissingTool, promptForUpdatingTool } from './goInstallTools'; import { getModFolderPath, promptToUpdateToolForModules } from './goModules'; import { byteOffsetAt, getBinPath, getFileArchive, getGoConfig, getModuleCache, getToolsEnvVars, getWorkspaceFolderPath, goKeywords, isPositionInString, killTree, runGodoc } from './util'; const missingToolMsg = 'Missing tool: '; export interface GoDefinitionInformation { file: string; line: number; column: number; doc: string; declarationlines: string[]; name: string; toolUsed: string; } interface GoDefinitionInput { document: vscode.TextDocument; position: vscode.Position; word: string; includeDocs: boolean; isMod: boolean; cwd: string; } interface GoGetDocOuput { name: string; import: string; decl: string; doc: string; pos: string; } interface GuruDefinitionOuput { objpos: string; desc: string; } export function definitionLocation( document: vscode.TextDocument, position: vscode.Position, goConfig: vscode.WorkspaceConfiguration, includeDocs: boolean, token: vscode.CancellationToken ): Promise<GoDefinitionInformation> { const adjustedPos = adjustWordPosition(document, position); if (!adjustedPos[0]) { return Promise.resolve(null); } const word = adjustedPos[1]; position = adjustedPos[2]; if (!goConfig) { goConfig = getGoConfig(document.uri); } const toolForDocs = goConfig['docsTool'] || 'godoc'; return getModFolderPath(document.uri).then((modFolderPath) => { const input: GoDefinitionInput = { document, position, word, includeDocs, isMod: !!modFolderPath, cwd: modFolderPath && modFolderPath !== getModuleCache() ? modFolderPath : getWorkspaceFolderPath(document.uri) || path.dirname(document.fileName) }; if (toolForDocs === 'godoc') { return definitionLocation_godef(input, token); } else if (toolForDocs === 'guru') { return definitionLocation_guru(input, token); } return definitionLocation_gogetdoc(input, token, true); }); } export function adjustWordPosition( document: vscode.TextDocument, position: vscode.Position ): [boolean, string, vscode.Position] { const wordRange = document.getWordRangeAtPosition(position); const lineText = document.lineAt(position.line).text; const word = wordRange ? document.getText(wordRange) : ''; if ( !wordRange || lineText.startsWith('//') || isPositionInString(document, position) || word.match(/^\d+.?\d+$/) || goKeywords.indexOf(word) > 0 ) { return [false, null, null]; } if (position.isEqual(wordRange.end) && position.isAfter(wordRange.start)) { position = position.translate(0, -1); } return [true, word, position]; } const godefImportDefinitionRegex = /^import \(.* ".*"\)$/; function definitionLocation_godef( input: GoDefinitionInput, token: vscode.CancellationToken, useReceivers: boolean = true ): Promise<GoDefinitionInformation> { const godefTool = 'godef'; const godefPath = getBinPath(godefTool); if (!path.isAbsolute(godefPath)) { return Promise.reject(missingToolMsg + godefTool); } const offset = byteOffsetAt(input.document, input.position); const env = getToolsEnvVars(); let p: cp.ChildProcess; if (token) { token.onCancellationRequested(() => killTree(p.pid)); } return new Promise<GoDefinitionInformation>((resolve, reject) => { // Spawn `godef` process const args = ['-t', '-i', '-f', input.document.fileName, '-o', offset.toString()]; // if (useReceivers) { // args.push('-r'); // } p = cp.execFile(godefPath, args, { env, cwd: input.cwd }, (err, stdout, stderr) => { try { if (err && (<any>err).code === 'ENOENT') { return reject(missingToolMsg + godefTool); } if (err) { if ( input.isMod && !input.includeDocs && stderr && stderr.startsWith(`godef: no declaration found for`) ) { promptToUpdateToolForModules( 'godef', `To get the Go to Definition feature when using Go modules, please update your version of the "godef" tool.` ); return reject(stderr); } if (stderr.indexOf('flag provided but not defined: -r') !== -1) { promptForUpdatingTool('godef'); p = null; return definitionLocation_godef(input, token, false).then(resolve, reject); } return reject(err.message || stderr); } const result = stdout.toString(); const lines = result.split('\n'); let match = /(.*):(\d+):(\d+)/.exec(lines[0]); if (!match) { // TODO: Gotodef on pkg name: // /usr/local/go/src/html/template\n return resolve(null); } const [_, file, line, col] = match; const pkgPath = path.dirname(file); const definitionInformation: GoDefinitionInformation = { file, line: +line - 1, column: +col - 1, declarationlines: lines.slice(1), toolUsed: 'godef', doc: null, name: null }; if (!input.includeDocs || godefImportDefinitionRegex.test(definitionInformation.declarationlines[0])) { return resolve(definitionInformation); } match = /^\w+ \(\*?(\w+)\)/.exec(lines[1]); runGodoc(input.cwd, pkgPath, match ? match[1] : '', input.word, token) .then((doc) => { if (doc) { definitionInformation.doc = doc; } resolve(definitionInformation); }) .catch((runGoDocErr) => { console.log(runGoDocErr); resolve(definitionInformation); }); } catch (e) { reject(e); } }); if (p.pid) { p.stdin.end(input.document.getText()); } }); } function definitionLocation_gogetdoc( input: GoDefinitionInput, token: vscode.CancellationToken, useTags: boolean ): Promise<GoDefinitionInformation> { const gogetdoc = getBinPath('gogetdoc'); if (!path.isAbsolute(gogetdoc)) { return Promise.reject(missingToolMsg + 'gogetdoc'); } const offset = byteOffsetAt(input.document, input.position); const env = getToolsEnvVars(); let p: cp.ChildProcess; if (token) { token.onCancellationRequested(() => killTree(p.pid)); } return new Promise<GoDefinitionInformation>((resolve, reject) => { const gogetdocFlagsWithoutTags = [ '-u', '-json', '-modified', '-pos', input.document.fileName + ':#' + offset.toString() ]; const buildTags = getGoConfig(input.document.uri)['buildTags']; const gogetdocFlags = buildTags && useTags ? [...gogetdocFlagsWithoutTags, '-tags', buildTags] : gogetdocFlagsWithoutTags; p = cp.execFile(gogetdoc, gogetdocFlags, { env, cwd: input.cwd }, (err, stdout, stderr) => { try { if (err && (<any>err).code === 'ENOENT') { return reject(missingToolMsg + 'gogetdoc'); } if (stderr && stderr.startsWith('flag provided but not defined: -tags')) { p = null; return definitionLocation_gogetdoc(input, token, false).then(resolve, reject); } if (err) { if (input.isMod && !input.includeDocs && stdout.startsWith(`gogetdoc: couldn't get package for`)) { promptToUpdateToolForModules( 'gogetdoc', `To get the Go to Definition feature when using Go modules, please update your version of the "gogetdoc" tool.` ); return resolve(null); } return reject(err.message || stderr); } const goGetDocOutput = <GoGetDocOuput>JSON.parse(stdout.toString()); const match = /(.*):(\d+):(\d+)/.exec(goGetDocOutput.pos); const definitionInfo: GoDefinitionInformation = { file: null, line: 0, column: 0, toolUsed: 'gogetdoc', declarationlines: goGetDocOutput.decl.split('\n'), doc: goGetDocOutput.doc, name: goGetDocOutput.name }; if (!match) { return resolve(definitionInfo); } const [_, file, line, col] = match; definitionInfo.file = match[1]; definitionInfo.line = +match[2] - 1; definitionInfo.column = +match[3] - 1; return resolve(definitionInfo); } catch (e) { reject(e); } }); if (p.pid) { p.stdin.end(getFileArchive(input.document)); } }); } function definitionLocation_guru( input: GoDefinitionInput, token: vscode.CancellationToken ): Promise<GoDefinitionInformation> { const guru = getBinPath('guru'); if (!path.isAbsolute(guru)) { return Promise.reject(missingToolMsg + 'guru'); } const offset = byteOffsetAt(input.document, input.position); const env = getToolsEnvVars(); let p: cp.ChildProcess; if (token) { token.onCancellationRequested(() => killTree(p.pid)); } return new Promise<GoDefinitionInformation>((resolve, reject) => { p = cp.execFile( guru, ['-json', '-modified', 'definition', input.document.fileName + ':#' + offset.toString()], { env }, (err, stdout, stderr) => { try { if (err && (<any>err).code === 'ENOENT') { return reject(missingToolMsg + 'guru'); } if (err) { return reject(err.message || stderr); } const guruOutput = <GuruDefinitionOuput>JSON.parse(stdout.toString()); const match = /(.*):(\d+):(\d+)/.exec(guruOutput.objpos); const definitionInfo: GoDefinitionInformation = { file: null, line: 0, column: 0, toolUsed: 'guru', declarationlines: [guruOutput.desc], doc: null, name: null }; if (!match) { return resolve(definitionInfo); } const [_, file, line, col] = match; definitionInfo.file = match[1]; definitionInfo.line = +match[2] - 1; definitionInfo.column = +match[3] - 1; return resolve(definitionInfo); } catch (e) { reject(e); } } ); if (p.pid) { p.stdin.end(getFileArchive(input.document)); } }); } export function parseMissingError(err: any): [boolean, string] { if (err) { // Prompt for missing tool is located here so that the // prompts dont show up on hover or signature help if (typeof err === 'string' && err.startsWith(missingToolMsg)) { return [true, err.substr(missingToolMsg.length)]; } } return [false, null]; } export class GoDefinitionProvider implements vscode.DefinitionProvider { private goConfig: vscode.WorkspaceConfiguration = null; constructor(goConfig?: vscode.WorkspaceConfiguration) { this.goConfig = goConfig; } public provideDefinition( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken ): Thenable<vscode.Location> { return definitionLocation(document, position, this.goConfig, false, token).then( (definitionInfo) => { if (definitionInfo == null || definitionInfo.file == null) { return null; } const definitionResource = vscode.Uri.file(definitionInfo.file); const pos = new vscode.Position(definitionInfo.line, definitionInfo.column); return new vscode.Location(definitionResource, pos); }, (err) => { const miss = parseMissingError(err); if (miss[0]) { promptForMissingTool(miss[1]); } else if (err) { return Promise.reject(err); } return Promise.resolve(null); } ); } }
the_stack
import { assert, assertInstanceof, } from '../../../assert.js'; import { CaptureCandidate, ConstraintsPreferrer, PhotoConstraintsPreferrer, VideoConstraintsPreferrer, } from '../../../device/constraints_preferrer.js'; import {StreamConstraints} from '../../../device/stream_constraints.js'; import * as dom from '../../../dom.js'; import {DeviceOperator} from '../../../mojo/device_operator.js'; import {CaptureIntent} from '../../../mojo/type.js'; import * as state from '../../../state.js'; import { Facing, Mode, Resolution, } from '../../../type.js'; import {assertEnumVariant} from '../../../util.js'; import { ModeBase, ModeFactory, } from './mode_base.js'; import { PhotoFactory, PhotoHandler, } from './photo.js'; import {PortraitFactory, PortraitHandler} from './portrait.js'; import { ScanFactory, ScanHandler, } from './scan.js'; import {SquareFactory} from './square.js'; import { VideoFactory, VideoHandler, } from './video.js'; export {PhotoHandler, PhotoResult} from './photo.js'; export {getDefaultScanCorners, ScanHandler} from './scan.js'; export {setAvc1Parameters, Video, VideoHandler, VideoResult} from './video.js'; /** * Callback to trigger mode switching. Should return whether mode switching * succeed. */ export type DoSwitchMode = () => Promise<boolean>; /** * Parameters for capture settings. */ interface CaptureParams { mode: Mode; constraints: StreamConstraints; captureResolution: Resolution; videoSnapshotResolution: Resolution; } /** * The abstract interface for the mode configuration. */ interface ModeConfig { /** * @return Resolves to boolean indicating whether the mode is supported by * video device with specified device id. */ isSupported(deviceId: string): Promise<boolean>; isSupportPTZ(captureResolution: Resolution, previewResolution: Resolution): boolean; /** * Makes video capture device prepared for capturing in this mode. * @param constraints Constraints for preview stream. */ prepareDevice(constraints: StreamConstraints, captureResolution: Resolution): Promise<void>; /** * Get general stream constraints of this mode for fake cameras. */ getConstraintsForFakeCamera(deviceId: string|null): StreamConstraints[]; /** * Gets factory to create capture object for this mode. */ getCaptureFactory(): ModeFactory; /** * HALv3 constraints preferrer for this mode. */ readonly constraintsPreferrer: ConstraintsPreferrer; /** * Mode to be fallbacked to when fail to configure this mode. */ readonly fallbackMode: Mode; } /** * Mode controller managing capture sequence of different camera mode. */ export class Modes { /** * Capture controller of current camera mode. */ current: ModeBase|null = null; private readonly modesGroup = dom.get('#modes-group', HTMLElement); /** * Parameters to create mode capture controller. */ private captureParams: CaptureParams|null = null; /** * Mode classname and related functions and attributes. */ private readonly allModes: {[mode in Mode]: ModeConfig}; /** * @param defaultMode Default mode to be switched to. */ constructor( defaultMode: Mode, photoPreferrer: PhotoConstraintsPreferrer, videoPreferrer: VideoConstraintsPreferrer, private readonly doSwitchMode: DoSwitchMode, handler: PhotoHandler&PortraitHandler&ScanHandler&VideoHandler, ) { /** * Returns a set of general constraints for fake cameras. * @param videoMode Is getting constraints for video mode. * @param deviceId Id of video device. * @return Result of constraints-candidates. */ const getConstraintsForFakeCamera = function( videoMode: boolean, deviceId: string): StreamConstraints[] { const frameRate = {min: 20, ideal: 30}; return [ { deviceId, audio: videoMode, video: { aspectRatio: {ideal: videoMode ? 1.7777777778 : 1.3333333333}, width: {min: 1280}, frameRate, }, }, { deviceId, audio: videoMode, video: { width: {min: 640}, frameRate, }, }, ]; }; // Workaround for b/184089334 on PTZ camera to use preview frame as photo // result. const checkSupportPTZForPhotoMode = (captureResolution, previewResolution) => captureResolution.equals(previewResolution); // clang-format format this wrong if we use async (...) => {...} (missing a // space after async). Using async function instead to get around this. // TODO(pihsun): style guide recommends using function xxx() instead of // lambda anyway, change other location too. async function prepareDeviceForPhoto( constraints: StreamConstraints, resolution: Resolution, captureIntent: CaptureIntent): Promise<void> { const deviceOperator = await DeviceOperator.getInstance(); if (deviceOperator === null) { return; } const deviceId = constraints.deviceId; await deviceOperator.setCaptureIntent(deviceId, captureIntent); await deviceOperator.setStillCaptureResolution(deviceId, resolution); } this.allModes = { [Mode.VIDEO]: { getCaptureFactory: () => { const params = this.getCaptureParams(); return new VideoFactory( params.constraints, params.captureResolution, params.videoSnapshotResolution, handler); }, isSupported: async () => true, isSupportPTZ: () => true, prepareDevice: async (constraints) => { const deviceOperator = await DeviceOperator.getInstance(); if (deviceOperator === null) { return; } const deviceId = constraints.deviceId; await deviceOperator.setCaptureIntent( deviceId, CaptureIntent.VIDEO_RECORD); if (await deviceOperator.isBlobVideoSnapshotEnabled(deviceId)) { await deviceOperator.setStillCaptureResolution( deviceId, this.getCaptureParams().videoSnapshotResolution); } let minFrameRate = 0; let maxFrameRate = 0; if (constraints.video && constraints.video.frameRate) { const frameRate = constraints.video.frameRate; if (typeof frameRate === 'number') { minFrameRate = frameRate; maxFrameRate = frameRate; } else if (frameRate.exact) { minFrameRate = frameRate.exact; maxFrameRate = frameRate.exact; } else if (frameRate.min && frameRate.max) { minFrameRate = frameRate.min; maxFrameRate = frameRate.max; } // TODO(wtlee): To set the fps range to the default value, we should // remove the frameRate from constraints instead of using incomplete // range. } await deviceOperator.setFpsRange( deviceId, minFrameRate, maxFrameRate); }, constraintsPreferrer: videoPreferrer, getConstraintsForFakeCamera: getConstraintsForFakeCamera.bind(this, true), fallbackMode: Mode.PHOTO, }, [Mode.PHOTO]: { getCaptureFactory: () => { const params = this.getCaptureParams(); return new PhotoFactory( params.constraints, params.captureResolution, handler); }, isSupported: async () => true, isSupportPTZ: checkSupportPTZForPhotoMode, prepareDevice: async (constraints, resolution) => prepareDeviceForPhoto( constraints, resolution, CaptureIntent.STILL_CAPTURE), constraintsPreferrer: photoPreferrer, getConstraintsForFakeCamera: getConstraintsForFakeCamera.bind(this, false), fallbackMode: Mode.SQUARE, }, [Mode.SQUARE]: { getCaptureFactory: () => { const params = this.getCaptureParams(); return new SquareFactory( params.constraints, params.captureResolution, handler); }, isSupported: async () => true, isSupportPTZ: checkSupportPTZForPhotoMode, prepareDevice: async (constraints, resolution) => prepareDeviceForPhoto( constraints, resolution, CaptureIntent.STILL_CAPTURE), constraintsPreferrer: photoPreferrer, getConstraintsForFakeCamera: getConstraintsForFakeCamera.bind(this, false), fallbackMode: Mode.PHOTO, }, [Mode.PORTRAIT]: { getCaptureFactory: () => { const params = this.getCaptureParams(); return new PortraitFactory( params.constraints, params.captureResolution, handler); }, isSupported: async (deviceId) => { if (deviceId === null) { return false; } const deviceOperator = await DeviceOperator.getInstance(); if (deviceOperator === null) { return false; } return await deviceOperator.isPortraitModeSupported(deviceId); }, isSupportPTZ: checkSupportPTZForPhotoMode, prepareDevice: async (constraints, resolution) => prepareDeviceForPhoto( constraints, resolution, CaptureIntent.STILL_CAPTURE), constraintsPreferrer: photoPreferrer, getConstraintsForFakeCamera: getConstraintsForFakeCamera.bind(this, false), fallbackMode: Mode.PHOTO, }, [Mode.SCAN]: { getCaptureFactory: () => { const params = this.getCaptureParams(); return new ScanFactory( params.constraints, params.captureResolution, handler); }, isSupported: async () => state.get(state.State.SHOW_SCAN_MODE), isSupportPTZ: checkSupportPTZForPhotoMode, prepareDevice: async (constraints, resolution) => prepareDeviceForPhoto( constraints, resolution, CaptureIntent.DOCUMENT), constraintsPreferrer: photoPreferrer, getConstraintsForFakeCamera: getConstraintsForFakeCamera.bind(this, false), fallbackMode: Mode.PHOTO, }, }; dom.getAll('.mode-item>input', HTMLInputElement).forEach((element) => { element.addEventListener('click', (event) => { if (!state.get(state.State.STREAMING) || state.get(state.State.TAKING)) { event.preventDefault(); } }); element.addEventListener('change', async () => { if (element.checked) { const mode = assertEnumVariant(Mode, element.dataset['mode']); this.updateModeUI(mode); state.set(state.State.MODE_SWITCHING, true); const isSuccess = await this.doSwitchMode(); state.set(state.State.MODE_SWITCHING, false, {hasError: !isSuccess}); } }); }); [state.State.EXPERT, state.State.SAVE_METADATA].forEach((s) => { state.addObserver(s, () => { this.updateSaveMetadata(); }); }); // Set default mode when app started. this.updateModeUI(defaultMode); } private get allModeNames(): Mode[] { return Object.values(Mode); } private getCaptureParams(): CaptureParams { assert(this.captureParams !== null); return this.captureParams; } /** * Updates state of mode related UI to the target mode. */ private updateModeUI(mode: Mode) { this.allModeNames.forEach((m) => state.set(m, m === mode)); const element = dom.get(`.mode-item>input[data-mode=${mode}]`, HTMLInputElement); element.checked = true; const wrapper = assertInstanceof(element.parentElement, HTMLDivElement); const scrollLeft = wrapper.offsetLeft - (this.modesGroup.offsetWidth - wrapper.offsetWidth) / 2; this.modesGroup.scrollTo({ left: scrollLeft, top: 0, behavior: 'smooth', }); } /** * Gets all mode candidates. Desired trying sequence of candidate modes is * reflected in the order of the returned array. */ getModeCandidates(): Mode[] { const tried = {}; const results: Mode[] = []; let mode = this.allModeNames.find((mode) => state.get(mode)); assert(mode !== undefined); while (!tried[mode]) { tried[mode] = true; results.push(mode); mode = this.allModes[mode].fallbackMode; } return results; } /** * Gets all available capture resolution and its corresponding preview * constraints for the given |mode| and |deviceId|. */ getResolutionCandidates(mode: Mode, deviceId: string): CaptureCandidate[] { return this.allModes[mode].constraintsPreferrer.getSortedCandidates( deviceId); } /** * Gets a general set of resolution candidates given by |mode| and |deviceId| * for fake cameras. */ getFakeResolutionCandidates(mode: Mode, deviceId: string): CaptureCandidate[] { const previewCandidates = this.allModes[mode].getConstraintsForFakeCamera(deviceId); return [{resolution: null, previewCandidates}]; } /** * Gets factory to create mode capture object. */ getModeFactory(mode: Mode): ModeFactory { return this.allModes[mode].getCaptureFactory(); } /** * @param constraints Constraints for preview stream. */ setCaptureParams( mode: Mode, constraints: StreamConstraints, captureResolution: Resolution, videoSnapshotResolution: Resolution): void { this.captureParams = {mode, constraints, captureResolution, videoSnapshotResolution}; } /** * Makes video capture device prepared for capturing in this mode. */ async prepareDevice(): Promise<void> { if (state.get(state.State.USE_FAKE_CAMERA)) { return; } const {mode, captureResolution, constraints} = this.getCaptureParams(); return this.allModes[mode].prepareDevice( constraints, assertInstanceof(captureResolution, Resolution)); } /** * Gets supported modes for video device of given device id. * @param deviceId Device id of the video device. * @return All supported mode for the video device. */ async getSupportedModes(deviceId: string): Promise<Mode[]> { const supportedModes: Mode[] = []; for (const mode of this.allModeNames) { const obj = this.allModes[mode]; if (await obj.isSupported(deviceId)) { supportedModes.push(mode); } } return supportedModes; } isSupportPTZ( mode: Mode, captureResolution: Resolution, previewResolution: Resolution): boolean { return this.allModes[mode].isSupportPTZ( captureResolution, previewResolution); } /** * Updates mode selection UI according to given device id. */ async updateModeSelectionUI(deviceId: string): Promise<void> { const supportedModes = await this.getSupportedModes(deviceId); const items = dom.getAll('div.mode-item', HTMLDivElement); let first = null; let last = null; items.forEach((el) => { const radio = dom.getFrom(el, 'input[type=radio]', HTMLInputElement); const supported = (supportedModes as string[]).includes(radio.dataset['mode']); el.classList.toggle('hide', !supported); if (supported) { if (first === null) { first = el; } last = el; } }); items.forEach((el) => { el.classList.toggle('first', el === first); el.classList.toggle('last', el === last); }); } /** * Creates and updates current mode object. * @param factory The factory ready for producing mode capture object. * @param stream Stream of the new switching mode. * @param facing Camera facing of the current mode. * @param deviceId Device id of currently working video device. */ async updateMode( factory: ModeFactory, stream: MediaStream, facing: Facing, deviceId: string|null): Promise<void> { if (this.current !== null) { await this.current.clear(); await this.disableSaveMetadata(); } const {mode, captureResolution} = this.getCaptureParams(); this.updateModeUI(mode); this.current = factory.produce(); if (deviceId && captureResolution) { this.allModes[mode].constraintsPreferrer.updateValues( deviceId, stream, facing, captureResolution); } await this.updateSaveMetadata(); } /** * Clears everything when mode is not needed anymore. */ async clear(): Promise<void> { if (this.current !== null) { await this.current.clear(); await this.disableSaveMetadata(); } this.captureParams = null; this.current = null; } /** * Checks whether to save image metadata or not. * @return Promise for the operation. */ private async updateSaveMetadata(): Promise<void> { if (state.get(state.State.EXPERT) && state.get(state.State.SAVE_METADATA)) { await this.enableSaveMetadata(); } else { await this.disableSaveMetadata(); } } /** * Enables save metadata of subsequent photos in the current mode. * @return Promise for the operation. */ private async enableSaveMetadata(): Promise<void> { if (this.current !== null) { await this.current.addMetadataObserver(); } } /** * Disables save metadata of subsequent photos in the current mode. * @return Promise for the operation. */ private async disableSaveMetadata(): Promise<void> { if (this.current !== null) { await this.current.removeMetadataObserver(); } } }
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace recommender_v1beta1 { export interface Options extends GlobalOptions { version: 'v1beta1'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Recommender API * * * * @example * ```js * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * ``` */ export class Recommender { context: APIRequestContext; billingAccounts: Resource$Billingaccounts; folders: Resource$Folders; organizations: Resource$Organizations; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.billingAccounts = new Resource$Billingaccounts(this.context); this.folders = new Resource$Folders(this.context); this.organizations = new Resource$Organizations(this.context); this.projects = new Resource$Projects(this.context); } } /** * Contains metadata about how much money a recommendation can save or incur. */ export interface Schema$GoogleCloudRecommenderV1beta1CostProjection { /** * An approximate projection on amount saved or amount incurred. Negative cost units indicate cost savings and positive cost units indicate increase. See google.type.Money documentation for positive/negative units. A user's permissions may affect whether the cost is computed using list prices or custom contract prices. */ cost?: Schema$GoogleTypeMoney; /** * Duration for which this cost applies. */ duration?: string | null; } /** * Contains the impact a recommendation can have for a given category. */ export interface Schema$GoogleCloudRecommenderV1beta1Impact { /** * Category that is being targeted. */ category?: string | null; /** * Use with CategoryType.COST */ costProjection?: Schema$GoogleCloudRecommenderV1beta1CostProjection; /** * Use with CategoryType.SECURITY */ securityProjection?: Schema$GoogleCloudRecommenderV1beta1SecurityProjection; /** * Use with CategoryType.SUSTAINABILITY */ sustainabilityProjection?: Schema$GoogleCloudRecommenderV1beta1SustainabilityProjection; } /** * An insight along with the information used to derive the insight. The insight may have associated recomendations as well. */ export interface Schema$GoogleCloudRecommenderV1beta1Insight { /** * Recommendations derived from this insight. */ associatedRecommendations?: Schema$GoogleCloudRecommenderV1beta1InsightRecommendationReference[]; /** * Category being targeted by the insight. */ category?: string | null; /** * A struct of custom fields to explain the insight. Example: "grantedPermissionsCount": "1000" */ content?: {[key: string]: any} | null; /** * Free-form human readable summary in English. The maximum length is 500 characters. */ description?: string | null; /** * Fingerprint of the Insight. Provides optimistic locking when updating states. */ etag?: string | null; /** * Insight subtype. Insight content schema will be stable for a given subtype. */ insightSubtype?: string | null; /** * Timestamp of the latest data used to generate the insight. */ lastRefreshTime?: string | null; /** * Name of the insight. */ name?: string | null; /** * Observation period that led to the insight. The source data used to generate the insight ends at last_refresh_time and begins at (last_refresh_time - observation_period). */ observationPeriod?: string | null; /** * Insight's severity. */ severity?: string | null; /** * Information state and metadata. */ stateInfo?: Schema$GoogleCloudRecommenderV1beta1InsightStateInfo; /** * Fully qualified resource names that this insight is targeting. */ targetResources?: string[] | null; } /** * Reference to an associated recommendation. */ export interface Schema$GoogleCloudRecommenderV1beta1InsightRecommendationReference { /** * Recommendation resource name, e.g. projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendations/[RECOMMENDATION_ID] */ recommendation?: string | null; } /** * Information related to insight state. */ export interface Schema$GoogleCloudRecommenderV1beta1InsightStateInfo { /** * Insight state. */ state?: string | null; /** * A map of metadata for the state, provided by user or automations systems. */ stateMetadata?: {[key: string]: string} | null; } /** * Configuration for an InsightType. */ export interface Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig { /** * Allows clients to store small amounts of arbitrary data. Annotations must follow the Kubernetes syntax. The total size of all keys and values combined is limited to 256k. Key can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ annotations?: {[key: string]: string} | null; /** * A user-settable field to provide a human-readable name to be used in user interfaces. */ displayName?: string | null; /** * Fingerprint of the InsightTypeConfig. Provides optimistic locking when updating. */ etag?: string | null; /** * InsightTypeGenerationConfig which configures the generation of insights for this insight type. */ insightTypeGenerationConfig?: Schema$GoogleCloudRecommenderV1beta1InsightTypeGenerationConfig; /** * Name of insight type config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/config */ name?: string | null; /** * Output only. Immutable. The revision ID of the config. A new revision is committed whenever the config is changed in any way. The format is an 8-character hexadecimal string. */ revisionId?: string | null; /** * Last time when the config was updated. */ updateTime?: string | null; } /** * A configuration to customize the generation of insights. Eg, customizing the lookback period considered when generating a insight. */ export interface Schema$GoogleCloudRecommenderV1beta1InsightTypeGenerationConfig { /** * Parameters for this InsightTypeGenerationConfig. These configs can be used by or are applied to all subtypes. */ params?: {[key: string]: any} | null; } /** * Response to the `ListInsights` method. */ export interface Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse { /** * The set of insights for the `parent` resource. */ insights?: Schema$GoogleCloudRecommenderV1beta1Insight[]; /** * A token that can be used to request the next page of results. This field is empty if there are no additional results. */ nextPageToken?: string | null; } /** * Response to the `ListRecommendations` method. */ export interface Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse { /** * A token that can be used to request the next page of results. This field is empty if there are no additional results. */ nextPageToken?: string | null; /** * The set of recommendations for the `parent` resource. */ recommendations?: Schema$GoogleCloudRecommenderV1beta1Recommendation[]; } /** * Request for the `MarkInsightAccepted` method. */ export interface Schema$GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest { /** * Required. Fingerprint of the Insight. Provides optimistic locking. */ etag?: string | null; /** * Optional. State properties user wish to include with this state. Full replace of the current state_metadata. */ stateMetadata?: {[key: string]: string} | null; } /** * Request for the `MarkRecommendationClaimed` Method. */ export interface Schema$GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest { /** * Required. Fingerprint of the Recommendation. Provides optimistic locking. */ etag?: string | null; /** * State properties to include with this state. Overwrites any existing `state_metadata`. Keys must match the regex `/^a-z0-9{0,62\}$/`. Values must match the regex `/^[a-zA-Z0-9_./-]{0,255\}$/`. */ stateMetadata?: {[key: string]: string} | null; } /** * Request for the `MarkRecommendationFailed` Method. */ export interface Schema$GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest { /** * Required. Fingerprint of the Recommendation. Provides optimistic locking. */ etag?: string | null; /** * State properties to include with this state. Overwrites any existing `state_metadata`. Keys must match the regex `/^a-z0-9{0,62\}$/`. Values must match the regex `/^[a-zA-Z0-9_./-]{0,255\}$/`. */ stateMetadata?: {[key: string]: string} | null; } /** * Request for the `MarkRecommendationSucceeded` Method. */ export interface Schema$GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest { /** * Required. Fingerprint of the Recommendation. Provides optimistic locking. */ etag?: string | null; /** * State properties to include with this state. Overwrites any existing `state_metadata`. Keys must match the regex `/^a-z0-9{0,62\}$/`. Values must match the regex `/^[a-zA-Z0-9_./-]{0,255\}$/`. */ stateMetadata?: {[key: string]: string} | null; } /** * Contains an operation for a resource loosely based on the JSON-PATCH format with support for: * Custom filters for describing partial array patch. * Extended path values for describing nested arrays. * Custom fields for describing the resource for which the operation is being described. * Allows extension to custom operations not natively supported by RFC6902. See https://tools.ietf.org/html/rfc6902 for details on the original RFC. */ export interface Schema$GoogleCloudRecommenderV1beta1Operation { /** * Type of this operation. Contains one of 'add', 'remove', 'replace', 'move', 'copy', 'test' and 'custom' operations. This field is case-insensitive and always populated. */ action?: string | null; /** * Path to the target field being operated on. If the operation is at the resource level, then path should be "/". This field is always populated. */ path?: string | null; /** * Set of filters to apply if `path` refers to array elements or nested array elements in order to narrow down to a single unique element that is being tested/modified. This is intended to be an exact match per filter. To perform advanced matching, use path_value_matchers. * Example: ``` { "/versions/x/name" : "it-123" "/versions/x/targetSize/percent": 20 \} ``` * Example: ``` { "/bindings/x/role": "roles/owner" "/bindings/x/condition" : null \} ``` * Example: ``` { "/bindings/x/role": "roles/owner" "/bindings/x/members/x" : ["x@example.com", "y@example.com"] \} ``` When both path_filters and path_value_matchers are set, an implicit AND must be performed. */ pathFilters?: {[key: string]: any} | null; /** * Similar to path_filters, this contains set of filters to apply if `path` field refers to array elements. This is meant to support value matching beyond exact match. To perform exact match, use path_filters. When both path_filters and path_value_matchers are set, an implicit AND must be performed. */ pathValueMatchers?: { [key: string]: Schema$GoogleCloudRecommenderV1beta1ValueMatcher; } | null; /** * Contains the fully qualified resource name. This field is always populated. ex: //cloudresourcemanager.googleapis.com/projects/foo. */ resource?: string | null; /** * Type of GCP resource being modified/tested. This field is always populated. Example: cloudresourcemanager.googleapis.com/Project, compute.googleapis.com/Instance */ resourceType?: string | null; /** * Can be set with action 'copy' or 'move' to indicate the source field within resource or source_resource, ignored if provided for other operation types. */ sourcePath?: string | null; /** * Can be set with action 'copy' to copy resource configuration across different resources of the same type. Example: A resource clone can be done via action = 'copy', path = "/", from = "/", source_resource = and resource_name = . This field is empty for all other values of `action`. */ sourceResource?: string | null; /** * Value for the `path` field. Will be set for actions:'add'/'replace'. Maybe set for action: 'test'. Either this or `value_matcher` will be set for 'test' operation. An exact match must be performed. */ value?: any | null; /** * Can be set for action 'test' for advanced matching for the value of 'path' field. Either this or `value` will be set for 'test' operation. */ valueMatcher?: Schema$GoogleCloudRecommenderV1beta1ValueMatcher; } /** * Group of operations that need to be performed atomically. */ export interface Schema$GoogleCloudRecommenderV1beta1OperationGroup { /** * List of operations across one or more resources that belong to this group. Loosely based on RFC6902 and should be performed in the order they appear. */ operations?: Schema$GoogleCloudRecommenderV1beta1Operation[]; } /** * A recommendation along with a suggested action. E.g., a rightsizing recommendation for an underutilized VM, IAM role recommendations, etc */ export interface Schema$GoogleCloudRecommenderV1beta1Recommendation { /** * Optional set of additional impact that this recommendation may have when trying to optimize for the primary category. These may be positive or negative. */ additionalImpact?: Schema$GoogleCloudRecommenderV1beta1Impact[]; /** * Insights that led to this recommendation. */ associatedInsights?: Schema$GoogleCloudRecommenderV1beta1RecommendationInsightReference[]; /** * Content of the recommendation describing recommended changes to resources. */ content?: Schema$GoogleCloudRecommenderV1beta1RecommendationContent; /** * Free-form human readable summary in English. The maximum length is 500 characters. */ description?: string | null; /** * Fingerprint of the Recommendation. Provides optimistic locking when updating states. */ etag?: string | null; /** * Last time this recommendation was refreshed by the system that created it in the first place. */ lastRefreshTime?: string | null; /** * Name of recommendation. */ name?: string | null; /** * The primary impact that this recommendation can have while trying to optimize for one category. */ primaryImpact?: Schema$GoogleCloudRecommenderV1beta1Impact; /** * Recommendation's priority. */ priority?: string | null; /** * Contains an identifier for a subtype of recommendations produced for the same recommender. Subtype is a function of content and impact, meaning a new subtype might be added when significant changes to `content` or `primary_impact.category` are introduced. See the Recommenders section to see a list of subtypes for a given Recommender. Examples: For recommender = "google.iam.policy.Recommender", recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE" */ recommenderSubtype?: string | null; /** * Information for state. Contains state and metadata. */ stateInfo?: Schema$GoogleCloudRecommenderV1beta1RecommendationStateInfo; /** * Corresponds to a mutually exclusive group ID within a recommender. A non-empty ID indicates that the recommendation belongs to a mutually exclusive group. This means that only one recommendation within the group is suggested to be applied. */ xorGroupId?: string | null; } /** * Contains what resources are changing and how they are changing. */ export interface Schema$GoogleCloudRecommenderV1beta1RecommendationContent { /** * Operations to one or more Google Cloud resources grouped in such a way that, all operations within one group are expected to be performed atomically and in an order. */ operationGroups?: Schema$GoogleCloudRecommenderV1beta1OperationGroup[]; /** * Condensed overview information about the recommendation. */ overview?: {[key: string]: any} | null; } /** * Reference to an associated insight. */ export interface Schema$GoogleCloudRecommenderV1beta1RecommendationInsightReference { /** * Insight resource name, e.g. projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID] */ insight?: string | null; } /** * Information for state. Contains state and metadata. */ export interface Schema$GoogleCloudRecommenderV1beta1RecommendationStateInfo { /** * The state of the recommendation, Eg ACTIVE, SUCCEEDED, FAILED. */ state?: string | null; /** * A map of metadata for the state, provided by user or automations systems. */ stateMetadata?: {[key: string]: string} | null; } /** * Configuration for a Recommender. */ export interface Schema$GoogleCloudRecommenderV1beta1RecommenderConfig { /** * Allows clients to store small amounts of arbitrary data. Annotations must follow the Kubernetes syntax. The total size of all keys and values combined is limited to 256k. Key can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ annotations?: {[key: string]: string} | null; /** * A user-settable field to provide a human-readable name to be used in user interfaces. */ displayName?: string | null; /** * Fingerprint of the RecommenderConfig. Provides optimistic locking when updating. */ etag?: string | null; /** * Name of recommender config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config */ name?: string | null; /** * RecommenderGenerationConfig which configures the Generation of recommendations for this recommender. */ recommenderGenerationConfig?: Schema$GoogleCloudRecommenderV1beta1RecommenderGenerationConfig; /** * Output only. Immutable. The revision ID of the config. A new revision is committed whenever the config is changed in any way. The format is an 8-character hexadecimal string. */ revisionId?: string | null; /** * Last time when the config was updated. */ updateTime?: string | null; } /** * A Configuration to customize the generation of recommendations. Eg, customizing the lookback period considered when generating a recommendation. */ export interface Schema$GoogleCloudRecommenderV1beta1RecommenderGenerationConfig { /** * Parameters for this RecommenderGenerationConfig. These configs can be used by or are applied to all subtypes. */ params?: {[key: string]: any} | null; } /** * Contains various ways of describing the impact on Security. */ export interface Schema$GoogleCloudRecommenderV1beta1SecurityProjection { /** * This field can be used by the recommender to define details specific to security impact. */ details?: {[key: string]: any} | null; } /** * Contains metadata about how much sustainability a recommendation can save or incur. */ export interface Schema$GoogleCloudRecommenderV1beta1SustainabilityProjection { /** * Duration for which this sustanability applies. */ duration?: string | null; /** * Carbon Footprint generated in kg of CO2 equivalent. Chose kg_c_o2e so that the name renders correctly in camelCase (kgCO2e). */ kgCO2e?: number | null; } /** * Contains various matching options for values for a GCP resource field. */ export interface Schema$GoogleCloudRecommenderV1beta1ValueMatcher { /** * To be used for full regex matching. The regular expression is using the Google RE2 syntax (https://github.com/google/re2/wiki/Syntax), so to be used with RE2::FullMatch */ matchesPattern?: string | null; } /** * Represents an amount of money with its currency type. */ export interface Schema$GoogleTypeMoney { /** * The three-letter currency code defined in ISO 4217. */ currencyCode?: string | null; /** * Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999 inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. */ nanos?: number | null; /** * The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. */ units?: string | null; } export class Resource$Billingaccounts { context: APIRequestContext; locations: Resource$Billingaccounts$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Billingaccounts$Locations(this.context); } } export class Resource$Billingaccounts$Locations { context: APIRequestContext; insightTypes: Resource$Billingaccounts$Locations$Insighttypes; recommenders: Resource$Billingaccounts$Locations$Recommenders; constructor(context: APIRequestContext) { this.context = context; this.insightTypes = new Resource$Billingaccounts$Locations$Insighttypes( this.context ); this.recommenders = new Resource$Billingaccounts$Locations$Recommenders( this.context ); } } export class Resource$Billingaccounts$Locations$Insighttypes { context: APIRequestContext; insights: Resource$Billingaccounts$Locations$Insighttypes$Insights; constructor(context: APIRequestContext) { this.context = context; this.insights = new Resource$Billingaccounts$Locations$Insighttypes$Insights( this.context ); } } export class Resource$Billingaccounts$Locations$Insighttypes$Insights { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested insight. Requires the recommender.*.get IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.insightTypes.insights.get({ * // Required. Name of the insight. * name: 'billingAccounts/my-billingAccount/locations/my-location/insightTypes/my-insightType/insights/my-insight', * }); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; get( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } /** * Lists insights for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.insightTypes.insights.list({ * // Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. * parent: * 'billingAccounts/my-billingAccount/locations/my-location/insightTypes/my-insightType', * }); * console.log(res.data); * * // Example response * // { * // "insights": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>; list( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/insights').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters ); } } /** * Marks the Insight State as Accepted. Users can use this method to indicate to the Recommender API that they have applied some action based on the insight. This stops the insight content from being updated. MarkInsightAccepted can be applied to insights in ACTIVE state. Requires the recommender.*.update IAM permission for the specified insight. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.insightTypes.insights.markAccepted( * { * // Required. Name of the insight. * name: 'billingAccounts/my-billingAccount/locations/my-location/insightTypes/my-insightType/insights/my-insight', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markAccepted( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions ): GaxiosPromise<Readable>; markAccepted( params?: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; markAccepted( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markAccepted( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( params: Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markAccepted').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } } export interface Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Get extends StandardParameters { /** * Required. Name of the insight. */ name?: string; } export interface Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$List extends StandardParameters { /** * Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. */ parent?: string; } export interface Params$Resource$Billingaccounts$Locations$Insighttypes$Insights$Markaccepted extends StandardParameters { /** * Required. Name of the insight. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest; } export class Resource$Billingaccounts$Locations$Recommenders { context: APIRequestContext; recommendations: Resource$Billingaccounts$Locations$Recommenders$Recommendations; constructor(context: APIRequestContext) { this.context = context; this.recommendations = new Resource$Billingaccounts$Locations$Recommenders$Recommendations( this.context ); } } export class Resource$Billingaccounts$Locations$Recommenders$Recommendations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested recommendation. Requires the recommender.*.get IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.recommenders.recommendations.get( * { * // Required. Name of the recommendation. * name: 'billingAccounts/my-billingAccount/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; get( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Lists recommendations for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.recommenders.recommendations.list( * { * // Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. * parent: * 'billingAccounts/my-billingAccount/locations/my-location/recommenders/my-recommender', * } * ); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "recommendations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>; list( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/recommendations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters ); } } /** * Marks the Recommendation State as Claimed. Users can use this method to indicate to the Recommender API that they are starting to apply the recommendation themselves. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationClaimed can be applied to recommendations in CLAIMED or ACTIVE state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.recommenders.recommendations.markClaimed( * { * // Required. Name of the recommendation. * name: 'billingAccounts/my-billingAccount/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markClaimed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markClaimed( params?: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markClaimed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markClaimed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markClaimed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Failed. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation failed. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationFailed can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.recommenders.recommendations.markFailed( * { * // Required. Name of the recommendation. * name: 'billingAccounts/my-billingAccount/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markFailed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markFailed( params?: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markFailed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markFailed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markFailed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Succeeded. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation was successful. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.billingAccounts.locations.recommenders.recommendations.markSucceeded( * { * // Required. Name of the recommendation. * name: 'billingAccounts/my-billingAccount/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markSucceeded( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions ): GaxiosPromise<Readable>; markSucceeded( params?: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markSucceeded( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markSucceeded( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( params: Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( paramsOrCallback?: | Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markSucceeded').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } } export interface Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Get extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; } export interface Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$List extends StandardParameters { /** * Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. */ parent?: string; } export interface Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markclaimed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest; } export interface Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Markfailed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest; } export interface Params$Resource$Billingaccounts$Locations$Recommenders$Recommendations$Marksucceeded extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest; } export class Resource$Folders { context: APIRequestContext; locations: Resource$Folders$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Folders$Locations(this.context); } } export class Resource$Folders$Locations { context: APIRequestContext; insightTypes: Resource$Folders$Locations$Insighttypes; recommenders: Resource$Folders$Locations$Recommenders; constructor(context: APIRequestContext) { this.context = context; this.insightTypes = new Resource$Folders$Locations$Insighttypes( this.context ); this.recommenders = new Resource$Folders$Locations$Recommenders( this.context ); } } export class Resource$Folders$Locations$Insighttypes { context: APIRequestContext; insights: Resource$Folders$Locations$Insighttypes$Insights; constructor(context: APIRequestContext) { this.context = context; this.insights = new Resource$Folders$Locations$Insighttypes$Insights( this.context ); } } export class Resource$Folders$Locations$Insighttypes$Insights { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested insight. Requires the recommender.*.get IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.folders.locations.insightTypes.insights.get({ * // Required. Name of the insight. * name: 'folders/my-folder/locations/my-location/insightTypes/my-insightType/insights/my-insight', * }); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Folders$Locations$Insighttypes$Insights$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; get( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( paramsOrCallback?: | Params$Resource$Folders$Locations$Insighttypes$Insights$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Insighttypes$Insights$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Insighttypes$Insights$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } /** * Lists insights for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.folders.locations.insightTypes.insights.list({ * // Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. * parent: * 'folders/my-folder/locations/my-location/insightTypes/my-insightType', * }); * console.log(res.data); * * // Example response * // { * // "insights": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Folders$Locations$Insighttypes$Insights$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Folders$Locations$Insighttypes$Insights$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>; list( params: Params$Resource$Folders$Locations$Insighttypes$Insights$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Folders$Locations$Insighttypes$Insights$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( params: Params$Resource$Folders$Locations$Insighttypes$Insights$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Folders$Locations$Insighttypes$Insights$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Insighttypes$Insights$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Insighttypes$Insights$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/insights').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters ); } } /** * Marks the Insight State as Accepted. Users can use this method to indicate to the Recommender API that they have applied some action based on the insight. This stops the insight content from being updated. MarkInsightAccepted can be applied to insights in ACTIVE state. Requires the recommender.*.update IAM permission for the specified insight. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.folders.locations.insightTypes.insights.markAccepted({ * // Required. Name of the insight. * name: 'folders/my-folder/locations/my-location/insightTypes/my-insightType/insights/my-insight', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markAccepted( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions ): GaxiosPromise<Readable>; markAccepted( params?: Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; markAccepted( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markAccepted( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( params: Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( paramsOrCallback?: | Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markAccepted').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } } export interface Params$Resource$Folders$Locations$Insighttypes$Insights$Get extends StandardParameters { /** * Required. Name of the insight. */ name?: string; } export interface Params$Resource$Folders$Locations$Insighttypes$Insights$List extends StandardParameters { /** * Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. */ parent?: string; } export interface Params$Resource$Folders$Locations$Insighttypes$Insights$Markaccepted extends StandardParameters { /** * Required. Name of the insight. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest; } export class Resource$Folders$Locations$Recommenders { context: APIRequestContext; recommendations: Resource$Folders$Locations$Recommenders$Recommendations; constructor(context: APIRequestContext) { this.context = context; this.recommendations = new Resource$Folders$Locations$Recommenders$Recommendations( this.context ); } } export class Resource$Folders$Locations$Recommenders$Recommendations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested recommendation. Requires the recommender.*.get IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.folders.locations.recommenders.recommendations.get({ * // Required. Name of the recommendation. * name: 'folders/my-folder/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * }); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Folders$Locations$Recommenders$Recommendations$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; get( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( paramsOrCallback?: | Params$Resource$Folders$Locations$Recommenders$Recommendations$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Recommenders$Recommendations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Recommenders$Recommendations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Lists recommendations for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.folders.locations.recommenders.recommendations.list({ * // Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. * parent: * 'folders/my-folder/locations/my-location/recommenders/my-recommender', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "recommendations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Folders$Locations$Recommenders$Recommendations$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>; list( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Folders$Locations$Recommenders$Recommendations$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Recommenders$Recommendations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Recommenders$Recommendations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/recommendations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters ); } } /** * Marks the Recommendation State as Claimed. Users can use this method to indicate to the Recommender API that they are starting to apply the recommendation themselves. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationClaimed can be applied to recommendations in CLAIMED or ACTIVE state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.folders.locations.recommenders.recommendations.markClaimed( * { * // Required. Name of the recommendation. * name: 'folders/my-folder/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markClaimed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markClaimed( params?: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markClaimed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markClaimed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( paramsOrCallback?: | Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markClaimed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Failed. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation failed. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationFailed can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.folders.locations.recommenders.recommendations.markFailed( * { * // Required. Name of the recommendation. * name: 'folders/my-folder/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markFailed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markFailed( params?: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markFailed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markFailed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( paramsOrCallback?: | Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markFailed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Succeeded. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation was successful. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.folders.locations.recommenders.recommendations.markSucceeded( * { * // Required. Name of the recommendation. * name: 'folders/my-folder/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markSucceeded( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions ): GaxiosPromise<Readable>; markSucceeded( params?: Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markSucceeded( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markSucceeded( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( params: Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( paramsOrCallback?: | Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markSucceeded').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } } export interface Params$Resource$Folders$Locations$Recommenders$Recommendations$Get extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; } export interface Params$Resource$Folders$Locations$Recommenders$Recommendations$List extends StandardParameters { /** * Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. */ parent?: string; } export interface Params$Resource$Folders$Locations$Recommenders$Recommendations$Markclaimed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest; } export interface Params$Resource$Folders$Locations$Recommenders$Recommendations$Markfailed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest; } export interface Params$Resource$Folders$Locations$Recommenders$Recommendations$Marksucceeded extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest; } export class Resource$Organizations { context: APIRequestContext; locations: Resource$Organizations$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Organizations$Locations(this.context); } } export class Resource$Organizations$Locations { context: APIRequestContext; insightTypes: Resource$Organizations$Locations$Insighttypes; recommenders: Resource$Organizations$Locations$Recommenders; constructor(context: APIRequestContext) { this.context = context; this.insightTypes = new Resource$Organizations$Locations$Insighttypes( this.context ); this.recommenders = new Resource$Organizations$Locations$Recommenders( this.context ); } } export class Resource$Organizations$Locations$Insighttypes { context: APIRequestContext; insights: Resource$Organizations$Locations$Insighttypes$Insights; constructor(context: APIRequestContext) { this.context = context; this.insights = new Resource$Organizations$Locations$Insighttypes$Insights( this.context ); } /** * Gets the requested InsightTypeConfig. There is only one instance of the config for each InsightType. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.organizations.locations.insightTypes.getConfig({ * // Required. Name of the InsightTypeConfig to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * name: 'organizations/my-organization/locations/my-location/insightTypes/my-insightType/config', * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "insightTypeGenerationConfig": {}, * // "name": "my_name", * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ getConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Getconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; getConfig( params?: Params$Resource$Organizations$Locations$Insighttypes$Getconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>; getConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Getconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; getConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Getconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; getConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Getconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; getConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; getConfig( paramsOrCallback?: | Params$Resource$Organizations$Locations$Insighttypes$Getconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Insighttypes$Getconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Insighttypes$Getconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters ); } } /** * Updates an InsightTypeConfig change. This will create a new revision of the config. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.insightTypes.updateConfig({ * // Name of insight type config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/config * name: 'organizations/my-organization/locations/my-location/insightTypes/my-insightType/config', * // The list of fields to be updated. * updateMask: 'placeholder-value', * // If true, validate the request and preview the change, but do not actually update it. * validateOnly: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "insightTypeGenerationConfig": {}, * // "name": "my_name", * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "insightTypeGenerationConfig": {}, * // "name": "my_name", * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ updateConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Updateconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; updateConfig( params?: Params$Resource$Organizations$Locations$Insighttypes$Updateconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>; updateConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Updateconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; updateConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Updateconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; updateConfig( params: Params$Resource$Organizations$Locations$Insighttypes$Updateconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; updateConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; updateConfig( paramsOrCallback?: | Params$Resource$Organizations$Locations$Insighttypes$Updateconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Insighttypes$Updateconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Insighttypes$Updateconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters ); } } } export interface Params$Resource$Organizations$Locations$Insighttypes$Getconfig extends StandardParameters { /** * Required. Name of the InsightTypeConfig to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` */ name?: string; } export interface Params$Resource$Organizations$Locations$Insighttypes$Updateconfig extends StandardParameters { /** * Name of insight type config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/config */ name?: string; /** * The list of fields to be updated. */ updateMask?: string; /** * If true, validate the request and preview the change, but do not actually update it. */ validateOnly?: boolean; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig; } export class Resource$Organizations$Locations$Insighttypes$Insights { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested insight. Requires the recommender.*.get IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.insightTypes.insights.get({ * // Required. Name of the insight. * name: 'organizations/my-organization/locations/my-location/insightTypes/my-insightType/insights/my-insight', * }); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Organizations$Locations$Insighttypes$Insights$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; get( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( paramsOrCallback?: | Params$Resource$Organizations$Locations$Insighttypes$Insights$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Insighttypes$Insights$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Insighttypes$Insights$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } /** * Lists insights for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.insightTypes.insights.list({ * // Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. * parent: * 'organizations/my-organization/locations/my-location/insightTypes/my-insightType', * }); * console.log(res.data); * * // Example response * // { * // "insights": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Organizations$Locations$Insighttypes$Insights$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>; list( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Organizations$Locations$Insighttypes$Insights$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Insighttypes$Insights$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Insighttypes$Insights$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/insights').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters ); } } /** * Marks the Insight State as Accepted. Users can use this method to indicate to the Recommender API that they have applied some action based on the insight. This stops the insight content from being updated. MarkInsightAccepted can be applied to insights in ACTIVE state. Requires the recommender.*.update IAM permission for the specified insight. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.insightTypes.insights.markAccepted( * { * // Required. Name of the insight. * name: 'organizations/my-organization/locations/my-location/insightTypes/my-insightType/insights/my-insight', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markAccepted( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions ): GaxiosPromise<Readable>; markAccepted( params?: Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; markAccepted( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markAccepted( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( params: Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( paramsOrCallback?: | Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markAccepted').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } } export interface Params$Resource$Organizations$Locations$Insighttypes$Insights$Get extends StandardParameters { /** * Required. Name of the insight. */ name?: string; } export interface Params$Resource$Organizations$Locations$Insighttypes$Insights$List extends StandardParameters { /** * Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. */ parent?: string; } export interface Params$Resource$Organizations$Locations$Insighttypes$Insights$Markaccepted extends StandardParameters { /** * Required. Name of the insight. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest; } export class Resource$Organizations$Locations$Recommenders { context: APIRequestContext; recommendations: Resource$Organizations$Locations$Recommenders$Recommendations; constructor(context: APIRequestContext) { this.context = context; this.recommendations = new Resource$Organizations$Locations$Recommenders$Recommendations( this.context ); } /** * Gets the requested Recommender Config. There is only one instance of the config for each Recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.organizations.locations.recommenders.getConfig({ * // Required. Name of the Recommendation Config to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * name: 'organizations/my-organization/locations/my-location/recommenders/my-recommender/config', * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "name": "my_name", * // "recommenderGenerationConfig": {}, * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ getConfig( params: Params$Resource$Organizations$Locations$Recommenders$Getconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; getConfig( params?: Params$Resource$Organizations$Locations$Recommenders$Getconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>; getConfig( params: Params$Resource$Organizations$Locations$Recommenders$Getconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; getConfig( params: Params$Resource$Organizations$Locations$Recommenders$Getconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; getConfig( params: Params$Resource$Organizations$Locations$Recommenders$Getconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; getConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; getConfig( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Getconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Getconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Getconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters ); } } /** * Updates a Recommender Config. This will create a new revision of the config. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.recommenders.updateConfig({ * // Name of recommender config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config * name: 'organizations/my-organization/locations/my-location/recommenders/my-recommender/config', * // The list of fields to be updated. * updateMask: 'placeholder-value', * // If true, validate the request and preview the change, but do not actually update it. * validateOnly: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "name": "my_name", * // "recommenderGenerationConfig": {}, * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "name": "my_name", * // "recommenderGenerationConfig": {}, * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ updateConfig( params: Params$Resource$Organizations$Locations$Recommenders$Updateconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; updateConfig( params?: Params$Resource$Organizations$Locations$Recommenders$Updateconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>; updateConfig( params: Params$Resource$Organizations$Locations$Recommenders$Updateconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; updateConfig( params: Params$Resource$Organizations$Locations$Recommenders$Updateconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; updateConfig( params: Params$Resource$Organizations$Locations$Recommenders$Updateconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; updateConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; updateConfig( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Updateconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Updateconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Updateconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters ); } } } export interface Params$Resource$Organizations$Locations$Recommenders$Getconfig extends StandardParameters { /** * Required. Name of the Recommendation Config to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` */ name?: string; } export interface Params$Resource$Organizations$Locations$Recommenders$Updateconfig extends StandardParameters { /** * Name of recommender config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config */ name?: string; /** * The list of fields to be updated. */ updateMask?: string; /** * If true, validate the request and preview the change, but do not actually update it. */ validateOnly?: boolean; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1RecommenderConfig; } export class Resource$Organizations$Locations$Recommenders$Recommendations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested recommendation. Requires the recommender.*.get IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.recommenders.recommendations.get({ * // Required. Name of the recommendation. * name: 'organizations/my-organization/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * }); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; get( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Lists recommendations for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.recommenders.recommendations.list( * { * // Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. * parent: * 'organizations/my-organization/locations/my-location/recommenders/my-recommender', * } * ); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "recommendations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Organizations$Locations$Recommenders$Recommendations$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>; list( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Recommendations$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Recommendations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Recommendations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/recommendations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters ); } } /** * Marks the Recommendation State as Claimed. Users can use this method to indicate to the Recommender API that they are starting to apply the recommendation themselves. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationClaimed can be applied to recommendations in CLAIMED or ACTIVE state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.recommenders.recommendations.markClaimed( * { * // Required. Name of the recommendation. * name: 'organizations/my-organization/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markClaimed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markClaimed( params?: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markClaimed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markClaimed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markClaimed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Failed. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation failed. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationFailed can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.recommenders.recommendations.markFailed( * { * // Required. Name of the recommendation. * name: 'organizations/my-organization/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markFailed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markFailed( params?: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markFailed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markFailed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markFailed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Succeeded. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation was successful. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.organizations.locations.recommenders.recommendations.markSucceeded( * { * // Required. Name of the recommendation. * name: 'organizations/my-organization/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markSucceeded( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions ): GaxiosPromise<Readable>; markSucceeded( params?: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markSucceeded( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markSucceeded( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( params: Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( paramsOrCallback?: | Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markSucceeded').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } } export interface Params$Resource$Organizations$Locations$Recommenders$Recommendations$Get extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; } export interface Params$Resource$Organizations$Locations$Recommenders$Recommendations$List extends StandardParameters { /** * Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. */ parent?: string; } export interface Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markclaimed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest; } export interface Params$Resource$Organizations$Locations$Recommenders$Recommendations$Markfailed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest; } export interface Params$Resource$Organizations$Locations$Recommenders$Recommendations$Marksucceeded extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest; } export class Resource$Projects { context: APIRequestContext; locations: Resource$Projects$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Projects$Locations(this.context); } } export class Resource$Projects$Locations { context: APIRequestContext; insightTypes: Resource$Projects$Locations$Insighttypes; recommenders: Resource$Projects$Locations$Recommenders; constructor(context: APIRequestContext) { this.context = context; this.insightTypes = new Resource$Projects$Locations$Insighttypes( this.context ); this.recommenders = new Resource$Projects$Locations$Recommenders( this.context ); } } export class Resource$Projects$Locations$Insighttypes { context: APIRequestContext; insights: Resource$Projects$Locations$Insighttypes$Insights; constructor(context: APIRequestContext) { this.context = context; this.insights = new Resource$Projects$Locations$Insighttypes$Insights( this.context ); } /** * Gets the requested InsightTypeConfig. There is only one instance of the config for each InsightType. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.projects.locations.insightTypes.getConfig({ * // Required. Name of the InsightTypeConfig to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * name: 'projects/my-project/locations/my-location/insightTypes/my-insightType/config', * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "insightTypeGenerationConfig": {}, * // "name": "my_name", * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ getConfig( params: Params$Resource$Projects$Locations$Insighttypes$Getconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; getConfig( params?: Params$Resource$Projects$Locations$Insighttypes$Getconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>; getConfig( params: Params$Resource$Projects$Locations$Insighttypes$Getconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; getConfig( params: Params$Resource$Projects$Locations$Insighttypes$Getconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; getConfig( params: Params$Resource$Projects$Locations$Insighttypes$Getconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; getConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; getConfig( paramsOrCallback?: | Params$Resource$Projects$Locations$Insighttypes$Getconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Insighttypes$Getconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Insighttypes$Getconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters ); } } /** * Updates an InsightTypeConfig change. This will create a new revision of the config. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.projects.locations.insightTypes.updateConfig({ * // Name of insight type config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/config * name: 'projects/my-project/locations/my-location/insightTypes/my-insightType/config', * // The list of fields to be updated. * updateMask: 'placeholder-value', * // If true, validate the request and preview the change, but do not actually update it. * validateOnly: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "insightTypeGenerationConfig": {}, * // "name": "my_name", * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "insightTypeGenerationConfig": {}, * // "name": "my_name", * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ updateConfig( params: Params$Resource$Projects$Locations$Insighttypes$Updateconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; updateConfig( params?: Params$Resource$Projects$Locations$Insighttypes$Updateconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>; updateConfig( params: Params$Resource$Projects$Locations$Insighttypes$Updateconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; updateConfig( params: Params$Resource$Projects$Locations$Insighttypes$Updateconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; updateConfig( params: Params$Resource$Projects$Locations$Insighttypes$Updateconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; updateConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> ): void; updateConfig( paramsOrCallback?: | Params$Resource$Projects$Locations$Insighttypes$Updateconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Insighttypes$Updateconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Insighttypes$Updateconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig>( parameters ); } } } export interface Params$Resource$Projects$Locations$Insighttypes$Getconfig extends StandardParameters { /** * Required. Name of the InsightTypeConfig to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config` */ name?: string; } export interface Params$Resource$Projects$Locations$Insighttypes$Updateconfig extends StandardParameters { /** * Name of insight type config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/config */ name?: string; /** * The list of fields to be updated. */ updateMask?: string; /** * If true, validate the request and preview the change, but do not actually update it. */ validateOnly?: boolean; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1InsightTypeConfig; } export class Resource$Projects$Locations$Insighttypes$Insights { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested insight. Requires the recommender.*.get IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.projects.locations.insightTypes.insights.get({ * // Required. Name of the insight. * name: 'projects/my-project/locations/my-location/insightTypes/my-insightType/insights/my-insight', * }); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Insighttypes$Insights$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; get( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Insighttypes$Insights$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Insighttypes$Insights$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Insighttypes$Insights$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } /** * Lists insights for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified insight type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.projects.locations.insightTypes.insights.list({ * // Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. * parent: * 'projects/my-project/locations/my-location/insightTypes/my-insightType', * }); * console.log(res.data); * * // Example response * // { * // "insights": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Insighttypes$Insights$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Insighttypes$Insights$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>; list( params: Params$Resource$Projects$Locations$Insighttypes$Insights$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Insighttypes$Insights$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( params: Params$Resource$Projects$Locations$Insighttypes$Insights$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Insighttypes$Insights$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Insighttypes$Insights$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Insighttypes$Insights$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/insights').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListInsightsResponse>( parameters ); } } /** * Marks the Insight State as Accepted. Users can use this method to indicate to the Recommender API that they have applied some action based on the insight. This stops the insight content from being updated. MarkInsightAccepted can be applied to insights in ACTIVE state. Requires the recommender.*.update IAM permission for the specified insight. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.projects.locations.insightTypes.insights.markAccepted({ * // Required. Name of the insight. * name: 'projects/my-project/locations/my-location/insightTypes/my-insightType/insights/my-insight', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "associatedRecommendations": [], * // "category": "my_category", * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "insightSubtype": "my_insightSubtype", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "observationPeriod": "my_observationPeriod", * // "severity": "my_severity", * // "stateInfo": {}, * // "targetResources": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markAccepted( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions ): GaxiosPromise<Readable>; markAccepted( params?: Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight>; markAccepted( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markAccepted( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( params: Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> ): void; markAccepted( paramsOrCallback?: | Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Insight> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Insight> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markAccepted').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Insight>( parameters ); } } } export interface Params$Resource$Projects$Locations$Insighttypes$Insights$Get extends StandardParameters { /** * Required. Name of the insight. */ name?: string; } export interface Params$Resource$Projects$Locations$Insighttypes$Insights$List extends StandardParameters { /** * Optional. Filter expression to restrict the insights returned. Supported filter fields: * `stateInfo.state` * `insightSubtype` * `severity` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `insightSubtype = PERMISSIONS_USAGE` * `severity = CRITICAL OR severity = HIGH` * `stateInfo.state = ACTIVE AND (severity = CRITICAL OR severity = HIGH)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types. */ parent?: string; } export interface Params$Resource$Projects$Locations$Insighttypes$Insights$Markaccepted extends StandardParameters { /** * Required. Name of the insight. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest; } export class Resource$Projects$Locations$Recommenders { context: APIRequestContext; recommendations: Resource$Projects$Locations$Recommenders$Recommendations; constructor(context: APIRequestContext) { this.context = context; this.recommendations = new Resource$Projects$Locations$Recommenders$Recommendations( this.context ); } /** * Gets the requested Recommender Config. There is only one instance of the config for each Recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.projects.locations.recommenders.getConfig({ * // Required. Name of the Recommendation Config to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * name: 'projects/my-project/locations/my-location/recommenders/my-recommender/config', * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "name": "my_name", * // "recommenderGenerationConfig": {}, * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ getConfig( params: Params$Resource$Projects$Locations$Recommenders$Getconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; getConfig( params?: Params$Resource$Projects$Locations$Recommenders$Getconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>; getConfig( params: Params$Resource$Projects$Locations$Recommenders$Getconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; getConfig( params: Params$Resource$Projects$Locations$Recommenders$Getconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; getConfig( params: Params$Resource$Projects$Locations$Recommenders$Getconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; getConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; getConfig( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Getconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Getconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Getconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters ); } } /** * Updates a Recommender Config. This will create a new revision of the config. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await recommender.projects.locations.recommenders.updateConfig({ * // Name of recommender config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config * name: 'projects/my-project/locations/my-location/recommenders/my-recommender/config', * // The list of fields to be updated. * updateMask: 'placeholder-value', * // If true, validate the request and preview the change, but do not actually update it. * validateOnly: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "name": "my_name", * // "recommenderGenerationConfig": {}, * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "annotations": {}, * // "displayName": "my_displayName", * // "etag": "my_etag", * // "name": "my_name", * // "recommenderGenerationConfig": {}, * // "revisionId": "my_revisionId", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ updateConfig( params: Params$Resource$Projects$Locations$Recommenders$Updateconfig, options: StreamMethodOptions ): GaxiosPromise<Readable>; updateConfig( params?: Params$Resource$Projects$Locations$Recommenders$Updateconfig, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>; updateConfig( params: Params$Resource$Projects$Locations$Recommenders$Updateconfig, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; updateConfig( params: Params$Resource$Projects$Locations$Recommenders$Updateconfig, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; updateConfig( params: Params$Resource$Projects$Locations$Recommenders$Updateconfig, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; updateConfig( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> ): void; updateConfig( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Updateconfig | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Updateconfig; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Updateconfig; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1RecommenderConfig>( parameters ); } } } export interface Params$Resource$Projects$Locations$Recommenders$Getconfig extends StandardParameters { /** * Required. Name of the Recommendation Config to get. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config` */ name?: string; } export interface Params$Resource$Projects$Locations$Recommenders$Updateconfig extends StandardParameters { /** * Name of recommender config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config */ name?: string; /** * The list of fields to be updated. */ updateMask?: string; /** * If true, validate the request and preview the change, but do not actually update it. */ validateOnly?: boolean; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1RecommenderConfig; } export class Resource$Projects$Locations$Recommenders$Recommendations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the requested recommendation. Requires the recommender.*.get IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.projects.locations.recommenders.recommendations.get({ * // Required. Name of the recommendation. * name: 'projects/my-project/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * }); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Recommenders$Recommendations$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; get( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Get, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Recommendations$Get | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Recommendations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Recommendations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Lists recommendations for the specified Cloud Resource. Requires the recommender.*.list IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.projects.locations.recommenders.recommendations.list({ * // Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) * filter: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. * parent: * 'projects/my-project/locations/my-location/recommenders/my-recommender', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "recommendations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Recommenders$Recommendations$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>; list( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$List, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Recommendations$List | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Recommendations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Recommendations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+parent}/recommendations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1ListRecommendationsResponse>( parameters ); } } /** * Marks the Recommendation State as Claimed. Users can use this method to indicate to the Recommender API that they are starting to apply the recommendation themselves. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationClaimed can be applied to recommendations in CLAIMED or ACTIVE state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.projects.locations.recommenders.recommendations.markClaimed( * { * // Required. Name of the recommendation. * name: 'projects/my-project/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markClaimed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markClaimed( params?: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markClaimed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markClaimed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markClaimed( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markClaimed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Failed. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation failed. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationFailed can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.projects.locations.recommenders.recommendations.markFailed( * { * // Required. Name of the recommendation. * name: 'projects/my-project/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markFailed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions ): GaxiosPromise<Readable>; markFailed( params?: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markFailed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markFailed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markFailed( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markFailed').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } /** * Marks the Recommendation State as Succeeded. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation was successful. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/recommender.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const recommender = google.recommender('v1beta1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await recommender.projects.locations.recommenders.recommendations.markSucceeded( * { * // Required. Name of the recommendation. * name: 'projects/my-project/locations/my-location/recommenders/my-recommender/recommendations/my-recommendation', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "etag": "my_etag", * // "stateMetadata": {} * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "additionalImpact": [], * // "associatedInsights": [], * // "content": {}, * // "description": "my_description", * // "etag": "my_etag", * // "lastRefreshTime": "my_lastRefreshTime", * // "name": "my_name", * // "primaryImpact": {}, * // "priority": "my_priority", * // "recommenderSubtype": "my_recommenderSubtype", * // "stateInfo": {}, * // "xorGroupId": "my_xorGroupId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ markSucceeded( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions ): GaxiosPromise<Readable>; markSucceeded( params?: Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation>; markSucceeded( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; markSucceeded( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation>, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( params: Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded, callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( callback: BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> ): void; markSucceeded( paramsOrCallback?: | Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudRecommenderV1beta1Recommendation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudRecommenderV1beta1Recommendation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://recommender.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1beta1/{+name}:markSucceeded').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudRecommenderV1beta1Recommendation>( parameters ); } } } export interface Params$Resource$Projects$Locations$Recommenders$Recommendations$Get extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; } export interface Params$Resource$Projects$Locations$Recommenders$Recommendations$List extends StandardParameters { /** * Filter expression to restrict the recommendations returned. Supported filter fields: * `state_info.state` * `recommenderSubtype` * `priority` Examples: * `stateInfo.state = ACTIVE OR stateInfo.state = DISMISSED` * `recommenderSubtype = REMOVE_ROLE OR recommenderSubtype = REPLACE_ROLE` * `priority = P1 OR priority = P2` * `stateInfo.state = ACTIVE AND (priority = P1 OR priority = P2)` (These expressions are based on the filter language described at https://google.aip.dev/160) */ filter?: string; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call. */ pageToken?: string; /** * Required. The container resource on which to execute the request. Acceptable formats: * `projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `projects/[PROJECT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `folders/[FOLDER_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` * `organizations/[ORGANIZATION_ID]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]` LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders. */ parent?: string; } export interface Params$Resource$Projects$Locations$Recommenders$Recommendations$Markclaimed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest; } export interface Params$Resource$Projects$Locations$Recommenders$Recommendations$Markfailed extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest; } export interface Params$Resource$Projects$Locations$Recommenders$Recommendations$Marksucceeded extends StandardParameters { /** * Required. Name of the recommendation. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest; } }
the_stack
import { DataFrame, FieldType, GrafanaTheme, PanelData } from '@grafana/data'; import { getLocationSrv } from '@grafana/runtime'; import { Button, Icon, IconButton, Modal, useTheme, VerticalGroup } from '@grafana/ui'; import { cx } from 'emotion'; import React from 'react'; import { button, buttons, infoButton, modalArticleIcon, modalChildrenLinks, modalParentsLinks, modalRelativesLinksContainer, modalTooltipContent, modalTypography, warningButton, } from './styles'; import { Predicate, PredicateOperator, TroubleshootingInfo } from './types'; interface Props { data: PanelData; troubleshooting: TroubleshootingInfo; } function navigateDashboard(dashboardUid: string) { const path = `/d/${dashboardUid}`; getLocationSrv().update({ path, }); } function renderNavigation(troubleshooting: TroubleshootingInfo, theme: GrafanaTheme) { const hasParents = troubleshooting.parents && troubleshooting.parents.length > 0; const hasChildren = troubleshooting.children && troubleshooting.children.length > 0; if (!hasChildren && !hasParents) { return; } return ( <VerticalGroup spacing="md"> <h4> <Icon name="chart-line" className={modalArticleIcon(theme)} /> Related dashboards </h4> <div className={modalRelativesLinksContainer}> {hasParents && ( <div className={modalParentsLinks}> <VerticalGroup spacing="md"> {troubleshooting.parents!.map(parent => ( <Button key={parent.uid} variant="link" title={parent.title} onClick={() => navigateDashboard(parent.uid)} > <Icon name="angle-left" /> {parent.name} </Button> ))} </VerticalGroup> </div> )} {hasChildren && ( <div className={modalChildrenLinks}> <VerticalGroup spacing="md"> {troubleshooting.children!.map(child => ( <Button key={child.uid} variant="link" title={child.title} onClick={() => navigateDashboard(child.uid)} > {child.name} <Icon name="angle-right" /> </Button> ))} </VerticalGroup> </div> )} </div> </VerticalGroup> ); } function renderInfoModal(troubleshooting: TroubleshootingInfo, theme: GrafanaTheme) { const hasMetrics = troubleshooting.metrics.length > 0; const hasDerived = troubleshooting.derivedMetrics && troubleshooting.derivedMetrics.length > 0; const hasUrls = troubleshooting.urls && troubleshooting.urls.length > 0; return ( <div className={modalTypography(theme)}> <VerticalGroup spacing="lg"> {hasMetrics && ( <VerticalGroup spacing="md"> <h4> <Icon name="database" className={modalArticleIcon(theme)} /> PCP metrics </h4> <ul> {troubleshooting.metrics.map(metric => ( <li key={metric.name}> {/* Rerender caused by prop change seem to force hide the Tooltip unfortunately */} {metric.helptext ? ( // <Tooltip content={metric.title} theme="info"> // <span className={modalTooltipContent(theme)}>{metric.name}</span> // </Tooltip> <span className={modalTooltipContent(theme)} title={metric.helptext}> {metric.name} </span> ) : ( metric.name )} </li> ))} </ul> </VerticalGroup> )} {hasDerived && ( <VerticalGroup spacing="md"> <h4> <Icon name="database" className={modalArticleIcon(theme)} /> Derived PCP metrics </h4> <ul> {troubleshooting.derivedMetrics!.map(metric => ( <li key={metric.name}> {metric.name} = {metric.expr} </li> ))} </ul> </VerticalGroup> )} {hasUrls && ( <VerticalGroup spacing="md"> <h4> <Icon name="file-alt" className={modalArticleIcon(theme)} /> Further reading </h4> <ul> {troubleshooting.urls!.map(url => ( <li key={url}> <a href={url} target="_blank" rel="noreferrer"> {url} </a> </li> ))} </ul> </VerticalGroup> )} {troubleshooting.notes && ( <VerticalGroup spacing="md"> <h4> <Icon name="question-circle" className={modalArticleIcon(theme)} /> Notes </h4> <span dangerouslySetInnerHTML={{ __html: troubleshooting.notes }} /> </VerticalGroup> )} {renderNavigation(troubleshooting, theme)} </VerticalGroup> </div> ); } function predicateDescription(predicate: Predicate) { return ( <p> Metric <strong>{predicate.metric}</strong> has recently had a value{' '} <strong> {predicate.operator === PredicateOperator.GreaterThan ? 'above' : 'below'} {predicate.value} </strong> </p> ); } function renderWarningModal(troubleshooting: TroubleshootingInfo, theme: GrafanaTheme) { const hasUrls = troubleshooting.urls && troubleshooting.urls.length > 0; return ( <div className={modalTypography(theme)}> <VerticalGroup spacing="lg"> <VerticalGroup spacing="md"> <h2>{troubleshooting.warning}</h2> {troubleshooting.description && <p>{troubleshooting.description}</p>} </VerticalGroup> {troubleshooting.predicate && ( <VerticalGroup spacing="md"> <h4> <Icon name="question-circle" className={modalArticleIcon(theme)} /> Why is this warning shown? </h4> {predicateDescription(troubleshooting.predicate)} </VerticalGroup> )} {hasUrls && ( <VerticalGroup spacing="md"> <h4> <Icon name="search" className={modalArticleIcon(theme)} /> Troubleshooting </h4> <ul> {troubleshooting.urls!.map(url => ( <li key={url}> <a href={url} target="_blank" rel="noreferrer"> {url} </a> </li> ))} </ul> </VerticalGroup> )} {renderNavigation(troubleshooting, theme)} </VerticalGroup> </div> ); } function evaluatePredicate(series: DataFrame[], predicate: Predicate) { let predicateFn; switch (predicate.operator) { case PredicateOperator.GreaterThan: predicateFn = (val: number) => val > predicate.value; break; case PredicateOperator.LesserThan: predicateFn = (val: number) => val < predicate.value; break; default: return false; } for (const dataFrame of series) { for (const field of dataFrame.fields) { if (field.type !== FieldType.number) { continue; } for (let i = 0; i < field.values.length; i++) { if (predicateFn(field.values.get(i))) { return true; } } } } return false; } function modalHeader(title: string) { return ( <div className="modal-header-title"> <Icon name="exclamation-triangle" size="lg" /> <span className="p-l-1">{title}</span> </div> ); } export const TroubleshootingPane: React.FC<Props> = (props: Props) => { const { data, troubleshooting } = props; const theme = useTheme(); const [openedModal, openModal] = React.useState(''); const showWarning = troubleshooting.predicate ? evaluatePredicate(data.series, troubleshooting.predicate) : false; return ( <> <div className={buttons}> <IconButton surface="panel" name="question-circle" size="lg" className={cx(button(theme), infoButton(theme))} onClick={() => openModal('info')} /> {showWarning && ( <IconButton surface="panel" name="exclamation-triangle" size="lg" className={cx(button(theme), warningButton(theme))} onClick={() => openModal('warning')} /> )} </div> <Modal title={modalHeader(`${troubleshooting.name} - Information`)} isOpen={openedModal === 'info'} onDismiss={() => openModal('')} > {renderInfoModal(troubleshooting, theme)} </Modal> {showWarning && ( <Modal title={modalHeader(`${troubleshooting.name} - Warning`)} isOpen={openedModal === 'warning'} onDismiss={() => openModal('')} > {renderWarningModal(troubleshooting, theme)} </Modal> )} </> ); };
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [iam](https://docs.aws.amazon.com/service-authorization/latest/reference/list_identityandaccessmanagement.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Iam extends PolicyStatement { public servicePrefix = 'iam'; /** * Statement provider for service [iam](https://docs.aws.amazon.com/service-authorization/latest/reference/list_identityandaccessmanagement.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to add a new client ID (audience) to the list of registered IDs for the specified IAM OpenID Connect (OIDC) provider resource * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddClientIDToOpenIDConnectProvider.html */ public toAddClientIDToOpenIDConnectProvider() { return this.to('AddClientIDToOpenIDConnectProvider'); } /** * Grants permission to add an IAM role to the specified instance profile * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html */ public toAddRoleToInstanceProfile() { return this.to('AddRoleToInstanceProfile'); } /** * Grants permission to add an IAM user to the specified IAM group * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html */ public toAddUserToGroup() { return this.to('AddUserToGroup'); } /** * Grants permission to attach a managed policy to the specified IAM group * * Access Level: Permissions management * * Possible conditions: * - .ifPolicyARN() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachGroupPolicy.html */ public toAttachGroupPolicy() { return this.to('AttachGroupPolicy'); } /** * Grants permission to attach a managed policy to the specified IAM role * * Access Level: Permissions management * * Possible conditions: * - .ifPolicyARN() * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html */ public toAttachRolePolicy() { return this.to('AttachRolePolicy'); } /** * Grants permission to attach a managed policy to the specified IAM user * * Access Level: Permissions management * * Possible conditions: * - .ifPolicyARN() * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html */ public toAttachUserPolicy() { return this.to('AttachUserPolicy'); } /** * Grants permission for an IAM user to to change their own password * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ChangePassword.html */ public toChangePassword() { return this.to('ChangePassword'); } /** * Grants permission to create access key and secret access key for the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html */ public toCreateAccessKey() { return this.to('CreateAccessKey'); } /** * Grants permission to create an alias for your AWS account * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccountAlias.html */ public toCreateAccountAlias() { return this.to('CreateAccountAlias'); } /** * Grants permission to create a new group * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateGroup.html */ public toCreateGroup() { return this.to('CreateGroup'); } /** * Grants permission to create a new instance profile * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html */ public toCreateInstanceProfile() { return this.to('CreateInstanceProfile'); } /** * Grants permission to create a password for the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html */ public toCreateLoginProfile() { return this.to('CreateLoginProfile'); } /** * Grants permission to create an IAM resource that describes an identity provider (IdP) that supports OpenID Connect (OIDC) * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateOpenIDConnectProvider.html */ public toCreateOpenIDConnectProvider() { return this.to('CreateOpenIDConnectProvider'); } /** * Grants permission to create a new managed policy * * Access Level: Permissions management * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicy.html */ public toCreatePolicy() { return this.to('CreatePolicy'); } /** * Grants permission to create a new version of the specified managed policy * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicyVersion.html */ public toCreatePolicyVersion() { return this.to('CreatePolicyVersion'); } /** * Grants permission to create a new role * * Access Level: Write * * Possible conditions: * - .ifPermissionsBoundary() * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html */ public toCreateRole() { return this.to('CreateRole'); } /** * Grants permission to create an IAM resource that describes an identity provider (IdP) that supports SAML 2.0 * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateSAMLProvider.html */ public toCreateSAMLProvider() { return this.to('CreateSAMLProvider'); } /** * Grants permission to create an IAM role that allows an AWS service to perform actions on your behalf * * Access Level: Write * * Possible conditions: * - .ifAWSServiceName() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceLinkedRole.html */ public toCreateServiceLinkedRole() { return this.to('CreateServiceLinkedRole'); } /** * Grants permission to create a new service-specific credential for an IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html */ public toCreateServiceSpecificCredential() { return this.to('CreateServiceSpecificCredential'); } /** * Grants permission to create a new IAM user * * Access Level: Write * * Possible conditions: * - .ifPermissionsBoundary() * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html */ public toCreateUser() { return this.to('CreateUser'); } /** * Grants permission to create a new virtual MFA device * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateVirtualMFADevice.html */ public toCreateVirtualMFADevice() { return this.to('CreateVirtualMFADevice'); } /** * Grants permission to deactivate the specified MFA device and remove its association with the IAM user for which it was originally enabled * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html */ public toDeactivateMFADevice() { return this.to('DeactivateMFADevice'); } /** * Grants permission to delete the access key pair that is associated with the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccessKey.html */ public toDeleteAccessKey() { return this.to('DeleteAccessKey'); } /** * Grants permission to delete the specified AWS account alias * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccountAlias.html */ public toDeleteAccountAlias() { return this.to('DeleteAccountAlias'); } /** * Grants permission to delete the password policy for the AWS account * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteAccountPasswordPolicy.html */ public toDeleteAccountPasswordPolicy() { return this.to('DeleteAccountPasswordPolicy'); } /** * Grants permission to delete the specified IAM group * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroup.html */ public toDeleteGroup() { return this.to('DeleteGroup'); } /** * Grants permission to delete the specified inline policy from its group * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroupPolicy.html */ public toDeleteGroupPolicy() { return this.to('DeleteGroupPolicy'); } /** * Grants permission to delete the specified instance profile * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html */ public toDeleteInstanceProfile() { return this.to('DeleteInstanceProfile'); } /** * Grants permission to delete the password for the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteLoginProfile.html */ public toDeleteLoginProfile() { return this.to('DeleteLoginProfile'); } /** * Grants permission to delete an OpenID Connect identity provider (IdP) resource object in IAM * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteOpenIDConnectProvider.html */ public toDeleteOpenIDConnectProvider() { return this.to('DeleteOpenIDConnectProvider'); } /** * Grants permission to delete the specified managed policy and remove it from any IAM entities (users, groups, or roles) to which it is attached * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeletePolicy.html */ public toDeletePolicy() { return this.to('DeletePolicy'); } /** * Grants permission to delete a version from the specified managed policy * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeletePolicyVersion.html */ public toDeletePolicyVersion() { return this.to('DeletePolicyVersion'); } /** * Grants permission to delete the specified role * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRole.html */ public toDeleteRole() { return this.to('DeleteRole'); } /** * Grants permission to remove the permissions boundary from a role * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRolePermissionsBoundary.html */ public toDeleteRolePermissionsBoundary() { return this.to('DeleteRolePermissionsBoundary'); } /** * Grants permission to delete the specified inline policy from the specified role * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRolePolicy.html */ public toDeleteRolePolicy() { return this.to('DeleteRolePolicy'); } /** * Grants permission to delete a SAML provider resource in IAM * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSAMLProvider.html */ public toDeleteSAMLProvider() { return this.to('DeleteSAMLProvider'); } /** * Grants permission to delete the specified SSH public key * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSSHPublicKey.html */ public toDeleteSSHPublicKey() { return this.to('DeleteSSHPublicKey'); } /** * Grants permission to delete the specified server certificate * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServerCertificate.html */ public toDeleteServerCertificate() { return this.to('DeleteServerCertificate'); } /** * Grants permission to delete an IAM role that is linked to a specific AWS service, if the service is no longer using it * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceLinkedRole.html */ public toDeleteServiceLinkedRole() { return this.to('DeleteServiceLinkedRole'); } /** * Grants permission to delete the specified service-specific credential for an IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html */ public toDeleteServiceSpecificCredential() { return this.to('DeleteServiceSpecificCredential'); } /** * Grants permission to delete a signing certificate that is associated with the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSigningCertificate.html */ public toDeleteSigningCertificate() { return this.to('DeleteSigningCertificate'); } /** * Grants permission to delete the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUser.html */ public toDeleteUser() { return this.to('DeleteUser'); } /** * Grants permission to remove the permissions boundary from the specified IAM user * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUserPermissionsBoundary.html */ public toDeleteUserPermissionsBoundary() { return this.to('DeleteUserPermissionsBoundary'); } /** * Grants permission to delete the specified inline policy from an IAM user * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUserPolicy.html */ public toDeleteUserPolicy() { return this.to('DeleteUserPolicy'); } /** * Grants permission to delete a virtual MFA device * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteVirtualMFADevice.html */ public toDeleteVirtualMFADevice() { return this.to('DeleteVirtualMFADevice'); } /** * Grants permission to detach a managed policy from the specified IAM group * * Access Level: Permissions management * * Possible conditions: * - .ifPolicyARN() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DetachGroupPolicy.html */ public toDetachGroupPolicy() { return this.to('DetachGroupPolicy'); } /** * Grants permission to detach a managed policy from the specified role * * Access Level: Permissions management * * Possible conditions: * - .ifPolicyARN() * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DetachRolePolicy.html */ public toDetachRolePolicy() { return this.to('DetachRolePolicy'); } /** * Grants permission to detach a managed policy from the specified IAM user * * Access Level: Permissions management * * Possible conditions: * - .ifPolicyARN() * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_DetachUserPolicy.html */ public toDetachUserPolicy() { return this.to('DetachUserPolicy'); } /** * Grants permission to enable an MFA device and associate it with the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html */ public toEnableMFADevice() { return this.to('EnableMFADevice'); } /** * Grants permission to generate a credential report for the AWS account * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateCredentialReport.html */ public toGenerateCredentialReport() { return this.to('GenerateCredentialReport'); } /** * Grants permission to generate an access report for an AWS Organizations entity * * Access Level: Read * * Possible conditions: * - .ifOrganizationsPolicyId() * * Dependent actions: * - organizations:DescribePolicy * - organizations:ListChildren * - organizations:ListParents * - organizations:ListPoliciesForTarget * - organizations:ListRoots * - organizations:ListTargetsForPolicy * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateOrganizationsAccessReport.html */ public toGenerateOrganizationsAccessReport() { return this.to('GenerateOrganizationsAccessReport'); } /** * Grants permission to generate a service last accessed data report for an IAM resource * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateServiceLastAccessedDetails.html */ public toGenerateServiceLastAccessedDetails() { return this.to('GenerateServiceLastAccessedDetails'); } /** * Grants permission to retrieve information about when the specified access key was last used * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html */ public toGetAccessKeyLastUsed() { return this.to('GetAccessKeyLastUsed'); } /** * Grants permission to retrieve information about all IAM users, groups, roles, and policies in your AWS account, including their relationships to one another * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountAuthorizationDetails.html */ public toGetAccountAuthorizationDetails() { return this.to('GetAccountAuthorizationDetails'); } /** * Grants permission to retrieve the password policy for the AWS account * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountPasswordPolicy.html */ public toGetAccountPasswordPolicy() { return this.to('GetAccountPasswordPolicy'); } /** * Grants permission to retrieve information about IAM entity usage and IAM quotas in the AWS account * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountSummary.html */ public toGetAccountSummary() { return this.to('GetAccountSummary'); } /** * Grants permission to retrieve a list of all of the context keys that are referenced in the specified policy * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetContextKeysForCustomPolicy.html */ public toGetContextKeysForCustomPolicy() { return this.to('GetContextKeysForCustomPolicy'); } /** * Grants permission to retrieve a list of all context keys that are referenced in all IAM policies that are attached to the specified IAM identity (user, group, or role) * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetContextKeysForPrincipalPolicy.html */ public toGetContextKeysForPrincipalPolicy() { return this.to('GetContextKeysForPrincipalPolicy'); } /** * Grants permission to retrieve a credential report for the AWS account * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetCredentialReport.html */ public toGetCredentialReport() { return this.to('GetCredentialReport'); } /** * Grants permission to retrieve a list of IAM users in the specified IAM group * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetGroup.html */ public toGetGroup() { return this.to('GetGroup'); } /** * Grants permission to retrieve an inline policy document that is embedded in the specified IAM group * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetGroupPolicy.html */ public toGetGroupPolicy() { return this.to('GetGroupPolicy'); } /** * Grants permission to retrieve information about the specified instance profile, including the instance profile's path, GUID, ARN, and role * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetInstanceProfile.html */ public toGetInstanceProfile() { return this.to('GetInstanceProfile'); } /** * Grants permission to retrieve the user name and password creation date for the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetLoginProfile.html */ public toGetLoginProfile() { return this.to('GetLoginProfile'); } /** * Grants permission to retrieve information about the specified OpenID Connect (OIDC) provider resource in IAM * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOpenIDConnectProvider.html */ public toGetOpenIDConnectProvider() { return this.to('GetOpenIDConnectProvider'); } /** * Grants permission to retrieve an AWS Organizations access report * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetOrganizationsAccessReport.html */ public toGetOrganizationsAccessReport() { return this.to('GetOrganizationsAccessReport'); } /** * Grants permission to retrieve information about the specified managed policy, including the policy's default version and the total number of identities to which the policy is attached * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetPolicy.html */ public toGetPolicy() { return this.to('GetPolicy'); } /** * Grants permission to retrieve information about a version of the specified managed policy, including the policy document * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetPolicyVersion.html */ public toGetPolicyVersion() { return this.to('GetPolicyVersion'); } /** * Grants permission to retrieve information about the specified role, including the role's path, GUID, ARN, and the role's trust policy * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html */ public toGetRole() { return this.to('GetRole'); } /** * Grants permission to retrieve an inline policy document that is embedded with the specified IAM role * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRolePolicy.html */ public toGetRolePolicy() { return this.to('GetRolePolicy'); } /** * Grants permission to retrieve the SAML provider metadocument that was uploaded when the IAM SAML provider resource was created or updated * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetSAMLProvider.html */ public toGetSAMLProvider() { return this.to('GetSAMLProvider'); } /** * Grants permission to retrieve the specified SSH public key, including metadata about the key * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetSSHPublicKey.html */ public toGetSSHPublicKey() { return this.to('GetSSHPublicKey'); } /** * Grants permission to retrieve information about the specified server certificate stored in IAM * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetServerCertificate.html */ public toGetServerCertificate() { return this.to('GetServerCertificate'); } /** * Grants permission to retrieve information about the service last accessed data report * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetServiceLastAccessedDetails.html */ public toGetServiceLastAccessedDetails() { return this.to('GetServiceLastAccessedDetails'); } /** * Grants permission to retrieve information about the entities from the service last accessed data report * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetServiceLastAccessedDetailsWithEntities.html */ public toGetServiceLastAccessedDetailsWithEntities() { return this.to('GetServiceLastAccessedDetailsWithEntities'); } /** * Grants permission to retrieve an IAM service-linked role deletion status * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetServiceLinkedRoleDeletionStatus.html */ public toGetServiceLinkedRoleDeletionStatus() { return this.to('GetServiceLinkedRoleDeletionStatus'); } /** * Grants permission to retrieve information about the specified IAM user, including the user's creation date, path, unique ID, and ARN * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUser.html */ public toGetUser() { return this.to('GetUser'); } /** * Grants permission to retrieve an inline policy document that is embedded in the specified IAM user * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetUserPolicy.html */ public toGetUserPolicy() { return this.to('GetUserPolicy'); } /** * Grants permission to list information about the access key IDs that are associated with the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccessKeys.html */ public toListAccessKeys() { return this.to('ListAccessKeys'); } /** * Grants permission to list the account alias that is associated with the AWS account * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccountAliases.html */ public toListAccountAliases() { return this.to('ListAccountAliases'); } /** * Grants permission to list all managed policies that are attached to the specified IAM group * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedGroupPolicies.html */ public toListAttachedGroupPolicies() { return this.to('ListAttachedGroupPolicies'); } /** * Grants permission to list all managed policies that are attached to the specified IAM role * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedRolePolicies.html */ public toListAttachedRolePolicies() { return this.to('ListAttachedRolePolicies'); } /** * Grants permission to list all managed policies that are attached to the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedUserPolicies.html */ public toListAttachedUserPolicies() { return this.to('ListAttachedUserPolicies'); } /** * Grants permission to list all IAM identities to which the specified managed policy is attached * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListEntitiesForPolicy.html */ public toListEntitiesForPolicy() { return this.to('ListEntitiesForPolicy'); } /** * Grants permission to list the names of the inline policies that are embedded in the specified IAM group * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupPolicies.html */ public toListGroupPolicies() { return this.to('ListGroupPolicies'); } /** * Grants permission to list the IAM groups that have the specified path prefix * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroups.html */ public toListGroups() { return this.to('ListGroups'); } /** * Grants permission to list the IAM groups that the specified IAM user belongs to * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupsForUser.html */ public toListGroupsForUser() { return this.to('ListGroupsForUser'); } /** * Grants permission to list the tags that are attached to the specified instance profile * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfileTags.html */ public toListInstanceProfileTags() { return this.to('ListInstanceProfileTags'); } /** * Grants permission to list the instance profiles that have the specified path prefix * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html */ public toListInstanceProfiles() { return this.to('ListInstanceProfiles'); } /** * Grants permission to list the instance profiles that have the specified associated IAM role * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html */ public toListInstanceProfilesForRole() { return this.to('ListInstanceProfilesForRole'); } /** * Grants permission to list the tags that are attached to the specified virtual mfa device * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADeviceTags.html */ public toListMFADeviceTags() { return this.to('ListMFADeviceTags'); } /** * Grants permission to list the MFA devices for an IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADevices.html */ public toListMFADevices() { return this.to('ListMFADevices'); } /** * Grants permission to list the tags that are attached to the specified OpenID Connect provider * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviderTags.html */ public toListOpenIDConnectProviderTags() { return this.to('ListOpenIDConnectProviderTags'); } /** * Grants permission to list information about the IAM OpenID Connect (OIDC) provider resource objects that are defined in the AWS account * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListOpenIDConnectProviders.html */ public toListOpenIDConnectProviders() { return this.to('ListOpenIDConnectProviders'); } /** * Grants permission to list all managed policies * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicies.html */ public toListPolicies() { return this.to('ListPolicies'); } /** * Grants permission to list information about the policies that grant an entity access to a specific service * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPoliciesGrantingServiceAccess.html */ public toListPoliciesGrantingServiceAccess() { return this.to('ListPoliciesGrantingServiceAccess'); } /** * Grants permission to list the tags that are attached to the specified managed policy * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicyTags.html */ public toListPolicyTags() { return this.to('ListPolicyTags'); } /** * Grants permission to list information about the versions of the specified managed policy, including the version that is currently set as the policy's default version * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicyVersions.html */ public toListPolicyVersions() { return this.to('ListPolicyVersions'); } /** * Grants permission to list the names of the inline policies that are embedded in the specified IAM role * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRolePolicies.html */ public toListRolePolicies() { return this.to('ListRolePolicies'); } /** * Grants permission to list the tags that are attached to the specified IAM role * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRoleTags.html */ public toListRoleTags() { return this.to('ListRoleTags'); } /** * Grants permission to list the IAM roles that have the specified path prefix * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRoles.html */ public toListRoles() { return this.to('ListRoles'); } /** * Grants permission to list the tags that are attached to the specified SAML provider * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviderTags.html */ public toListSAMLProviderTags() { return this.to('ListSAMLProviderTags'); } /** * Grants permission to list the SAML provider resources in IAM * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSAMLProviders.html */ public toListSAMLProviders() { return this.to('ListSAMLProviders'); } /** * Grants permission to list information about the SSH public keys that are associated with the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSSHPublicKeys.html */ public toListSSHPublicKeys() { return this.to('ListSSHPublicKeys'); } /** * Grants permission to list the tags that are attached to the specified server certificate * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServerCertificateTags.html */ public toListServerCertificateTags() { return this.to('ListServerCertificateTags'); } /** * Grants permission to list the server certificates that have the specified path prefix * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServerCertificates.html */ public toListServerCertificates() { return this.to('ListServerCertificates'); } /** * Grants permission to list the service-specific credentials that are associated with the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListServiceSpecificCredentials.html */ public toListServiceSpecificCredentials() { return this.to('ListServiceSpecificCredentials'); } /** * Grants permission to list information about the signing certificates that are associated with the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSigningCertificates.html */ public toListSigningCertificates() { return this.to('ListSigningCertificates'); } /** * Grants permission to list the names of the inline policies that are embedded in the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUserPolicies.html */ public toListUserPolicies() { return this.to('ListUserPolicies'); } /** * Grants permission to list the tags that are attached to the specified IAM user * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUserTags.html */ public toListUserTags() { return this.to('ListUserTags'); } /** * Grants permission to list the IAM users that have the specified path prefix * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUsers.html */ public toListUsers() { return this.to('ListUsers'); } /** * Grants permission to list virtual MFA devices by assignment status * * Access Level: List * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListVirtualMFADevices.html */ public toListVirtualMFADevices() { return this.to('ListVirtualMFADevices'); } /** * Grants permission to pass a role to a service * * Access Level: Write * * Possible conditions: * - .ifAssociatedResourceArn() * - .ifPassedToService() * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html */ public toPassRole() { return this.to('PassRole'); } /** * Grants permission to create or update an inline policy document that is embedded in the specified IAM group * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutGroupPolicy.html */ public toPutGroupPolicy() { return this.to('PutGroupPolicy'); } /** * Grants permission to set a managed policy as a permissions boundary for a role * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html */ public toPutRolePermissionsBoundary() { return this.to('PutRolePermissionsBoundary'); } /** * Grants permission to create or update an inline policy document that is embedded in the specified IAM role * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html */ public toPutRolePolicy() { return this.to('PutRolePolicy'); } /** * Grants permission to set a managed policy as a permissions boundary for an IAM user * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutUserPermissionsBoundary.html */ public toPutUserPermissionsBoundary() { return this.to('PutUserPermissionsBoundary'); } /** * Grants permission to create or update an inline policy document that is embedded in the specified IAM user * * Access Level: Permissions management * * Possible conditions: * - .ifPermissionsBoundary() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutUserPolicy.html */ public toPutUserPolicy() { return this.to('PutUserPolicy'); } /** * Grants permission to remove the client ID (audience) from the list of client IDs in the specified IAM OpenID Connect (OIDC) provider resource * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveClientIDFromOpenIDConnectProvider.html */ public toRemoveClientIDFromOpenIDConnectProvider() { return this.to('RemoveClientIDFromOpenIDConnectProvider'); } /** * Grants permission to remove an IAM role from the specified EC2 instance profile * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html */ public toRemoveRoleFromInstanceProfile() { return this.to('RemoveRoleFromInstanceProfile'); } /** * Grants permission to remove an IAM user from the specified group * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveUserFromGroup.html */ public toRemoveUserFromGroup() { return this.to('RemoveUserFromGroup'); } /** * Grants permission to reset the password for an existing service-specific credential for an IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html */ public toResetServiceSpecificCredential() { return this.to('ResetServiceSpecificCredential'); } /** * Grants permission to synchronize the specified MFA device with its IAM entity (user or role) * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResyncMFADevice.html */ public toResyncMFADevice() { return this.to('ResyncMFADevice'); } /** * Grants permission to set the version of the specified policy as the policy's default version * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_SetDefaultPolicyVersion.html */ public toSetDefaultPolicyVersion() { return this.to('SetDefaultPolicyVersion'); } /** * Grants permission to set the STS global endpoint token version * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_SetSecurityTokenServicePreferences.html */ public toSetSecurityTokenServicePreferences() { return this.to('SetSecurityTokenServicePreferences'); } /** * Grants permission to simulate whether an identity-based policy or resource-based policy provides permissions for specific API operations and resources * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_SimulateCustomPolicy.html */ public toSimulateCustomPolicy() { return this.to('SimulateCustomPolicy'); } /** * Grants permission to simulate whether an identity-based policy that is attached to a specified IAM entity (user or role) provides permissions for specific API operations and resources * * Access Level: Read * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_SimulatePrincipalPolicy.html */ public toSimulatePrincipalPolicy() { return this.to('SimulatePrincipalPolicy'); } /** * Grants permission to add tags to an instance profile * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html */ public toTagInstanceProfile() { return this.to('TagInstanceProfile'); } /** * Grants permission to add tags to a virtual mfa device * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagMFADevice.html */ public toTagMFADevice() { return this.to('TagMFADevice'); } /** * Grants permission to add tags to an OpenID Connect provider * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagOpenIDConnectProvider.html */ public toTagOpenIDConnectProvider() { return this.to('TagOpenIDConnectProvider'); } /** * Grants permission to add tags to a managed policy * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagPolicy.html */ public toTagPolicy() { return this.to('TagPolicy'); } /** * Grants permission to add tags to an IAM role * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html */ public toTagRole() { return this.to('TagRole'); } /** * Grants permission to add tags to a SAML Provider * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagSAMLProvider.html */ public toTagSAMLProvider() { return this.to('TagSAMLProvider'); } /** * Grants permission to add tags to a server certificate * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagServerCertificate.html */ public toTagServerCertificate() { return this.to('TagServerCertificate'); } /** * Grants permission to add tags to an IAM user * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagUser.html */ public toTagUser() { return this.to('TagUser'); } /** * Grants permission to remove the specified tags from the instance profile * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagInstanceProfile.html */ public toUntagInstanceProfile() { return this.to('UntagInstanceProfile'); } /** * Grants permission to remove the specified tags from the virtual mfa device * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagMFADevice.html */ public toUntagMFADevice() { return this.to('UntagMFADevice'); } /** * Grants permission to remove the specified tags from the OpenID Connect provider * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagOpenIDConnectProvider.html */ public toUntagOpenIDConnectProvider() { return this.to('UntagOpenIDConnectProvider'); } /** * Grants permission to remove the specified tags from the managed policy * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagPolicy.html */ public toUntagPolicy() { return this.to('UntagPolicy'); } /** * Grants permission to remove the specified tags from the role * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagRole.html */ public toUntagRole() { return this.to('UntagRole'); } /** * Grants permission to remove the specified tags from the SAML Provider * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagSAMLProvider.html */ public toUntagSAMLProvider() { return this.to('UntagSAMLProvider'); } /** * Grants permission to remove the specified tags from the server certificate * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagServerCertificate.html */ public toUntagServerCertificate() { return this.to('UntagServerCertificate'); } /** * Grants permission to remove the specified tags from the user * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagUser.html */ public toUntagUser() { return this.to('UntagUser'); } /** * Grants permission to update the status of the specified access key as Active or Inactive * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html */ public toUpdateAccessKey() { return this.to('UpdateAccessKey'); } /** * Grants permission to update the password policy settings for the AWS account * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccountPasswordPolicy.html */ public toUpdateAccountPasswordPolicy() { return this.to('UpdateAccountPasswordPolicy'); } /** * Grants permission to update the policy that grants an IAM entity permission to assume a role * * Access Level: Permissions management * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAssumeRolePolicy.html */ public toUpdateAssumeRolePolicy() { return this.to('UpdateAssumeRolePolicy'); } /** * Grants permission to update the name or path of the specified IAM group * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateGroup.html */ public toUpdateGroup() { return this.to('UpdateGroup'); } /** * Grants permission to change the password for the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateLoginProfile.html */ public toUpdateLoginProfile() { return this.to('UpdateLoginProfile'); } /** * Grants permission to update the entire list of server certificate thumbprints that are associated with an OpenID Connect (OIDC) provider resource * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateOpenIDConnectProviderThumbprint.html */ public toUpdateOpenIDConnectProviderThumbprint() { return this.to('UpdateOpenIDConnectProviderThumbprint'); } /** * Grants permission to update the description or maximum session duration setting of a role * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html */ public toUpdateRole() { return this.to('UpdateRole'); } /** * Grants permission to update only the description of a role * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRoleDescription.html */ public toUpdateRoleDescription() { return this.to('UpdateRoleDescription'); } /** * Grants permission to update the metadata document for an existing SAML provider resource * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateSAMLProvider.html */ public toUpdateSAMLProvider() { return this.to('UpdateSAMLProvider'); } /** * Grants permission to update the status of an IAM user's SSH public key to active or inactive * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateSSHPublicKey.html */ public toUpdateSSHPublicKey() { return this.to('UpdateSSHPublicKey'); } /** * Grants permission to update the name or the path of the specified server certificate stored in IAM * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServerCertificate.html */ public toUpdateServerCertificate() { return this.to('UpdateServerCertificate'); } /** * Grants permission to update the status of a service-specific credential to active or inactive for an IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html */ public toUpdateServiceSpecificCredential() { return this.to('UpdateServiceSpecificCredential'); } /** * Grants permission to update the status of the specified user signing certificate to active or disabled * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateSigningCertificate.html */ public toUpdateSigningCertificate() { return this.to('UpdateSigningCertificate'); } /** * Grants permission to update the name or the path of the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateUser.html */ public toUpdateUser() { return this.to('UpdateUser'); } /** * Grants permission to upload an SSH public key and associate it with the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UploadSSHPublicKey.html */ public toUploadSSHPublicKey() { return this.to('UploadSSHPublicKey'); } /** * Grants permission to upload a server certificate entity for the AWS account * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UploadServerCertificate.html */ public toUploadServerCertificate() { return this.to('UploadServerCertificate'); } /** * Grants permission to upload an X.509 signing certificate and associate it with the specified IAM user * * Access Level: Write * * https://docs.aws.amazon.com/IAM/latest/APIReference/API_UploadSigningCertificate.html */ public toUploadSigningCertificate() { return this.to('UploadSigningCertificate'); } protected accessLevelList: AccessLevelList = { "Write": [ "AddClientIDToOpenIDConnectProvider", "AddRoleToInstanceProfile", "AddUserToGroup", "ChangePassword", "CreateAccessKey", "CreateAccountAlias", "CreateGroup", "CreateInstanceProfile", "CreateLoginProfile", "CreateOpenIDConnectProvider", "CreateRole", "CreateSAMLProvider", "CreateServiceLinkedRole", "CreateServiceSpecificCredential", "CreateUser", "CreateVirtualMFADevice", "DeactivateMFADevice", "DeleteAccessKey", "DeleteAccountAlias", "DeleteGroup", "DeleteInstanceProfile", "DeleteLoginProfile", "DeleteOpenIDConnectProvider", "DeleteRole", "DeleteSAMLProvider", "DeleteSSHPublicKey", "DeleteServerCertificate", "DeleteServiceLinkedRole", "DeleteServiceSpecificCredential", "DeleteSigningCertificate", "DeleteUser", "DeleteVirtualMFADevice", "EnableMFADevice", "PassRole", "RemoveClientIDFromOpenIDConnectProvider", "RemoveRoleFromInstanceProfile", "RemoveUserFromGroup", "ResetServiceSpecificCredential", "ResyncMFADevice", "SetSecurityTokenServicePreferences", "UpdateAccessKey", "UpdateAccountPasswordPolicy", "UpdateGroup", "UpdateLoginProfile", "UpdateOpenIDConnectProviderThumbprint", "UpdateRole", "UpdateRoleDescription", "UpdateSAMLProvider", "UpdateSSHPublicKey", "UpdateServerCertificate", "UpdateServiceSpecificCredential", "UpdateSigningCertificate", "UpdateUser", "UploadSSHPublicKey", "UploadServerCertificate", "UploadSigningCertificate" ], "Permissions management": [ "AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy", "CreatePolicy", "CreatePolicyVersion", "DeleteAccountPasswordPolicy", "DeleteGroupPolicy", "DeletePolicy", "DeletePolicyVersion", "DeleteRolePermissionsBoundary", "DeleteRolePolicy", "DeleteUserPermissionsBoundary", "DeleteUserPolicy", "DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy", "PutGroupPolicy", "PutRolePermissionsBoundary", "PutRolePolicy", "PutUserPermissionsBoundary", "PutUserPolicy", "SetDefaultPolicyVersion", "UpdateAssumeRolePolicy" ], "Read": [ "GenerateCredentialReport", "GenerateOrganizationsAccessReport", "GenerateServiceLastAccessedDetails", "GetAccessKeyLastUsed", "GetAccountAuthorizationDetails", "GetAccountPasswordPolicy", "GetContextKeysForCustomPolicy", "GetContextKeysForPrincipalPolicy", "GetCredentialReport", "GetGroup", "GetGroupPolicy", "GetInstanceProfile", "GetOpenIDConnectProvider", "GetOrganizationsAccessReport", "GetPolicy", "GetPolicyVersion", "GetRole", "GetRolePolicy", "GetSAMLProvider", "GetSSHPublicKey", "GetServerCertificate", "GetServiceLastAccessedDetails", "GetServiceLastAccessedDetailsWithEntities", "GetServiceLinkedRoleDeletionStatus", "GetUser", "GetUserPolicy", "SimulateCustomPolicy", "SimulatePrincipalPolicy" ], "List": [ "GetAccountSummary", "GetLoginProfile", "ListAccessKeys", "ListAccountAliases", "ListAttachedGroupPolicies", "ListAttachedRolePolicies", "ListAttachedUserPolicies", "ListEntitiesForPolicy", "ListGroupPolicies", "ListGroups", "ListGroupsForUser", "ListInstanceProfileTags", "ListInstanceProfiles", "ListInstanceProfilesForRole", "ListMFADeviceTags", "ListMFADevices", "ListOpenIDConnectProviderTags", "ListOpenIDConnectProviders", "ListPolicies", "ListPoliciesGrantingServiceAccess", "ListPolicyTags", "ListPolicyVersions", "ListRolePolicies", "ListRoleTags", "ListRoles", "ListSAMLProviderTags", "ListSAMLProviders", "ListSSHPublicKeys", "ListServerCertificateTags", "ListServerCertificates", "ListServiceSpecificCredentials", "ListSigningCertificates", "ListUserPolicies", "ListUserTags", "ListUsers", "ListVirtualMFADevices" ], "Tagging": [ "TagInstanceProfile", "TagMFADevice", "TagOpenIDConnectProvider", "TagPolicy", "TagRole", "TagSAMLProvider", "TagServerCertificate", "TagUser", "UntagInstanceProfile", "UntagMFADevice", "UntagOpenIDConnectProvider", "UntagPolicy", "UntagRole", "UntagSAMLProvider", "UntagServerCertificate", "UntagUser" ] }; /** * Adds a resource of type access-report to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor-view-data-orgs.html * * @param entityPath - Identifier for the entityPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAccessReport(entityPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:access-report/${EntityPath}'; arn = arn.replace('${EntityPath}', entityPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type assumed-role to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html * * @param roleName - Identifier for the roleName. * @param roleSessionName - Identifier for the roleSessionName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAssumedRole(roleName: string, roleSessionName: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:assumed-role/${RoleName}/${RoleSessionName}'; arn = arn.replace('${RoleName}', roleName); arn = arn.replace('${RoleSessionName}', roleSessionName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type federated-user to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html * * @param userName - Identifier for the userName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onFederatedUser(userName: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:federated-user/${UserName}'; arn = arn.replace('${UserName}', userName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type group to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html * * @param groupNameWithPath - Identifier for the groupNameWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onGroup(groupNameWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:group/${GroupNameWithPath}'; arn = arn.replace('${GroupNameWithPath}', groupNameWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type instance-profile to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html * * @param instanceProfileNameWithPath - Identifier for the instanceProfileNameWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onInstanceProfile(instanceProfileNameWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:instance-profile/${InstanceProfileNameWithPath}'; arn = arn.replace('${InstanceProfileNameWithPath}', instanceProfileNameWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type mfa to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html * * @param mfaTokenIdWithPath - Identifier for the mfaTokenIdWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onMfa(mfaTokenIdWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:mfa/${MfaTokenIdWithPath}'; arn = arn.replace('${MfaTokenIdWithPath}', mfaTokenIdWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type oidc-provider to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html * * @param oidcProviderName - Identifier for the oidcProviderName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onOidcProvider(oidcProviderName: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:oidc-provider/${OidcProviderName}'; arn = arn.replace('${OidcProviderName}', oidcProviderName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type policy to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html * * @param policyNameWithPath - Identifier for the policyNameWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onPolicy(policyNameWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:policy/${PolicyNameWithPath}'; arn = arn.replace('${PolicyNameWithPath}', policyNameWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type role to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html * * @param roleNameWithPath - Identifier for the roleNameWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceTag() */ public onRole(roleNameWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:role/${RoleNameWithPath}'; arn = arn.replace('${RoleNameWithPath}', roleNameWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type saml-provider to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html * * @param samlProviderName - Identifier for the samlProviderName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onSamlProvider(samlProviderName: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:saml-provider/${SamlProviderName}'; arn = arn.replace('${SamlProviderName}', samlProviderName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type server-certificate to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html * * @param certificateNameWithPath - Identifier for the certificateNameWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onServerCertificate(certificateNameWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:server-certificate/${CertificateNameWithPath}'; arn = arn.replace('${CertificateNameWithPath}', certificateNameWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type sms-mfa to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_sms.html * * @param mfaTokenIdWithPath - Identifier for the mfaTokenIdWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onSmsMfa(mfaTokenIdWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:sms-mfa/${MfaTokenIdWithPath}'; arn = arn.replace('${MfaTokenIdWithPath}', mfaTokenIdWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type user to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html * * @param userNameWithPath - Identifier for the userNameWithPath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceTag() */ public onUser(userNameWithPath: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:iam::${Account}:user/${UserNameWithPath}'; arn = arn.replace('${UserNameWithPath}', userNameWithPath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by the AWS service to which this role is attached * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_AWSServiceName * * Applies to actions: * - .toCreateServiceLinkedRole() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifAWSServiceName(value: string | string[], operator?: Operator | string) { return this.if(`AWSServiceName`, value, operator || 'StringLike'); } /** * Filters by the resource that the role will be used on behalf of * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_AssociatedResourceArn * * Applies to actions: * - .toPassRole() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifAssociatedResourceArn(value: string | string[], operator?: Operator | string) { return this.if(`AssociatedResourceArn`, value, operator || 'ArnLike'); } /** * Filters access by the ID of an AWS Organizations policy * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_OrganizationsPolicyId * * Applies to actions: * - .toGenerateOrganizationsAccessReport() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifOrganizationsPolicyId(value: string | string[], operator?: Operator | string) { return this.if(`OrganizationsPolicyId`, value, operator || 'StringLike'); } /** * Filters access by the AWS service to which this role is passed * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_PassedToService * * Applies to actions: * - .toPassRole() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifPassedToService(value: string | string[], operator?: Operator | string) { return this.if(`PassedToService`, value, operator || 'StringLike'); } /** * Filters access if the specified policy is set as the permissions boundary on the IAM entity (user or role) * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_PermissionsBoundary * * Applies to actions: * - .toAttachRolePolicy() * - .toAttachUserPolicy() * - .toCreateRole() * - .toCreateUser() * - .toDeleteRolePermissionsBoundary() * - .toDeleteRolePolicy() * - .toDeleteUserPermissionsBoundary() * - .toDeleteUserPolicy() * - .toDetachRolePolicy() * - .toDetachUserPolicy() * - .toPutRolePermissionsBoundary() * - .toPutRolePolicy() * - .toPutUserPermissionsBoundary() * - .toPutUserPolicy() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifPermissionsBoundary(value: string | string[], operator?: Operator | string) { return this.if(`PermissionsBoundary`, value, operator || 'StringLike'); } /** * Filters access by the ARN of an IAM policy * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_PolicyARN * * Applies to actions: * - .toAttachGroupPolicy() * - .toAttachRolePolicy() * - .toAttachUserPolicy() * - .toDetachGroupPolicy() * - .toDetachRolePolicy() * - .toDetachUserPolicy() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifPolicyARN(value: string | string[], operator?: Operator | string) { return this.if(`PolicyARN`, value, operator || 'ArnLike'); } /** * Filters access by the tags attached to an IAM entity (user or role) * * https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_ResourceTag * * Applies to resource types: * - role * - user * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`ResourceTag/${ tagKey }`, value, operator || 'StringLike'); } }
the_stack
import { expect } from 'chai' import { der2raw, raw2der } from '../src/ecdsa_signature' import { WebCryptoAlgorithmSuite, AlgorithmSuiteIdentifier, } from '@aws-crypto/material-management' /* * This turns out the be very tricky. * Test vectors are the path to your success. * In case you need to create more, * I am reproducing the parts needed to copy/paste yourself to victory. * * DER encoding stores integers as signed values. * This means if the first bit is a 1, * the value will be interpreted as negative. * So an extra byte needs to be added on. * This is a problem because "raw" encoding is just r|s. * Without this "extra logic" a given DER signature `sig` *may* * raw2der(der2raw(sig)) !== sig * see: https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf 8.3 # Data for all verification examples ``` const dataToSign = new Uint8Array([1,2,3,4]) ``` # Generating a key ## For browsers: ``` const { publicKey, privateKey } = await window.crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-384' }, true, ['sign', 'verify']) // Set variables so you can import const publicKeyBytes = await window.crypto.subtle.exportKey('spki', publicKey) const privateKeyBytes = await window.crypto.subtle.exportKey('pkcs8', privateKey) ``` ## For node.js (v12) ``` const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {namedCurve: 'secp384r1' }) // Set variables so you can import const publicKeyBytes = publicKey.export({ type: 'spki', format: 'der' }) const privateKeyBytes = privateKey.export({ type: 'pkcs8', format: 'der' }) ``` ### Helpful REPL lines to transfer data :) ``` 'const publicKeyBytes = new Uint8Array(' + JSON.stringify([...new Uint8Array(publicKeyBytes)]) + ')' 'const privateKeyBytes = new Uint8Array(' + JSON.stringify([...new Uint8Array(privateKeyBytes)]) + ')' ``` # Import keys from a different environment ## For browsers, from node.js ``` const publicKey = await window.crypto.subtle.importKey('spki', publicKeyBytes, { name: 'ECDSA', namedCurve: 'P-384' }, true, ['verify']) const privateKey = await window.crypto.subtle.importKey('pkcs8', privateKeyBytes, { name: 'ECDSA', namedCurve: 'P-384' }, true, ['sign']) ``` ## For node.js (v12) from browsers ``` const publicKey = crypto.createPublicKey({key: publicKeyBytes, format: 'der', type: 'spki'}) const privateKey = crypto.createPrivateKey({key: privateKeyBytes, format: 'der', type: 'pkcs8'}) ``` # Sign the data ## For browsers: ``` const signature = await window.crypto.subtle.sign({ name: 'ECDSA', hash: { name: 'SHA-384' } }, privateKey, dataToSign) ``` ## For node.js v12 ``` const signature = crypto.createSign('sha384').update(dataToSign).sign(privateKey) ``` # Verify the signature ## For browsers: ``` const verify = await window.crypto.subtle.verify({ name: 'ECDSA', hash: { name: 'SHA-384' } }, publicKey, signature, dataToSign) ``` ## For node.js v12 ``` const isVerified = crypto.createVerify('sha384').update(dataToSign).verify(publicKey, signature) ``` */ /* Browser verification const publicKeyBytes = new Uint8Array([4,199,199,40,132,29,178,63,39,29,51,216,142,122,137,115,70,152,91,198,68,95,101,88,187,240,227,232,177,5,206,158,174,156,228,250,254,167,216,195,179,21,136,7,14,50,154,73,49,222,215,184,15,42,108,247,118,126,164,207,62,168,64,30,63]) const webCryptoAlgorithm = { name: 'ECDSA', namedCurve: 'P-256' } const extractable = false const usages = ['verify'] const format = 'raw' const publicKey = await crypto.subtle.importKey(format, publicKeyBytes, webCryptoAlgorithm, extractable, usages) const algorithm = { name: 'ECDSA', hash: { name: 'SHA-256' } } const isVerified = await crypto.subtle.verify(algorithm, publicKey, rawSignature, dataToSign) */ /* Node verification const publicPem = `-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEx8cohB2yPycdM9iOeolzRphbxkRf ZVi78OPosQXOnq6c5Pr+p9jDsxWIBw4ymkkx3te4Dyps93Z+pM8+qEAePw== -----END PUBLIC KEY----- ` const v = createVerify('sha256') v.update(dataToSign) const isVerified = v.verify(publicPem, derSignature) */ const validSuite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const rawSignature = new Uint8Array([ 22, 77, 187, 192, 175, 104, 2, 240, 55, 2, 6, 138, 103, 148, 214, 240, 244, 65, 224, 254, 60, 52, 218, 22, 250, 245, 216, 228, 151, 151, 220, 234, 125, 9, 97, 8, 132, 123, 79, 193, 216, 207, 214, 0, 73, 183, 149, 173, 26, 173, 251, 132, 140, 139, 44, 122, 11, 50, 163, 105, 138, 221, 223, 29, ]) const derSignature = new Uint8Array([ 48, 68, 2, 32, 22, 77, 187, 192, 175, 104, 2, 240, 55, 2, 6, 138, 103, 148, 214, 240, 244, 65, 224, 254, 60, 52, 218, 22, 250, 245, 216, 228, 151, 151, 220, 234, 2, 32, 125, 9, 97, 8, 132, 123, 79, 193, 216, 207, 214, 0, 73, 183, 149, 173, 26, 173, 251, 132, 140, 139, 44, 122, 11, 50, 163, 105, 138, 221, 223, 29, ]) const invalidLengthRawSignature = new Uint8Array([ 0, 22, 77, 187, 192, 175, 104, 2, 240, 55, 2, 6, 138, 103, 148, 214, 240, 244, 65, 224, 254, 60, 52, 218, 22, 250, 245, 216, 228, 151, 151, 220, 234, 125, 9, 97, 8, 132, 123, 79, 193, 216, 207, 214, 0, 73, 183, 149, 173, 26, 173, 251, 132, 140, 139, 44, 122, 11, 50, 163, 105, 138, 221, 223, 29, 0, ]) /* // All signatures should be verified with this public key (spki in bytes) const publicKeyBytes = new Uint8Array([48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,182,142,16,181,73,22,77,38,171,216,20,142,20,154,218,20,31,70,13,88,242,169,247,248,184,238,221,100,191,26,82,176,137,96,163,242,244,215,25,250,144,157,65,246,201,220,219,188,122,115,129,227,74,201,236,240,93,173,108,36,49,249,149,224,67,76,66,192,255,173,90,184,124,191,154,165,137,251,173,181,109,109,75,167,34,202,198,114,192,197,215,224,199,45,105,126]) */ /* The following may be useful along with the above code to create additional test vectors. ``` function test() { let i = 100 while (i--) { const sig = crypto.createSign('sha384').update(dataToSign).sign(privateKey) if ((sig[4] === 0 ? sig[56] : sig[55]) === 128) return sig if (sig[5] === 128) return sig } } ``` */ /* DER signatures for SHA384_ECDSA_P384 that exhibit different lengths, * and padding of r and s. */ // length == 102 const derSigNoPadding = new Uint8Array([ 48, 100, 2, 48, 125, 32, 154, 168, 112, 11, 187, 171, 135, 119, 83, 66, 69, 164, 226, 80, 39, 176, 112, 210, 72, 159, 201, 242, 110, 212, 158, 170, 99, 155, 80, 29, 99, 77, 158, 81, 170, 46, 116, 246, 137, 197, 82, 112, 70, 36, 196, 49, 2, 48, 117, 43, 254, 192, 131, 207, 80, 1, 152, 238, 154, 139, 42, 81, 244, 230, 42, 114, 137, 98, 127, 86, 166, 26, 172, 80, 132, 251, 97, 249, 4, 39, 47, 250, 132, 44, 187, 235, 197, 157, 56, 216, 39, 130, 69, 46, 185, 150, ]) const rawSigNoPadding = new Uint8Array([ 125, 32, 154, 168, 112, 11, 187, 171, 135, 119, 83, 66, 69, 164, 226, 80, 39, 176, 112, 210, 72, 159, 201, 242, 110, 212, 158, 170, 99, 155, 80, 29, 99, 77, 158, 81, 170, 46, 116, 246, 137, 197, 82, 112, 70, 36, 196, 49, 117, 43, 254, 192, 131, 207, 80, 1, 152, 238, 154, 139, 42, 81, 244, 230, 42, 114, 137, 98, 127, 86, 166, 26, 172, 80, 132, 251, 97, 249, 4, 39, 47, 250, 132, 44, 187, 235, 197, 157, 56, 216, 39, 130, 69, 46, 185, 150, ]) // length == 103, r is padded const derSigRPadded1 = new Uint8Array([ 48, 101, 2, 49, 0, 163, 81, 253, 131, 61, 166, 239, 242, 68, 133, 70, 219, 243, 67, 220, 94, 57, 115, 92, 119, 17, 93, 152, 78, 78, 177, 110, 48, 164, 12, 53, 146, 223, 8, 57, 108, 177, 237, 187, 165, 39, 162, 214, 193, 112, 220, 132, 13, 2, 48, 10, 2, 53, 95, 195, 68, 6, 79, 110, 220, 215, 130, 204, 182, 125, 44, 47, 198, 226, 17, 115, 207, 22, 89, 113, 18, 90, 63, 0, 105, 104, 221, 159, 156, 17, 168, 95, 96, 254, 88, 45, 120, 223, 180, 12, 44, 118, 18, ]) const rawSigRPadded1 = new Uint8Array([ 163, 81, 253, 131, 61, 166, 239, 242, 68, 133, 70, 219, 243, 67, 220, 94, 57, 115, 92, 119, 17, 93, 152, 78, 78, 177, 110, 48, 164, 12, 53, 146, 223, 8, 57, 108, 177, 237, 187, 165, 39, 162, 214, 193, 112, 220, 132, 13, 10, 2, 53, 95, 195, 68, 6, 79, 110, 220, 215, 130, 204, 182, 125, 44, 47, 198, 226, 17, 115, 207, 22, 89, 113, 18, 90, 63, 0, 105, 104, 221, 159, 156, 17, 168, 95, 96, 254, 88, 45, 120, 223, 180, 12, 44, 118, 18, ]) // length == 103, s is padded const derSigSPadded1 = new Uint8Array([ 48, 101, 2, 48, 13, 237, 65, 195, 0, 118, 121, 114, 12, 187, 102, 24, 62, 8, 42, 43, 27, 18, 27, 123, 222, 46, 84, 53, 255, 198, 169, 180, 206, 77, 60, 3, 171, 209, 129, 25, 245, 157, 197, 128, 191, 153, 226, 52, 170, 3, 93, 180, 2, 49, 0, 191, 191, 7, 215, 111, 31, 5, 75, 245, 134, 50, 255, 118, 224, 243, 133, 233, 162, 55, 22, 203, 124, 69, 231, 1, 190, 191, 175, 158, 82, 80, 168, 172, 29, 97, 13, 141, 126, 184, 238, 159, 214, 213, 92, 114, 94, 61, 82, ]) const rawSigSPadded1 = new Uint8Array([ 13, 237, 65, 195, 0, 118, 121, 114, 12, 187, 102, 24, 62, 8, 42, 43, 27, 18, 27, 123, 222, 46, 84, 53, 255, 198, 169, 180, 206, 77, 60, 3, 171, 209, 129, 25, 245, 157, 197, 128, 191, 153, 226, 52, 170, 3, 93, 180, 191, 191, 7, 215, 111, 31, 5, 75, 245, 134, 50, 255, 118, 224, 243, 133, 233, 162, 55, 22, 203, 124, 69, 231, 1, 190, 191, 175, 158, 82, 80, 168, 172, 29, 97, 13, 141, 126, 184, 238, 159, 214, 213, 92, 114, 94, 61, 82, ]) // length == 104 both r and s are padded const derSigBothSandRPadded = new Uint8Array([ 48, 102, 2, 49, 0, 161, 31, 228, 163, 249, 149, 236, 238, 15, 140, 163, 28, 152, 199, 168, 83, 187, 60, 79, 26, 71, 243, 120, 0, 44, 200, 217, 82, 162, 181, 168, 194, 181, 56, 20, 193, 213, 40, 112, 59, 13, 254, 55, 177, 231, 189, 128, 71, 2, 49, 0, 241, 232, 224, 60, 113, 203, 248, 143, 34, 63, 98, 221, 156, 143, 58, 106, 169, 169, 63, 126, 103, 145, 63, 246, 255, 32, 74, 11, 197, 255, 13, 244, 105, 188, 157, 210, 200, 36, 140, 218, 1, 115, 99, 255, 212, 71, 156, 38, ]) const rawSigBothSandRPadded = new Uint8Array([ 161, 31, 228, 163, 249, 149, 236, 238, 15, 140, 163, 28, 152, 199, 168, 83, 187, 60, 79, 26, 71, 243, 120, 0, 44, 200, 217, 82, 162, 181, 168, 194, 181, 56, 20, 193, 213, 40, 112, 59, 13, 254, 55, 177, 231, 189, 128, 71, 241, 232, 224, 60, 113, 203, 248, 143, 34, 63, 98, 221, 156, 143, 58, 106, 169, 169, 63, 126, 103, 145, 63, 246, 255, 32, 74, 11, 197, 255, 13, 244, 105, 188, 157, 210, 200, 36, 140, 218, 1, 115, 99, 255, 212, 71, 156, 38, ]) // Suite AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 const derSigSPadded2 = new Uint8Array([ 48, 101, 2, 49, 0, 206, 207, 127, 87, 135, 99, 138, 178, 184, 182, 16, 31, 28, 196, 105, 124, 25, 66, 150, 72, 89, 3, 170, 18, 226, 212, 211, 102, 87, 24, 100, 142, 19, 231, 192, 75, 170, 233, 113, 106, 52, 106, 218, 240, 88, 104, 184, 244, 2, 48, 0, 243, 34, 43, 43, 42, 51, 175, 155, 222, 78, 148, 98, 211, 255, 81, 171, 101, 118, 207, 128, 50, 101, 16, 181, 174, 34, 59, 245, 237, 246, 92, 103, 13, 144, 249, 54, 248, 1, 74, 205, 79, 83, 52, 249, 106, 46, 185, ]) const rawSigSPadded2 = new Uint8Array([ 206, 207, 127, 87, 135, 99, 138, 178, 184, 182, 16, 31, 28, 196, 105, 124, 25, 66, 150, 72, 89, 3, 170, 18, 226, 212, 211, 102, 87, 24, 100, 142, 19, 231, 192, 75, 170, 233, 113, 106, 52, 106, 218, 240, 88, 104, 184, 244, 0, 243, 34, 43, 43, 42, 51, 175, 155, 222, 78, 148, 98, 211, 255, 81, 171, 101, 118, 207, 128, 50, 101, 16, 181, 174, 34, 59, 245, 237, 246, 92, 103, 13, 144, 249, 54, 248, 1, 74, 205, 79, 83, 52, 249, 106, 46, 185, ]) // Suite AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 const derSigSPadded3 = new Uint8Array([ 48, 100, 2, 48, 3, 174, 112, 110, 38, 199, 245, 110, 255, 244, 216, 238, 8, 146, 175, 220, 53, 45, 2, 91, 102, 60, 134, 249, 53, 226, 56, 240, 122, 166, 67, 33, 106, 207, 9, 53, 2, 92, 141, 76, 160, 118, 192, 12, 170, 162, 98, 175, 2, 48, 0, 229, 249, 27, 0, 39, 69, 9, 104, 23, 106, 211, 90, 91, 144, 34, 124, 56, 104, 187, 224, 172, 166, 3, 130, 202, 230, 120, 84, 197, 8, 175, 200, 37, 52, 206, 23, 210, 129, 215, 103, 252, 66, 61, 47, 179, 31, 191, ]) const rawSigSPadded3 = new Uint8Array([ 3, 174, 112, 110, 38, 199, 245, 110, 255, 244, 216, 238, 8, 146, 175, 220, 53, 45, 2, 91, 102, 60, 134, 249, 53, 226, 56, 240, 122, 166, 67, 33, 106, 207, 9, 53, 2, 92, 141, 76, 160, 118, 192, 12, 170, 162, 98, 175, 0, 229, 249, 27, 0, 39, 69, 9, 104, 23, 106, 211, 90, 91, 144, 34, 124, 56, 104, 187, 224, 172, 166, 3, 130, 202, 230, 120, 84, 197, 8, 175, 200, 37, 52, 206, 23, 210, 129, 215, 103, 252, 66, 61, 47, 179, 31, 191, ]) // Suite AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 const derSigRPadded2 = new Uint8Array([ 48, 99, 2, 47, 26, 164, 142, 247, 57, 120, 102, 219, 166, 194, 246, 139, 155, 151, 31, 222, 39, 27, 176, 125, 4, 225, 191, 115, 206, 227, 133, 126, 132, 71, 27, 95, 99, 34, 68, 77, 155, 175, 77, 111, 199, 68, 75, 181, 35, 103, 80, 2, 48, 124, 106, 76, 171, 45, 237, 33, 38, 6, 243, 85, 223, 236, 216, 120, 53, 193, 229, 52, 139, 42, 178, 10, 217, 25, 236, 232, 148, 53, 85, 68, 73, 105, 97, 134, 176, 51, 81, 52, 118, 213, 36, 195, 16, 187, 114, 85, 182, ]) const rawSigRPadded2 = new Uint8Array([ 0, 26, 164, 142, 247, 57, 120, 102, 219, 166, 194, 246, 139, 155, 151, 31, 222, 39, 27, 176, 125, 4, 225, 191, 115, 206, 227, 133, 126, 132, 71, 27, 95, 99, 34, 68, 77, 155, 175, 77, 111, 199, 68, 75, 181, 35, 103, 80, 124, 106, 76, 171, 45, 237, 33, 38, 6, 243, 85, 223, 236, 216, 120, 53, 193, 229, 52, 139, 42, 178, 10, 217, 25, 236, 232, 148, 53, 85, 68, 73, 105, 97, 134, 176, 51, 81, 52, 118, 213, 36, 195, 16, 187, 114, 85, 182, ]) /* This vector has the "first byte" of r === 128. * This means that the "first bit" of r === 1. * This means the DER signature is padded. */ const derSigRonBoundary = new Uint8Array([ 48, 102, 2, 49, 0, 128, 193, 160, 46, 142, 254, 87, 100, 216, 114, 75, 154, 209, 17, 184, 155, 141, 178, 118, 99, 34, 161, 229, 195, 144, 1, 183, 41, 165, 115, 107, 123, 234, 39, 90, 43, 247, 108, 227, 88, 144, 107, 230, 39, 103, 213, 174, 206, 2, 49, 0, 209, 70, 36, 78, 124, 248, 10, 77, 80, 102, 88, 38, 166, 138, 237, 192, 93, 189, 17, 157, 57, 203, 245, 93, 178, 19, 206, 31, 13, 117, 4, 241, 176, 107, 169, 23, 39, 71, 127, 32, 210, 157, 82, 115, 163, 177, 42, 74, ]) const rawSigRonBoundary = new Uint8Array([ 128, 193, 160, 46, 142, 254, 87, 100, 216, 114, 75, 154, 209, 17, 184, 155, 141, 178, 118, 99, 34, 161, 229, 195, 144, 1, 183, 41, 165, 115, 107, 123, 234, 39, 90, 43, 247, 108, 227, 88, 144, 107, 230, 39, 103, 213, 174, 206, 209, 70, 36, 78, 124, 248, 10, 77, 80, 102, 88, 38, 166, 138, 237, 192, 93, 189, 17, 157, 57, 203, 245, 93, 178, 19, 206, 31, 13, 117, 4, 241, 176, 107, 169, 23, 39, 71, 127, 32, 210, 157, 82, 115, 163, 177, 42, 74, ]) /* This vector has the "first byte" of s === 128. * This means that the "first bit" of s === 1. * This means the DER signature is padded. */ const derSigSonBoundary = new Uint8Array([ 48, 101, 2, 48, 99, 9, 32, 95, 74, 230, 183, 174, 87, 124, 144, 130, 171, 98, 39, 162, 23, 207, 58, 218, 73, 183, 190, 173, 107, 46, 130, 60, 185, 45, 245, 81, 57, 191, 60, 41, 6, 8, 68, 241, 221, 25, 122, 145, 25, 229, 148, 158, 2, 49, 0, 128, 50, 250, 23, 18, 25, 233, 203, 214, 199, 87, 201, 51, 187, 231, 99, 99, 114, 101, 252, 197, 48, 94, 2, 1, 12, 154, 225, 237, 112, 63, 95, 149, 14, 159, 190, 177, 241, 121, 75, 133, 77, 148, 78, 11, 34, 215, 58, ]) const rawSigSonBoundary = new Uint8Array([ 99, 9, 32, 95, 74, 230, 183, 174, 87, 124, 144, 130, 171, 98, 39, 162, 23, 207, 58, 218, 73, 183, 190, 173, 107, 46, 130, 60, 185, 45, 245, 81, 57, 191, 60, 41, 6, 8, 68, 241, 221, 25, 122, 145, 25, 229, 148, 158, 128, 50, 250, 23, 18, 25, 233, 203, 214, 199, 87, 201, 51, 187, 231, 99, 99, 114, 101, 252, 197, 48, 94, 2, 1, 12, 154, 225, 237, 112, 63, 95, 149, 14, 159, 190, 177, 241, 121, 75, 133, 77, 148, 78, 11, 34, 215, 58, ]) describe('der2raw', () => { it('transform to raw signature', () => { const signature = der2raw(derSignature, validSuite) expect(signature).to.deep.equal(rawSignature) }) it('Precondition: Do not attempt to RAW format if the suite does not support signing.', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) expect(() => der2raw(derSignature, suite)).to.throw() }) describe('padding', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 ) const commitSuite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 ) it('No Padding', () => { expect(der2raw(derSigNoPadding, suite)).to.deep.equal(rawSigNoPadding) }) it('R padded', () => { expect(der2raw(derSigRPadded1, suite)).to.deep.equal(rawSigRPadded1) }) it('S padded', () => { expect(der2raw(derSigSPadded1, suite)).to.deep.equal(rawSigSPadded1) }) it('R and S padded', () => { expect(der2raw(derSigBothSandRPadded, suite)).to.deep.equal( rawSigBothSandRPadded ) }) it('S padded', () => { expect(der2raw(derSigSPadded2, commitSuite)).to.deep.equal(rawSigSPadded2) }) it('S padded (with no padding in DER)', () => { expect(der2raw(derSigSPadded3, commitSuite)).to.deep.equal(rawSigSPadded3) }) it('R padded', () => { expect(der2raw(derSigRPadded2, commitSuite)).to.deep.equal(rawSigRPadded2) }) it('transform to der signature with with r padded, but r is on the padding boundary', () => { expect(der2raw(derSigRonBoundary, suite)).to.deep.equal(rawSigRonBoundary) }) it('transform to der signature with s padded, but s is on the padding boundary', () => { expect(der2raw(derSigSonBoundary, suite)).to.deep.equal(rawSigSonBoundary) }) }) }) describe('raw2der', () => { it('transform to der signature', () => { const signature = raw2der(rawSignature, validSuite) expect(signature).to.deep.equal(derSignature) }) it('Precondition: Do not attempt to DER format if the suite does not support signing.', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) expect(() => raw2der(rawSignature, suite)).to.throw() }) const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 ) it('Precondition: The total raw signature length is twice the key length bytes.', () => { expect(() => raw2der(invalidLengthRawSignature, suite)).to.throw( 'Malformed signature.' ) }) describe('padding', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 ) const commitSuite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 ) it('No Padding', () => { expect(raw2der(rawSigNoPadding, suite)).to.deep.equal(derSigNoPadding) }) it('R padded', () => { expect(raw2der(rawSigRPadded1, suite)).to.deep.equal(derSigRPadded1) }) it('S padded', () => { expect(raw2der(rawSigSPadded1, suite)).to.deep.equal(derSigSPadded1) }) it('R and S padded', () => { expect(raw2der(rawSigBothSandRPadded, suite)).to.deep.equal( derSigBothSandRPadded ) }) it('S padded', () => { expect(raw2der(rawSigSPadded2, commitSuite)).to.deep.equal(derSigSPadded2) }) it('S padded (with no padding in DER)', () => { expect(raw2der(rawSigSPadded3, commitSuite)).to.deep.equal(derSigSPadded3) }) it('R padded', () => { expect(raw2der(rawSigRPadded2, commitSuite)).to.deep.equal(derSigRPadded2) }) it('transform to der signature with with r padded, but r is on the padding boundary', () => { expect(raw2der(rawSigRonBoundary, suite)).to.deep.equal(derSigRonBoundary) }) it('transform to der signature with s padded, but s is on the padding boundary', () => { expect(raw2der(rawSigSonBoundary, suite)).to.deep.equal(derSigSonBoundary) }) }) })
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class IVS extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: IVS.Types.ClientConfiguration) config: Config & IVS.Types.ClientConfiguration; /** * Performs GetChannel on multiple ARNs simultaneously. */ batchGetChannel(params: IVS.Types.BatchGetChannelRequest, callback?: (err: AWSError, data: IVS.Types.BatchGetChannelResponse) => void): Request<IVS.Types.BatchGetChannelResponse, AWSError>; /** * Performs GetChannel on multiple ARNs simultaneously. */ batchGetChannel(callback?: (err: AWSError, data: IVS.Types.BatchGetChannelResponse) => void): Request<IVS.Types.BatchGetChannelResponse, AWSError>; /** * Performs GetStreamKey on multiple ARNs simultaneously. */ batchGetStreamKey(params: IVS.Types.BatchGetStreamKeyRequest, callback?: (err: AWSError, data: IVS.Types.BatchGetStreamKeyResponse) => void): Request<IVS.Types.BatchGetStreamKeyResponse, AWSError>; /** * Performs GetStreamKey on multiple ARNs simultaneously. */ batchGetStreamKey(callback?: (err: AWSError, data: IVS.Types.BatchGetStreamKeyResponse) => void): Request<IVS.Types.BatchGetStreamKeyResponse, AWSError>; /** * Creates a new channel and an associated stream key to start streaming. */ createChannel(params: IVS.Types.CreateChannelRequest, callback?: (err: AWSError, data: IVS.Types.CreateChannelResponse) => void): Request<IVS.Types.CreateChannelResponse, AWSError>; /** * Creates a new channel and an associated stream key to start streaming. */ createChannel(callback?: (err: AWSError, data: IVS.Types.CreateChannelResponse) => void): Request<IVS.Types.CreateChannelResponse, AWSError>; /** * Creates a stream key, used to initiate a stream, for the specified channel ARN. Note that CreateChannel creates a stream key. If you subsequently use CreateStreamKey on the same channel, it will fail because a stream key already exists and there is a limit of 1 stream key per channel. To reset the stream key on a channel, use DeleteStreamKey and then CreateStreamKey. */ createStreamKey(params: IVS.Types.CreateStreamKeyRequest, callback?: (err: AWSError, data: IVS.Types.CreateStreamKeyResponse) => void): Request<IVS.Types.CreateStreamKeyResponse, AWSError>; /** * Creates a stream key, used to initiate a stream, for the specified channel ARN. Note that CreateChannel creates a stream key. If you subsequently use CreateStreamKey on the same channel, it will fail because a stream key already exists and there is a limit of 1 stream key per channel. To reset the stream key on a channel, use DeleteStreamKey and then CreateStreamKey. */ createStreamKey(callback?: (err: AWSError, data: IVS.Types.CreateStreamKeyResponse) => void): Request<IVS.Types.CreateStreamKeyResponse, AWSError>; /** * Deletes the specified channel and its associated stream keys. */ deleteChannel(params: IVS.Types.DeleteChannelRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified channel and its associated stream keys. */ deleteChannel(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a specified authorization key pair. This invalidates future viewer tokens generated using the key pair’s privateKey. */ deletePlaybackKeyPair(params: IVS.Types.DeletePlaybackKeyPairRequest, callback?: (err: AWSError, data: IVS.Types.DeletePlaybackKeyPairResponse) => void): Request<IVS.Types.DeletePlaybackKeyPairResponse, AWSError>; /** * Deletes a specified authorization key pair. This invalidates future viewer tokens generated using the key pair’s privateKey. */ deletePlaybackKeyPair(callback?: (err: AWSError, data: IVS.Types.DeletePlaybackKeyPairResponse) => void): Request<IVS.Types.DeletePlaybackKeyPairResponse, AWSError>; /** * Deletes the stream key for the specified ARN, so it can no longer be used to stream. */ deleteStreamKey(params: IVS.Types.DeleteStreamKeyRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the stream key for the specified ARN, so it can no longer be used to stream. */ deleteStreamKey(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Gets the channel configuration for the specified channel ARN. See also BatchGetChannel. */ getChannel(params: IVS.Types.GetChannelRequest, callback?: (err: AWSError, data: IVS.Types.GetChannelResponse) => void): Request<IVS.Types.GetChannelResponse, AWSError>; /** * Gets the channel configuration for the specified channel ARN. See also BatchGetChannel. */ getChannel(callback?: (err: AWSError, data: IVS.Types.GetChannelResponse) => void): Request<IVS.Types.GetChannelResponse, AWSError>; /** * Gets a specified playback authorization key pair and returns the arn and fingerprint. The privateKey held by the caller can be used to generate viewer authorization tokens, to grant viewers access to authorized channels. */ getPlaybackKeyPair(params: IVS.Types.GetPlaybackKeyPairRequest, callback?: (err: AWSError, data: IVS.Types.GetPlaybackKeyPairResponse) => void): Request<IVS.Types.GetPlaybackKeyPairResponse, AWSError>; /** * Gets a specified playback authorization key pair and returns the arn and fingerprint. The privateKey held by the caller can be used to generate viewer authorization tokens, to grant viewers access to authorized channels. */ getPlaybackKeyPair(callback?: (err: AWSError, data: IVS.Types.GetPlaybackKeyPairResponse) => void): Request<IVS.Types.GetPlaybackKeyPairResponse, AWSError>; /** * Gets information about the active (live) stream on a specified channel. */ getStream(params: IVS.Types.GetStreamRequest, callback?: (err: AWSError, data: IVS.Types.GetStreamResponse) => void): Request<IVS.Types.GetStreamResponse, AWSError>; /** * Gets information about the active (live) stream on a specified channel. */ getStream(callback?: (err: AWSError, data: IVS.Types.GetStreamResponse) => void): Request<IVS.Types.GetStreamResponse, AWSError>; /** * Gets stream-key information for a specified ARN. */ getStreamKey(params: IVS.Types.GetStreamKeyRequest, callback?: (err: AWSError, data: IVS.Types.GetStreamKeyResponse) => void): Request<IVS.Types.GetStreamKeyResponse, AWSError>; /** * Gets stream-key information for a specified ARN. */ getStreamKey(callback?: (err: AWSError, data: IVS.Types.GetStreamKeyResponse) => void): Request<IVS.Types.GetStreamKeyResponse, AWSError>; /** * Imports the public portion of a new key pair and returns its arn and fingerprint. The privateKey can then be used to generate viewer authorization tokens, to grant viewers access to authorized channels. */ importPlaybackKeyPair(params: IVS.Types.ImportPlaybackKeyPairRequest, callback?: (err: AWSError, data: IVS.Types.ImportPlaybackKeyPairResponse) => void): Request<IVS.Types.ImportPlaybackKeyPairResponse, AWSError>; /** * Imports the public portion of a new key pair and returns its arn and fingerprint. The privateKey can then be used to generate viewer authorization tokens, to grant viewers access to authorized channels. */ importPlaybackKeyPair(callback?: (err: AWSError, data: IVS.Types.ImportPlaybackKeyPairResponse) => void): Request<IVS.Types.ImportPlaybackKeyPairResponse, AWSError>; /** * Gets summary information about all channels in your account, in the AWS region where the API request is processed. This list can be filtered to match a specified string. */ listChannels(params: IVS.Types.ListChannelsRequest, callback?: (err: AWSError, data: IVS.Types.ListChannelsResponse) => void): Request<IVS.Types.ListChannelsResponse, AWSError>; /** * Gets summary information about all channels in your account, in the AWS region where the API request is processed. This list can be filtered to match a specified string. */ listChannels(callback?: (err: AWSError, data: IVS.Types.ListChannelsResponse) => void): Request<IVS.Types.ListChannelsResponse, AWSError>; /** * Gets summary information about playback key pairs. */ listPlaybackKeyPairs(params: IVS.Types.ListPlaybackKeyPairsRequest, callback?: (err: AWSError, data: IVS.Types.ListPlaybackKeyPairsResponse) => void): Request<IVS.Types.ListPlaybackKeyPairsResponse, AWSError>; /** * Gets summary information about playback key pairs. */ listPlaybackKeyPairs(callback?: (err: AWSError, data: IVS.Types.ListPlaybackKeyPairsResponse) => void): Request<IVS.Types.ListPlaybackKeyPairsResponse, AWSError>; /** * Gets summary information about stream keys for the specified channel. */ listStreamKeys(params: IVS.Types.ListStreamKeysRequest, callback?: (err: AWSError, data: IVS.Types.ListStreamKeysResponse) => void): Request<IVS.Types.ListStreamKeysResponse, AWSError>; /** * Gets summary information about stream keys for the specified channel. */ listStreamKeys(callback?: (err: AWSError, data: IVS.Types.ListStreamKeysResponse) => void): Request<IVS.Types.ListStreamKeysResponse, AWSError>; /** * Gets summary information about live streams in your account, in the AWS region where the API request is processed. */ listStreams(params: IVS.Types.ListStreamsRequest, callback?: (err: AWSError, data: IVS.Types.ListStreamsResponse) => void): Request<IVS.Types.ListStreamsResponse, AWSError>; /** * Gets summary information about live streams in your account, in the AWS region where the API request is processed. */ listStreams(callback?: (err: AWSError, data: IVS.Types.ListStreamsResponse) => void): Request<IVS.Types.ListStreamsResponse, AWSError>; /** * Gets information about AWS tags for the specified ARN. */ listTagsForResource(params: IVS.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: IVS.Types.ListTagsForResourceResponse) => void): Request<IVS.Types.ListTagsForResourceResponse, AWSError>; /** * Gets information about AWS tags for the specified ARN. */ listTagsForResource(callback?: (err: AWSError, data: IVS.Types.ListTagsForResourceResponse) => void): Request<IVS.Types.ListTagsForResourceResponse, AWSError>; /** * Inserts metadata into an RTMPS stream for the specified channel. A maximum of 5 requests per second per channel is allowed, each with a maximum 1KB payload. */ putMetadata(params: IVS.Types.PutMetadataRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Inserts metadata into an RTMPS stream for the specified channel. A maximum of 5 requests per second per channel is allowed, each with a maximum 1KB payload. */ putMetadata(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Disconnects the incoming RTMPS stream for the specified channel. Can be used in conjunction with DeleteStreamKey to prevent further streaming to a channel. Many streaming client-software libraries automatically reconnect a dropped RTMPS session, so to stop the stream permanently, you may want to first revoke the streamKey attached to the channel. */ stopStream(params: IVS.Types.StopStreamRequest, callback?: (err: AWSError, data: IVS.Types.StopStreamResponse) => void): Request<IVS.Types.StopStreamResponse, AWSError>; /** * Disconnects the incoming RTMPS stream for the specified channel. Can be used in conjunction with DeleteStreamKey to prevent further streaming to a channel. Many streaming client-software libraries automatically reconnect a dropped RTMPS session, so to stop the stream permanently, you may want to first revoke the streamKey attached to the channel. */ stopStream(callback?: (err: AWSError, data: IVS.Types.StopStreamResponse) => void): Request<IVS.Types.StopStreamResponse, AWSError>; /** * Adds or updates tags for the AWS resource with the specified ARN. */ tagResource(params: IVS.Types.TagResourceRequest, callback?: (err: AWSError, data: IVS.Types.TagResourceResponse) => void): Request<IVS.Types.TagResourceResponse, AWSError>; /** * Adds or updates tags for the AWS resource with the specified ARN. */ tagResource(callback?: (err: AWSError, data: IVS.Types.TagResourceResponse) => void): Request<IVS.Types.TagResourceResponse, AWSError>; /** * Removes tags from the resource with the specified ARN. */ untagResource(params: IVS.Types.UntagResourceRequest, callback?: (err: AWSError, data: IVS.Types.UntagResourceResponse) => void): Request<IVS.Types.UntagResourceResponse, AWSError>; /** * Removes tags from the resource with the specified ARN. */ untagResource(callback?: (err: AWSError, data: IVS.Types.UntagResourceResponse) => void): Request<IVS.Types.UntagResourceResponse, AWSError>; /** * Updates a channel's configuration. This does not affect an ongoing stream of this channel. You must stop and restart the stream for the changes to take effect. */ updateChannel(params: IVS.Types.UpdateChannelRequest, callback?: (err: AWSError, data: IVS.Types.UpdateChannelResponse) => void): Request<IVS.Types.UpdateChannelResponse, AWSError>; /** * Updates a channel's configuration. This does not affect an ongoing stream of this channel. You must stop and restart the stream for the changes to take effect. */ updateChannel(callback?: (err: AWSError, data: IVS.Types.UpdateChannelResponse) => void): Request<IVS.Types.UpdateChannelResponse, AWSError>; } declare namespace IVS { export interface BatchError { /** * Channel ARN. */ arn?: ResourceArn; /** * Error code. */ code?: errorCode; /** * Error message, determined by the application. */ message?: errorMessage; } export type BatchErrors = BatchError[]; export interface BatchGetChannelRequest { /** * Array of ARNs, one per channel. */ arns: ChannelArnList; } export interface BatchGetChannelResponse { channels?: Channels; /** * Each error object is related to a specific ARN in the request. */ errors?: BatchErrors; } export interface BatchGetStreamKeyRequest { /** * Array of ARNs, one per channel. */ arns: StreamKeyArnList; } export interface BatchGetStreamKeyResponse { streamKeys?: StreamKeys; errors?: BatchErrors; } export type Boolean = boolean; export interface Channel { /** * Channel ARN. */ arn?: ChannelArn; /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Default: LOW. */ latencyMode?: ChannelLatencyMode; /** * Channel type, which determines the allowable resolution and bitrate. If you exceed the allowable resolution or bitrate, the stream probably will disconnect immediately. Valid values: STANDARD: Multiple qualities are generated from the original input, to automatically give viewers the best experience for their devices and network conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5 Mbps. BASIC: Amazon IVS delivers the original input to viewers. The viewer’s video-quality choice is limited to the original input. Vertical resolution can be up to 480 and bitrate can be up to 1.5 Mbps. Default: STANDARD. */ type?: ChannelType; /** * Channel ingest endpoint, part of the definition of an ingest server, used when you set up streaming software. */ ingestEndpoint?: IngestEndpoint; /** * Channel playback URL. */ playbackUrl?: PlaybackURL; /** * Whether the channel is authorized. */ authorized?: IsAuthorized; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type ChannelArn = string; export type ChannelArnList = ChannelArn[]; export type ChannelLatencyMode = "NORMAL"|"LOW"|string; export type ChannelList = ChannelSummary[]; export type ChannelName = string; export interface ChannelSummary { /** * Channel ARN. */ arn?: ChannelArn; /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Default: LOW. */ latencyMode?: ChannelLatencyMode; /** * Whether the channel is authorized. */ authorized?: IsAuthorized; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type ChannelType = "BASIC"|"STANDARD"|string; export type Channels = Channel[]; export interface CreateChannelRequest { /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Default: LOW. */ latencyMode?: ChannelLatencyMode; /** * Channel type, which determines the allowable resolution and bitrate. If you exceed the allowable resolution or bitrate, the stream probably will disconnect immediately. Valid values: STANDARD: Multiple qualities are generated from the original input, to automatically give viewers the best experience for their devices and network conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5 Mbps. BASIC: Amazon IVS delivers the original input to viewers. The viewer’s video-quality choice is limited to the original input. Vertical resolution can be up to 480 and bitrate can be up to 1.5 Mbps. Default: STANDARD. */ type?: ChannelType; /** * Whether the channel is authorized. Default: false. */ authorized?: Boolean; /** * See Channel$tags. */ tags?: Tags; } export interface CreateChannelResponse { channel?: Channel; streamKey?: StreamKey; } export interface CreateStreamKeyRequest { /** * ARN of the channel for which to create the stream key. */ channelArn: ChannelArn; /** * See Channel$tags. */ tags?: Tags; } export interface CreateStreamKeyResponse { /** * Stream key used to authenticate an RTMPS stream for ingestion. */ streamKey?: StreamKey; } export interface DeleteChannelRequest { /** * ARN of the channel to be deleted. */ arn: ChannelArn; } export interface DeletePlaybackKeyPairRequest { /** * ARN of the key pair to be deleted. */ arn: PlaybackKeyPairArn; } export interface DeletePlaybackKeyPairResponse { } export interface DeleteStreamKeyRequest { /** * ARN of the stream key to be deleted. */ arn: StreamKeyArn; } export interface GetChannelRequest { /** * ARN of the channel for which the configuration is to be retrieved. */ arn: ChannelArn; } export interface GetChannelResponse { channel?: Channel; } export interface GetPlaybackKeyPairRequest { /** * ARN of the key pair to be returned. */ arn: PlaybackKeyPairArn; } export interface GetPlaybackKeyPairResponse { keyPair?: PlaybackKeyPair; } export interface GetStreamKeyRequest { /** * ARN for the stream key to be retrieved. */ arn: StreamKeyArn; } export interface GetStreamKeyResponse { streamKey?: StreamKey; } export interface GetStreamRequest { /** * Channel ARN for stream to be accessed. */ channelArn: ChannelArn; } export interface GetStreamResponse { stream?: Stream; } export interface ImportPlaybackKeyPairRequest { /** * The public portion of a customer-generated key pair. */ publicKeyMaterial: PlaybackPublicKeyMaterial; /** * An arbitrary string (a nickname) assigned to a playback key pair that helps the customer identify that resource. The value does not need to be unique. */ name?: PlaybackKeyPairName; /** * Any tags provided with the request are added to the playback key pair tags. */ tags?: Tags; } export interface ImportPlaybackKeyPairResponse { keyPair?: PlaybackKeyPair; } export type IngestEndpoint = string; export type IsAuthorized = boolean; export interface ListChannelsRequest { /** * Filters the channel list to match the specified name. */ filterByName?: ChannelName; /** * The first channel to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of channels to return. */ maxResults?: MaxChannelResults; } export interface ListChannelsResponse { /** * List of the matching channels. */ channels: ChannelList; /** * If there are more channels than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListPlaybackKeyPairsRequest { /** * Maximum number of key pairs to return. */ nextToken?: PaginationToken; /** * The first key pair to retrieve. This is used for pagination; see the nextToken response field. */ maxResults?: MaxPlaybackKeyPairResults; } export interface ListPlaybackKeyPairsResponse { /** * List of key pairs. */ keyPairs: PlaybackKeyPairList; /** * If there are more key pairs than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListStreamKeysRequest { /** * Channel ARN used to filter the list. */ channelArn: ChannelArn; /** * The first stream key to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of streamKeys to return. */ maxResults?: MaxStreamKeyResults; } export interface ListStreamKeysResponse { /** * List of stream keys. */ streamKeys: StreamKeyList; /** * If there are more stream keys than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListStreamsRequest { /** * The first stream to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of streams to return. */ maxResults?: MaxStreamResults; } export interface ListStreamsResponse { /** * List of streams. */ streams: StreamList; /** * If there are more streams than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListTagsForResourceRequest { /** * The ARN of the resource to be retrieved. */ resourceArn: ResourceArn; /** * The first tag to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: String; /** * Maximum number of tags to return. */ maxResults?: MaxTagResults; } export interface ListTagsForResourceResponse { tags: Tags; /** * If there are more tags than maxResults, use nextToken in the request to get the next set. */ nextToken?: String; } export type MaxChannelResults = number; export type MaxPlaybackKeyPairResults = number; export type MaxStreamKeyResults = number; export type MaxStreamResults = number; export type MaxTagResults = number; export type PaginationToken = string; export interface PlaybackKeyPair { /** * Key-pair ARN. */ arn?: PlaybackKeyPairArn; /** * Key-pair name. */ name?: PlaybackKeyPairName; /** * Key-pair identifier. */ fingerprint?: PlaybackKeyPairFingerprint; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type PlaybackKeyPairArn = string; export type PlaybackKeyPairFingerprint = string; export type PlaybackKeyPairList = PlaybackKeyPairSummary[]; export type PlaybackKeyPairName = string; export interface PlaybackKeyPairSummary { /** * Key-pair ARN. */ arn?: PlaybackKeyPairArn; /** * Key-pair name. */ name?: PlaybackKeyPairName; /** * Array of 1-50 maps, each of the form string:string (key:value) */ tags?: Tags; } export type PlaybackPublicKeyMaterial = string; export type PlaybackURL = string; export interface PutMetadataRequest { /** * ARN of the channel into which metadata is inserted. This channel must have an active stream. */ channelArn: ChannelArn; /** * Metadata to insert into the stream. Maximum: 1 KB per request. */ metadata: StreamMetadata; } export type ResourceArn = string; export interface StopStreamRequest { /** * ARN of the channel for which the stream is to be stopped. */ channelArn: ChannelArn; } export interface StopStreamResponse { } export interface Stream { /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * URL of the video master manifest, required by the video player to play the HLS stream. */ playbackUrl?: PlaybackURL; /** * ISO-8601 formatted timestamp of the stream’s start. */ startTime?: StreamStartTime; /** * The stream’s state. */ state?: StreamState; /** * The stream’s health. */ health?: StreamHealth; /** * Number of current viewers of the stream. */ viewerCount?: StreamViewerCount; } export type StreamHealth = "HEALTHY"|"STARVING"|"UNKNOWN"|string; export interface StreamKey { /** * Stream-key ARN. */ arn?: StreamKeyArn; /** * Stream-key value. */ value?: StreamKeyValue; /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type StreamKeyArn = string; export type StreamKeyArnList = StreamKeyArn[]; export type StreamKeyList = StreamKeySummary[]; export interface StreamKeySummary { /** * Stream-key ARN. */ arn?: StreamKeyArn; /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type StreamKeyValue = string; export type StreamKeys = StreamKey[]; export type StreamList = StreamSummary[]; export type StreamMetadata = string; export type StreamStartTime = Date; export type StreamState = "LIVE"|"OFFLINE"|string; export interface StreamSummary { /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * The stream’s state. */ state?: StreamState; /** * The stream’s health. */ health?: StreamHealth; /** * Number of current viewers of the stream. */ viewerCount?: StreamViewerCount; /** * ISO-8601 formatted timestamp of the stream’s start. */ startTime?: StreamStartTime; } export type StreamViewerCount = number; export type String = string; export type TagKey = string; export type TagKeyList = TagKey[]; export interface TagResourceRequest { /** * ARN of the resource for which tags are to be added or updated. */ resourceArn: ResourceArn; /** * Array of tags to be added or updated. */ tags: Tags; } export interface TagResourceResponse { } export type TagValue = string; export type Tags = {[key: string]: TagValue}; export interface UntagResourceRequest { /** * ARN of the resource for which tags are to be removed. */ resourceArn: ResourceArn; /** * Array of tags to be removed. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateChannelRequest { /** * ARN of the channel to be updated. */ arn: ChannelArn; /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Default: LOW. */ latencyMode?: ChannelLatencyMode; /** * Channel type, which determines the allowable resolution and bitrate. If you exceed the allowable resolution or bitrate, the stream probably will disconnect immediately. Valid values: STANDARD: Multiple qualities are generated from the original input, to automatically give viewers the best experience for their devices and network conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5 Mbps. BASIC: Amazon IVS delivers the original input to viewers. The viewer’s video-quality choice is limited to the original input. Vertical resolution can be up to 480 and bitrate can be up to 1.5 Mbps. Default: STANDARD. */ type?: ChannelType; /** * Whether the channel is authorized. Default: false. */ authorized?: Boolean; } export interface UpdateChannelResponse { channel?: Channel; } export type errorCode = string; export type errorMessage = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-07-14"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the IVS client. */ export import Types = IVS; } export = IVS;
the_stack
import { Loki } from "../../src/loki"; import { LokiOperatorPackageMap, LokiOperatorPackage, ComparatorOperatorPackage, aeqHelper, ltHelper, gtHelper } from "../../src/operator_packages"; import { ILokiComparer } from "../../src/comparators"; describe("Testing operator packages feature", () => { beforeEach(() => { }); it("LokiOperatorPackage (js) works as expected", () => { expect(LokiOperatorPackageMap["js"].$eq(true, true)).toEqual(true); expect(LokiOperatorPackageMap["js"].$eq(true, false)).toEqual(false); expect(LokiOperatorPackageMap["js"].$eq(5, "5")).toEqual(false); expect(LokiOperatorPackageMap["js"].$eq(null, null)).toEqual(true); expect(LokiOperatorPackageMap["js"].$eq(null, undefined)).toEqual(false); expect(LokiOperatorPackageMap["js"].$eq(undefined, undefined)).toEqual(true); expect(LokiOperatorPackageMap["js"].$eq(new Date(2015), new Date(2015))).toEqual(false); expect(LokiOperatorPackageMap["js"].$ne(true, true)).toEqual(false); expect(LokiOperatorPackageMap["js"].$ne(true, false)).toEqual(true); expect(LokiOperatorPackageMap["js"].$in(4, [1, 3, 4])).toEqual(true); expect(LokiOperatorPackageMap["js"].$in(8, [1, 3, 4])).toEqual(false); expect(LokiOperatorPackageMap["js"].$nin(4, [1, 3, 4])).toEqual(false); expect(LokiOperatorPackageMap["js"].$nin(8, [1, 3, 4])).toEqual(true); expect(LokiOperatorPackageMap["js"].$gte(new Date(2015), new Date(2015))).toEqual(true); expect(LokiOperatorPackageMap["js"].$lt(5, 10)).toEqual(true); expect(LokiOperatorPackageMap["js"].$lt(10, 5)).toEqual(false); expect(LokiOperatorPackageMap["js"].$lte(5, 5)).toEqual(true); expect(LokiOperatorPackageMap["js"].$lte(10, 5)).toEqual(false); expect(LokiOperatorPackageMap["js"].$gte(new Date(2015), new Date(2015))).toEqual(true); expect(LokiOperatorPackageMap["js"].$gt(5, 10)).toEqual(false); expect(LokiOperatorPackageMap["js"].$gt(10, 5)).toEqual(true); expect(LokiOperatorPackageMap["js"].$gte(5, 5)).toEqual(true); expect(LokiOperatorPackageMap["js"].$gte(10, 5)).toEqual(true); expect(LokiOperatorPackageMap["js"].$len("abc", 3)).toEqual(true); expect(LokiOperatorPackageMap["js"].$len("abcd", 3)).toEqual(false); expect(LokiOperatorPackageMap["js"].$len(5, 1)).toEqual(false); expect(LokiOperatorPackageMap["js"].$where(3, function(a: any) { return a - 3 === 0; })).toEqual(true); expect(LokiOperatorPackageMap["js"].$where(4, function(a: any) { return a - 3 === 0; })).toEqual(false); expect(LokiOperatorPackageMap["js"].$between(5, [1, 10])).toEqual(true); expect(LokiOperatorPackageMap["js"].$between(null, [1, 10])).toEqual(false); }); it("LokiAbstractOperatorPackage works as expected", () => { expect(LokiOperatorPackageMap["loki"].$eq(5, "5")).toEqual(true); expect(LokiOperatorPackageMap["loki"].$eq(null, undefined)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gte(null, null)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt(undefined, undefined)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gte(undefined, undefined)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt(0, 0)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gte(0, 0)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt(new Date(2010), new Date(2015))).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gte(new Date(2015), new Date(2015))).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt("14", 12)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt(12, "14")).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gt("10", 12)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gt(12, "10")).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt("test", 12)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt(12, "test")).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gt(12, 0)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt(0, 12)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$gt(12, "")).toEqual(true); expect(LokiOperatorPackageMap["loki"].$gt("", 12)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt(false, false)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lte(false, false)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(true, false)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt(true, true)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lte(true, true)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(null, null)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lte(null, null)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(undefined, undefined)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lte(undefined, undefined)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(-1, 0)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(0, 0)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lte(0, 0)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(1, 0)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt(new Date(2010), new Date(2015))).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(new Date(2015), new Date(2015))).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lte(new Date(2015), new Date(2015))).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt("12", 14)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(14, "12")).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt("10", 12)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(12, "10")).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt("test", 12)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt(12, "test")).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(12, 0)).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt(0, 12)).toEqual(true); expect(LokiOperatorPackageMap["loki"].$lt(12, "")).toEqual(false); expect(LokiOperatorPackageMap["loki"].$lt("", 12)).toEqual(true); }); it ("user defined LokiOperatorPackage works as expected", () => { // simple inline class overriding some ops to work negatively class MyOperatorPackage extends LokiOperatorPackage { $gt(a: any, b: any): boolean { if (a < b) return true; return false; } $lt(a: any, b: any): boolean { if (a > b) return true; return false; } } // inject our new operator into global LokiOperatorPackageMap. // if it already exists, it will overwrite... this includes overriding native packages. let db = new Loki("test.db", { lokiOperatorPackageMap : { "MyOperatorPackage": new MyOperatorPackage() } }); interface IMyDoc { a: number; b: number; } // for this collection, we will specify to use that operator package for its find ops let coll = db.addCollection<IMyDoc>("coll", { defaultLokiOperatorPackage: "MyOperatorPackage" }); coll.insert([ { a: 8, b: 2 }, { a: 3, b: 7 }, { a: 12, b: 1 }, { a: 5, b: 11 }, { a: 6, b: 8 }, { a: 10, b: 6 }, { a: 20, b: 15 } ]); // our $lt op override actually means gt, so find all docs greater than 9 sort largest to least (desc) let results = coll.chain().find({ a: { $lt: 9 } }).simplesort("a", { desc: true }).data(); expect(results.length).toEqual(3); expect(results[0].a).toEqual(20); expect(results[1].a).toEqual(12); expect(results[2].a).toEqual(10); }); it ("ComparatorOperatorPackage works as expected", () => { let customComparator: ILokiComparer<any> = (a: any, b: any) => { if (typeof a === "string" && typeof b === "string") { a = a.toLocaleLowerCase(); b = b.toLocaleLowerCase(); } if (a === b) return 0; if (a > b) return 1; return -1; }; let myComparatorOperatorPackage = new ComparatorOperatorPackage<string>(customComparator); let db = new Loki("test.db", { lokiOperatorPackageMap: { "MyComparatorOperatorPackage": myComparatorOperatorPackage } }); interface IMyDoc { name: string; num: number; } let coll = db.addCollection<IMyDoc>("coll", { defaultLokiOperatorPackage: "MyComparatorOperatorPackage" }); coll.insert([ { name: "a", num: 1 }, { name: "B", num: 2 }, { name: "c", num: 3 }, { name: "D", num: 4 }, { name: "e", num: 5 }, { name: "F", num: 6 }, { name: "g", num: 7 }, { name: "h", num: 8 } ]); let results = coll.chain().find({ name : { $lte: "d" }}).simplesort("name").data(); expect(results.length).toEqual(4); // our filtering used our case insensitive comparator, but or sort did not... // we could have mapped comparator into comparator map and set unindexedComparatorMap to use it... // see another unit test for how to do that expect(results[0].name).toEqual("B"); expect(results[1].name).toEqual("D"); expect(results[2].name).toEqual("a"); expect(results[3].name).toEqual("c"); // just making sure our in-op rewrite of variable tolowercase did not affect document expect(coll.findOne({ name: "B"}).num).toEqual(2); }); it ("Comparator map + unindexSortComparator works as expected", () => { let customComparator: ILokiComparer<any> = (a: any, b: any) => { if (typeof a === "string" && typeof b === "string") { a = a.toLocaleLowerCase(); b = b.toLocaleLowerCase(); } if (a === b) return 0; if (a > b) return 1; return -1; }; let db = new Loki("test.db", { comparatorMap: { "MyCustomComparator": customComparator } }); interface IMyDoc { name: string; num: number; } let coll = db.addCollection<IMyDoc>("coll", { unindexedSortComparator: "MyCustomComparator" }); coll.insert([ { name: "g", num: 7 }, { name: "a", num: 1 }, { name: "e", num: 5 }, { name: "B", num: 2 }, { name: "D", num: 4 }, { name: "F", num: 6 }, { name: "h", num: 8 }, { name: "c", num: 3 } ]); let results = coll.chain().simplesort("name").data(); expect(results[0].name).toEqual("a"); expect(results[1].name).toEqual("B"); expect(results[2].name).toEqual("c"); expect(results[3].name).toEqual("D"); expect(results[4].name).toEqual("e"); expect(results[5].name).toEqual("F"); expect(results[6].name).toEqual("g"); expect(results[7].name).toEqual("h"); }); it ("aeqHelper works as expected", () => { expect(aeqHelper(1, "1")).toEqual(true); expect(aeqHelper(false, false)).toEqual(true); expect(aeqHelper(true, true)).toEqual(true); expect(aeqHelper(false, true)).toEqual(false); expect(aeqHelper(true, false)).toEqual(false); expect(aeqHelper("", "")).toEqual(true); expect(aeqHelper("", " ")).toEqual(false); expect(aeqHelper(" ", "")).toEqual(false); expect(aeqHelper(1, "1")).toEqual(true); expect(aeqHelper(1, "1")).toEqual(true); expect(aeqHelper(1.0, "1")).toEqual(true); expect(aeqHelper(null, undefined)).toEqual(true); expect(aeqHelper(1.0, "1")).toEqual(true); expect(aeqHelper(new Date("1/1/2018"), new Date("1/1/2018"))).toEqual(true); expect(aeqHelper("aaa", "AAA")).toEqual(false); }); it ("ltHelper works as expected", () => { expect(ltHelper("5", 5, true)).toEqual(true); expect(ltHelper("5", 5, false)).toEqual(false); expect(ltHelper("5", 6, false)).toEqual(true); expect(ltHelper(6, "7", false)).toEqual(true); expect(ltHelper(new Date("1/1/2018"), new Date("2/1/2018"), false)).toEqual(true); expect(ltHelper(new Date("2/1/2018"), new Date("1/1/2018"), false)).toEqual(false); expect(ltHelper({ a: 1 }, "7", false)).toEqual(false); }); it ("gtHelper works as expected", () => { expect(gtHelper("5", 5, true)).toEqual(true); expect(gtHelper("5", 5, false)).toEqual(false); expect(gtHelper("5", 6, true)).toEqual(false); expect(gtHelper("6", 5, true)).toEqual(true); expect(gtHelper(false, true, false)).toEqual(false); expect(gtHelper(true, false, false)).toEqual(true); }); });
the_stack
import { FeeType, Network } from '@xchainjs/xchain-client' import { Asset, AssetBNB, BNBChain, baseAmount } from '@xchainjs/xchain-util' import nock from 'nock' import { Client as BinanceClient } from '../src/client' import { Account, Fees, TransactionResult, TxPage } from '../src/types/binance' const mockGetAccount = (url: string, address: string, result: Account, ntimes = 1, status = 200) => { nock(url).get(`/api/v1/account/${address}`).times(ntimes).reply(status, result) } const mockGetFees = (url: string, result: Fees) => { nock(url).get('/api/v1/fees').reply(200, result) } // eslint-disable-next-line @typescript-eslint/no-explicit-any const mockThornodeGetFees = (url: string, result: any[]) => { nock(url).get('/thorchain/inbound_addresses').reply(200, result) } const mockTxHash = (url: string, hash: string, result: TransactionResult) => { nock(url).get(`/api/v1/tx/${hash}?format=json`).reply(200, result) } const mockSearchTransactions = (url: string, result: TxPage) => { nock(url) .get(`/api/v1/transactions`) .query((_) => true) .reply(200, result) } const mockNodeInfo = (url: string) => { nock(url) .get('/api/v1/node-info') .reply(200, { node_info: { network: 'Binance-Chain-Ganges', }, }) } const mockTxSend = (url: string) => { nock(url) .post('/api/v1/broadcast?sync=true') .reply(200, [ { code: 0, hash: '90F7F45652D05800EED577CBA805A6858C3867E08A07D627BECC0D6304E52A31', log: 'Msg 0: ', ok: true, }, ]) } describe('BinanceClient Test', () => { let bnbClient: BinanceClient // HDWallet: https://github.com/binance-chain/go-sdk/blob/8f0e838a5402c99cc08057a04eaece6dfd99181f/keys/hdpath.go#L20 // https://github.com/ebellocchia/bip_utils#complete-code-example // Note: This phrase is created by https://iancoleman.io/bip39/ and will never been used in a real-world const phrase = 'rural bright ball negative already grass good grant nation screen model pizza' const mainnetaddress_path0 = 'bnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9e738vr' const mainnetaddress_path1 = 'bnb1vjlcrl5d9t8sexzajsr57taqmxf6jpmgng3gmn' const testnetaddress_path0 = 'tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj' const testnetaddress_path1 = 'tbnb1vjlcrl5d9t8sexzajsr57taqmxf6jpmgaacvmz' const singleTxFee = baseAmount(37500) const transferFee = { type: 'base' as FeeType, average: singleTxFee, fast: singleTxFee, fastest: singleTxFee } const multiTxFee = baseAmount(30000) const multiSendFee = { type: 'base' as FeeType, average: multiTxFee, fast: multiTxFee, fastest: multiTxFee } const transferAmount = baseAmount(1000000) const phraseForTX = 'wheel leg dune emerge sudden badge rough shine convince poet doll kiwi sleep labor hello' const testnetaddress_path0ForTx = 'tbnb1t95kjgmjc045l2a728z02textadd98yt339jk7' const mainnetClientURL = 'https://dex.binance.org' const testnetClientURL = 'https://testnet-dex.binance.org' const thornodeMainetClientURL = 'https://thornode.thorchain.info' beforeEach(async () => { bnbClient = new BinanceClient({ phrase, network: 'mainnet' as Network }) }) afterEach(async () => { bnbClient.purgeClient() }) it('should start with empty wallet', async () => { const bnbClientEmptyMain = new BinanceClient({ phrase, network: 'mainnet' as Network }) const addressMain = bnbClientEmptyMain.getAddress() expect(addressMain).toEqual(mainnetaddress_path0) const bnbClientEmptyTest = new BinanceClient({ phrase, network: Network.Testnet }) const addressTest = bnbClientEmptyTest.getAddress() expect(addressTest).toEqual(testnetaddress_path0) }) it('should support derivation index as string', async () => { const bnbForTxClientEmptyMain = new BinanceClient({ phrase: phraseForTX, network: Network.Testnet }) const address_path0ForTx = bnbForTxClientEmptyMain.getAddress() expect(address_path0ForTx).toEqual(testnetaddress_path0ForTx) const bnbClientEmptyMain = new BinanceClient({ phrase, network: 'mainnet' as Network }) const addressMain = bnbClientEmptyMain.getAddress() expect(addressMain).toEqual(mainnetaddress_path0) const bnbClientEmptyMain_path1 = new BinanceClient({ phrase, network: 'mainnet' as Network }) expect(bnbClientEmptyMain_path1.getAddress(1)).toEqual(mainnetaddress_path1) const bnbClientEmptyTest = new BinanceClient({ phrase, network: Network.Testnet }) const addressTest = bnbClientEmptyTest.getAddress() expect(addressTest).toEqual(testnetaddress_path0) const bnbClientEmptyTest_path1 = new BinanceClient({ phrase, network: Network.Testnet }) expect(bnbClientEmptyTest_path1.getAddress(1)).toEqual(testnetaddress_path1) }) it('throws an error passing an invalid phrase', async () => { expect(() => { new BinanceClient({ phrase: 'invalid phrase', network: 'mainnet' as Network }) }).toThrow() }) it('should have right address', async () => { expect(bnbClient.getAddress()).toEqual(mainnetaddress_path0) expect(bnbClient.getAddress(1)).toEqual(mainnetaddress_path1) }) it('should update net', () => { const client = new BinanceClient({ phrase, network: 'mainnet' as Network }) client.setNetwork(Network.Testnet) expect(client.getNetwork()).toEqual('testnet') expect(client.getAddress()).toEqual(testnetaddress_path0) }) it('setPhrase should return address', () => { expect(bnbClient.setPhrase(phrase)).toEqual(mainnetaddress_path0) bnbClient.setNetwork(Network.Testnet) expect(bnbClient.setPhrase(phrase)).toEqual(testnetaddress_path0) }) it('should validate address', () => { expect(bnbClient.validateAddress(mainnetaddress_path0)).toBeTruthy() bnbClient.setNetwork(Network.Testnet) expect(bnbClient.validateAddress(testnetaddress_path0)).toBeTruthy() }) it('has no balances', async () => { mockGetAccount(mainnetClientURL, 'bnb1v8cprldc948y7mge4yjept48xfqpa46mmcrpku', { account_number: 0, address: 'bnb1v8cprldc948y7mge4yjept48xfqpa46mmcrpku', balances: [], public_key: [], flags: 0, sequence: 0, }) let balances = await bnbClient.getBalance('bnb1v8cprldc948y7mge4yjept48xfqpa46mmcrpku') expect(balances).toEqual([]) mockGetAccount( mainnetClientURL, 'bnb1ja07feunxx6z9kue3fn05dazt0gpn4y9e5t8rn', { account_number: 0, address: '', balances: [], public_key: [], flags: 0, sequence: 0, }, 1, 404, ) balances = await bnbClient.getBalance('bnb1ja07feunxx6z9kue3fn05dazt0gpn4y9e5t8rn') expect(balances).toEqual([]) }) it('has balances', async () => { bnbClient.setNetwork(Network.Testnet) mockGetAccount(testnetClientURL, 'tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj', { account_number: 29408, address: 'tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj', balances: [ { free: '12.89087500', frozen: '0.10000000', locked: '0.00000000', symbol: 'BNB', }, { free: '12.89087510', frozen: '0.10000000', locked: '0.00000000', symbol: 'RUNE', }, ], public_key: [], flags: 0, sequence: 5, }) const AssetRune: Asset = { chain: BNBChain, symbol: 'RUNE', ticker: 'RUNE' } const balances = await bnbClient.getBalance('tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj', [AssetBNB, AssetRune]) expect(balances.length).toEqual(2) let amount = balances[0].amount expect(amount.amount().isEqualTo(1289087500)).toBeTruthy() amount = balances[1].amount expect(amount.amount().isEqualTo(1289087510)).toBeTruthy() }) it('fetches account data', async () => { bnbClient.setNetwork(Network.Testnet) mockGetAccount(testnetClientURL, 'tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj', { account_number: 123, address: 'tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj', balances: [], public_key: [], flags: 0, sequence: 5, }) const { account_number, address, balances, flags, sequence } = await bnbClient.getAccount() expect(account_number).toEqual(123) expect(address).toEqual('tbnb1zd87q9dywg3nu7z38mxdcxpw8hssrfp9htcrvj') expect(balances.length).toEqual(0) expect(flags).toEqual(0) expect(sequence).toEqual(5) }) it('fetches the transfer fees', async () => { mockThornodeGetFees(thornodeMainetClientURL, [ { chain: 'BCH', pub_key: 'thorpub1addwnpepqgphxg4kqfwvcha2dr9m44r4k73cqm2yd74vumyvke78zjj80mzrwh4y6nw', address: 'qzr0swflj9fq26ktjhxh6q0kl9ddvxljlye66s7lvx', halted: false, gas_rate: '3', }, { chain: 'BNB', pub_key: 'thorpub1addwnpepqgphxg4kqfwvcha2dr9m44r4k73cqm2yd74vumyvke78zjj80mzrwh4y6nw', address: 'bnb1smurj0u32gzk4ju4e47srahetttphuhe64gyg4', halted: false, gas_rate: '37500', }, { chain: 'BTC', pub_key: 'thorpub1addwnpepqgphxg4kqfwvcha2dr9m44r4k73cqm2yd74vumyvke78zjj80mzrwh4y6nw', address: 'bc1qsmurj0u32gzk4ju4e47srahetttphuhewtfrdk', halted: false, gas_rate: '72', }, { chain: 'ETH', pub_key: 'thorpub1addwnpepqgphxg4kqfwvcha2dr9m44r4k73cqm2yd74vumyvke78zjj80mzrwh4y6nw', address: '0xbcd3fd5588369d84f4fefde45ccfdc3e74d5a805', router: '0x42A5Ed456650a09Dc10EBc6361A7480fDd61f27B', halted: false, gas_rate: '30', }, { chain: 'LTC', pub_key: 'thorpub1addwnpepqgphxg4kqfwvcha2dr9m44r4k73cqm2yd74vumyvke78zjj80mzrwh4y6nw', address: 'ltc1qsmurj0u32gzk4ju4e47srahetttphuhe2hn84x', halted: false, gas_rate: '75', }, ]) const fees = await bnbClient.getFees() expect(fees.type).toEqual(transferFee.type) expect(fees.average.amount().isEqualTo(singleTxFee.amount())).toBeTruthy() expect(fees.fast.amount().isEqualTo(singleTxFee.amount())).toBeTruthy() expect(fees.fastest.amount().isEqualTo(singleTxFee.amount())).toBeTruthy() }) it('fetches the multisend fees', async () => { mockGetFees(mainnetClientURL, [ { msg_type: 'tokensFreeze', fee: 500000, fee_for: 1, }, { fixed_fee_params: { msg_type: 'send', fee: 37500, fee_for: 1, }, multi_transfer_fee: 30000, lower_limit_as_multi: 2, }, ]) const fees = await bnbClient.getMultiSendFees() expect(fees.type).toEqual(multiSendFee.type) expect(fees.average.amount().isEqualTo(multiTxFee.amount())).toBeTruthy() expect(fees.fast.amount().isEqualTo(multiTxFee.amount())).toBeTruthy() expect(fees.fastest.amount().isEqualTo(multiTxFee.amount())).toBeTruthy() }) it('fetches single and multi fees', async () => { mockGetFees(mainnetClientURL, [ { msg_type: 'tokensFreeze', fee: 500000, fee_for: 1, }, { fixed_fee_params: { msg_type: 'send', fee: 37500, fee_for: 1, }, multi_transfer_fee: 30000, lower_limit_as_multi: 2, }, ]) const { single, multi } = await bnbClient.getSingleAndMultiFees() expect(single.type).toEqual(transferFee.type) expect(single.average.amount().isEqualTo(singleTxFee.amount())).toBeTruthy() expect(single.fast.amount().isEqualTo(singleTxFee.amount())).toBeTruthy() expect(single.fastest.amount().isEqualTo(singleTxFee.amount())).toBeTruthy() expect(multi.type).toEqual(multiSendFee.type) expect(multi.average.amount().isEqualTo(multiTxFee.amount())).toBeTruthy() expect(multi.fast.amount().isEqualTo(multiTxFee.amount())).toBeTruthy() expect(multi.fastest.amount().isEqualTo(multiTxFee.amount())).toBeTruthy() }) it('should broadcast a transfer', async () => { const client = new BinanceClient({ phrase: phraseForTX, network: Network.Testnet }) expect(client.getAddress()).toEqual(testnetaddress_path0ForTx) mockGetAccount( testnetClientURL, testnetaddress_path0ForTx, { account_number: 0, address: testnetaddress_path0ForTx, balances: [ { free: '1.00037500', frozen: '0.10000000', locked: '0.00000000', symbol: 'BNB', }, ], public_key: [], flags: 0, sequence: 0, }, 3, ) const beforeTransfer = await client.getBalance(client.getAddress(0)) expect(beforeTransfer.length).toEqual(1) mockNodeInfo(testnetClientURL) mockTxSend(testnetClientURL) const txHash = await client.transfer({ asset: AssetBNB, recipient: testnetaddress_path0ForTx, amount: transferAmount, }) expect(txHash).toEqual(expect.any(String)) mockGetAccount(testnetClientURL, testnetaddress_path0ForTx, { account_number: 0, address: testnetaddress_path0ForTx, balances: [ { free: '1.00000000', frozen: '0.10000000', locked: '0.00000000', symbol: 'BNB', }, ], public_key: [], flags: 0, sequence: 0, }) const afterTransfer = await client.getBalance(client.getAddress(0)) expect(afterTransfer.length).toEqual(1) const expected = beforeTransfer[0].amount .amount() .minus(transferFee.average.amount()) .isEqualTo(afterTransfer[0].amount.amount()) expect(expected).toBeTruthy() }) it('should broadcast a multi transfer', async () => { const client = new BinanceClient({ phrase: phraseForTX, network: Network.Testnet }) expect(client.getAddress()).toEqual(testnetaddress_path0ForTx) mockGetAccount( testnetClientURL, testnetaddress_path0ForTx, { account_number: 0, address: testnetaddress_path0ForTx, balances: [ { free: '1.00090000', frozen: '0.10000000', locked: '0.00000000', symbol: 'BNB', }, ], public_key: [], flags: 0, sequence: 0, }, 3, ) const beforeTransfer = await client.getBalance(client.getAddress(0)) expect(beforeTransfer.length).toEqual(1) const transactions = [ { to: testnetaddress_path0ForTx, coins: [ { asset: AssetBNB, amount: transferAmount, }, ], }, { to: testnetaddress_path0ForTx, coins: [ { asset: AssetBNB, amount: transferAmount, }, ], }, { to: testnetaddress_path0ForTx, coins: [ { asset: AssetBNB, amount: transferAmount, }, ], }, ] mockNodeInfo(testnetClientURL) mockTxSend(testnetClientURL) const txHash = await client.multiSend({ transactions }) expect(txHash).toEqual(expect.any(String)) mockGetAccount(testnetClientURL, testnetaddress_path0ForTx, { account_number: 0, address: testnetaddress_path0ForTx, balances: [ { free: '1.00000000', frozen: '0.10000000', locked: '0.00000000', symbol: 'BNB', }, ], public_key: [], flags: 0, sequence: 0, }) const afterTransfer = await client.getBalance(client.getAddress(0)) expect(afterTransfer.length).toEqual(1) const expected = beforeTransfer[0].amount .amount() .minus(multiSendFee.average.amount().multipliedBy(transactions.length)) .isEqualTo(afterTransfer[0].amount.amount()) expect(expected).toBeTruthy() }) it('has an empty tx history', async () => { const bnbClientEmptyMain = new BinanceClient({ phrase: 'nose link choose blossom social craft they better render provide escape talk', network: 'mainnet' as Network, }) mockSearchTransactions(mainnetClientURL, { total: 0, tx: [], }) const txArray = await bnbClientEmptyMain.getTransactions() expect(txArray).toEqual({ total: 0, txs: [] }) }) it('has tx history', async () => { bnbClient.setNetwork(Network.Testnet) mockSearchTransactions(testnetClientURL, { total: 1, tx: [ { txHash: 'A9E8E05603658BF3A295F04C856FE69E79EDA7375A307369F37411939BC321BB', blockHeight: 85905063, txType: 'TRANSFER', timeStamp: '2020-11-06T12:38:42.889Z', fromAddr: testnetaddress_path0ForTx, toAddr: 'bnb14qsnqxrjg68k5w6duq4fseap6fkg9m8fspz8f2', value: '1000', txAsset: 'BNB', txFee: '0.00000000', proposalId: null, txAge: 10, orderId: 'EB54F541FAA756D3666DC8C9B9931FAC1D19CAC3-192151', code: 0, data: '', confirmBlocks: 0, memo: '', source: 100, sequence: 192150, }, ], }) const txArray = await bnbClient.getTransactions({ address: testnetaddress_path0ForTx }) expect(txArray.total).toBeTruthy() expect(txArray.txs.length).toBeTruthy() }) it('get transaction data', async () => { mockTxHash(mainnetClientURL, 'A9E8E05603658BF3A295F04C856FE69E79EDA7375A307369F37411939BC321BB', { hash: 'A9E8E05603658BF3A295F04C856FE69E79EDA7375A307369F37411939BC321BB', log: 'Msg 0: ', height: '85905063', code: 0, tx: { type: 'auth/StdTx', value: { data: null, memo: 'SWAP:THOR.RUNE', msg: [ { type: 'cosmos-sdk/Send', value: { inputs: [ { address: 'bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m', coins: [ { amount: 107167590000000, denom: 'BNB', }, ], }, ], outputs: [ { address: 'bnb1fm4gqjxkrdfk8f23xjv6yfx3k7vhrdck8qp6a6', coins: [ { amount: 107167590000000, denom: 'BNB', }, ], }, ], }, }, ], signatures: [ { account_number: 496097, pub_key: Buffer.from(''), sequence: 0, signature: Buffer.from(''), }, ], source: 0, }, }, }) mockSearchTransactions(mainnetClientURL, { total: 0, tx: [ { txHash: 'A9E8E05603658BF3A295F04C856FE69E79EDA7375A307369F37411939BC321BB', blockHeight: 85905063, txType: 'TRANSFER', timeStamp: '2020-11-06T12:38:42.889Z', fromAddr: 'bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m', toAddr: 'bnb1fm4gqjxkrdfk8f23xjv6yfx3k7vhrdck8qp6a6', value: '1071675.9', txAsset: 'BNB', txFee: '0.00000000', proposalId: null, txAge: 10, orderId: 'EB54F541FAA756D3666DC8C9B9931FAC1D19CAC3-192151', code: 0, data: '', confirmBlocks: 0, memo: '', source: 100, sequence: 192150, }, ], }) const tx = await bnbClient.getTransactionData('A9E8E05603658BF3A295F04C856FE69E79EDA7375A307369F37411939BC321BB') expect(tx.hash).toEqual('A9E8E05603658BF3A295F04C856FE69E79EDA7375A307369F37411939BC321BB') expect(tx.from[0].from).toEqual('bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m') expect(tx.from[0].amount.amount().isEqualTo(baseAmount(107167590000000, 8).amount())).toBeTruthy() expect(tx.to[0].to).toEqual('bnb1fm4gqjxkrdfk8f23xjv6yfx3k7vhrdck8qp6a6') expect(tx.to[0].amount.amount().isEqualTo(baseAmount(107167590000000, 8).amount())).toBeTruthy() }) it('should return valid explorer url', () => { // Client created with network === 'mainnet' expect(bnbClient.getExplorerUrl()).toEqual('https://explorer.binance.org') bnbClient.setNetwork(Network.Testnet) expect(bnbClient.getExplorerUrl()).toEqual('https://testnet-explorer.binance.org') }) it('should retrun valid explorer address url', () => { expect(bnbClient.getExplorerAddressUrl('anotherTestAddressHere')).toEqual( 'https://explorer.binance.org/address/anotherTestAddressHere', ) bnbClient.setNetwork(Network.Testnet) expect(bnbClient.getExplorerAddressUrl('testAddressHere')).toEqual( 'https://testnet-explorer.binance.org/address/testAddressHere', ) }) it('should retrun valid explorer tx url', () => { expect(bnbClient.getExplorerTxUrl('anotherTestTxHere')).toEqual('https://explorer.binance.org/tx/anotherTestTxHere') bnbClient.setNetwork(Network.Testnet) expect(bnbClient.getExplorerTxUrl('testTxHere')).toEqual('https://testnet-explorer.binance.org/tx/testTxHere') }) })
the_stack
* @module Tools */ // cSpell: ignore popout import * as React from "react"; import { IModelApp, IModelConnection, Tool } from "@itwin/core-frontend"; import { UiItemsProvidersTest } from "@itwin/ui-items-providers-test"; import { IconSpecUtilities, ToolbarItemUtilities, } from "@itwin/appui-abstract"; import { LocalStateStorage } from "@itwin/core-react"; import { ChildWindowLocationProps, ContentDialog, ContentDialogManager, ContentGroup, ContentLayoutManager, ContentProps, FrontstageManager, StageContentLayout, StageContentLayoutProps, UiFramework, } from "@itwin/appui-react"; import toolIconSvg from "@bentley/icons-generic/icons/window-add.svg"; import tool2IconSvg from "@bentley/icons-generic/icons/window-maximize.svg"; import tool3IconSvg from "@bentley/icons-generic/icons/3d-render.svg"; import tool4IconSvg from "@bentley/icons-generic/icons/3d.svg"; import layoutRestoreIconSvg from "@bentley/icons-generic/icons/download.svg"; import removeLayoutIconSvg from "@bentley/icons-generic/icons/remove.svg"; import layoutSaveIconSvg from "@bentley/icons-generic/icons/upload.svg?sprite"; import { PopupTestPanel } from "./PopupTestPanel"; import { PopupTestView } from "./PopupTestView"; import { ComponentExamplesPage } from "../appui/frontstages/component-examples/ComponentExamples"; import { ComponentExamplesProvider } from "../appui/frontstages/component-examples/ComponentExamplesProvider"; import { ITwinUIExamplesProvider } from "../appui/frontstages/component-examples/ITwinUIExamplesProvider"; export class TestExtensionUiProviderTool extends Tool { public static testExtensionLoaded = ""; public static override toolId = "TestExtensionUiProvider"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public static override get keyin(): string { return "load test provider"; } public static override get englishKeyin(): string { return this.keyin; } public override async run(_args: any[]): Promise<boolean> { await UiItemsProvidersTest.initialize(); return true; } } function getIModelSpecificKey(inKey: string, iModelConnection: IModelConnection | undefined) { const imodelId = iModelConnection?.iModelId ?? "unknownImodel"; return `[${imodelId}]${inKey}`; } export async function hasSavedViewLayoutProps(activeFrontstageId: string, iModelConnection: IModelConnection | undefined) { const localSettings = new LocalStateStorage(); return localSettings.hasSetting("ContentGroupLayout", getIModelSpecificKey(activeFrontstageId, iModelConnection)); } export async function getSavedViewLayoutProps(activeFrontstageId: string, iModelConnection: IModelConnection | undefined) { const localSettings = new LocalStateStorage(); const result = await localSettings.getSetting("ContentGroupLayout", getIModelSpecificKey(activeFrontstageId, iModelConnection)); if (result.setting) { // Parse StageContentLayoutProps const savedViewLayoutProps: StageContentLayoutProps = result.setting; if (iModelConnection) { // Create ViewStates const viewStates = await StageContentLayout.viewStatesFromProps(iModelConnection, savedViewLayoutProps); if (0 === viewStates.length) return undefined; // Add applicationData to the ContentProps savedViewLayoutProps.contentGroupProps.contents.forEach((contentProps: ContentProps, index: number) => { contentProps.applicationData = { viewState: viewStates[index], iModelConnection }; }); } return savedViewLayoutProps; } return undefined; } export class SaveContentLayoutTool extends Tool { public static override toolId = "SaveContentLayoutTool"; public static override iconSpec = IconSpecUtilities.createSvgIconSpec(layoutSaveIconSvg); public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public static override get keyin(): string { return "content layout save"; } public static override get englishKeyin(): string { return this.keyin; } public override async run(): Promise<boolean> { if (FrontstageManager.activeFrontstageDef && ContentLayoutManager.activeLayout && ContentLayoutManager.activeContentGroup) { const localSettings = new LocalStateStorage(); // Create props for the Layout, ContentGroup and ViewStates const savedViewLayoutProps = StageContentLayout.viewLayoutToProps(ContentLayoutManager.activeLayout, ContentLayoutManager.activeContentGroup, true, (contentProps: ContentProps) => { if (contentProps.applicationData) { if (contentProps.applicationData.iModelConnection) delete contentProps.applicationData.iModelConnection; if (contentProps.applicationData.viewState) delete contentProps.applicationData.viewState; } }); if (savedViewLayoutProps.contentLayoutProps) delete savedViewLayoutProps.contentLayoutProps; if (FrontstageManager.activeFrontstageDef.contentGroupProvider) savedViewLayoutProps.contentGroupProps = FrontstageManager.activeFrontstageDef.contentGroupProvider.prepareToSaveProps(savedViewLayoutProps.contentGroupProps); await localSettings.saveSetting("ContentGroupLayout", getIModelSpecificKey(FrontstageManager.activeFrontstageDef.id, UiFramework.getIModelConnection()), savedViewLayoutProps); } return true; } } export class RestoreSavedContentLayoutTool extends Tool { public static override toolId = "RestoreSavedContentLayoutTool"; public static override iconSpec = IconSpecUtilities.createWebComponentIconSpec(layoutRestoreIconSvg); public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public static override get keyin(): string { return "content layout restore"; } public static override get englishKeyin(): string { return this.keyin; } public override async run(): Promise<boolean> { if (FrontstageManager.activeFrontstageDef) { const savedViewLayoutProps = await getSavedViewLayoutProps(FrontstageManager.activeFrontstageDef.id, UiFramework.getIModelConnection()); if (savedViewLayoutProps) { let contentGroupProps = savedViewLayoutProps.contentGroupProps; if (FrontstageManager.activeFrontstageDef.contentGroupProvider) contentGroupProps = FrontstageManager.activeFrontstageDef.contentGroupProvider.applyUpdatesToSavedProps(savedViewLayoutProps.contentGroupProps); const contentGroup = new ContentGroup(contentGroupProps); // activate the layout await ContentLayoutManager.setActiveContentGroup(contentGroup); // emphasize the elements StageContentLayout.emphasizeElementsFromProps(contentGroup, savedViewLayoutProps); } } return true; } } export class RemoveSavedContentLayoutTool extends Tool { public static override toolId = "RemoveSavedContentLayoutTool"; public static override iconSpec = IconSpecUtilities.createWebComponentIconSpec(removeLayoutIconSvg); public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public static override get keyin(): string { return "content layout remove"; } public static override get englishKeyin(): string { return this.keyin; } public override async run(): Promise<boolean> { if (FrontstageManager.activeFrontstageDef) { const localSettings = new LocalStateStorage(); await localSettings.deleteSetting("ContentGroupLayout", getIModelSpecificKey(FrontstageManager.activeFrontstageDef.id, UiFramework.getIModelConnection())); } return true; } } export class OpenComponentExamplesPopoutTool extends Tool { public static override toolId = "openComponentExamplesChildWindow"; public static override iconSpec = "@bentley/icons-generic/icons/window-add.svg"; public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public override async run(): Promise<boolean> { await this._run(); return true; } private async _run(): Promise<void> { const location: ChildWindowLocationProps = { width: 800, height: 600, left: 0, top: 0, }; const connection = UiFramework.getIModelConnection(); if (connection) UiFramework.childWindowManager.openChildWindow("ComponentExamples", "Component Examples", <ComponentExamplesPage categories={[...ComponentExamplesProvider.categories, ...ITwinUIExamplesProvider.categories]} hideThemeOption />, location, UiFramework.useDefaultPopoutUrl); } public static override get flyover(): string { return "open examples popout"; } // if supporting localized key-ins return a localized string public static override get keyin(): string { return "open examples popout"; } public static override get englishKeyin(): string { return "open examples popout"; } public static getActionButtonDef(itemPriority: number, groupPriority?: number) { const overrides = { groupPriority, }; const iconSpec = IconSpecUtilities.createWebComponentIconSpec(toolIconSvg); return ToolbarItemUtilities.createActionButton(OpenComponentExamplesPopoutTool.toolId, itemPriority, iconSpec, OpenComponentExamplesPopoutTool.flyover, async () => { await IModelApp.tools.run(OpenComponentExamplesPopoutTool.toolId); }, overrides); } } export class OpenCustomPopoutTool extends Tool { public static override toolId = "OpenCustomPopout"; public static override iconSpec = IconSpecUtilities.createWebComponentIconSpec(tool2IconSvg); public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public override async run(): Promise<boolean> { await this._run(); return true; } private async _run(): Promise<void> { const location: ChildWindowLocationProps = { width: 800, height: 600, left: 0, top: 0, }; UiFramework.childWindowManager.openChildWindow("CustomPopout", "Custom Popout", <PopupTestPanel />, location /* , UiFramework.useDefaultPopoutUrl*/); } public static override get flyover(): string { return "open custom popout"; } // if supporting localized key-ins return a localized string public static override get keyin(): string { return "open custom popout"; } public static override get englishKeyin(): string { return "open custom popout"; } public static getActionButtonDef(itemPriority: number, groupPriority?: number) { const overrides = { groupPriority, }; return ToolbarItemUtilities.createActionButton(OpenCustomPopoutTool.toolId, itemPriority, OpenCustomPopoutTool.iconSpec, OpenCustomPopoutTool.flyover, async () => { await IModelApp.tools.run(OpenCustomPopoutTool.toolId); }, overrides); } } export class OpenViewPopoutTool extends Tool { public static override toolId = "OpenViewPopout"; public static override iconSpec = IconSpecUtilities.createWebComponentIconSpec(tool3IconSvg); public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public override async run(): Promise<boolean> { await this._run(); return true; } private async _run(): Promise<void> { const location: ChildWindowLocationProps = { width: 800, height: 600, left: 0, top: 0, }; UiFramework.childWindowManager.openChildWindow("ViewPopout", "View Popout", <PopupTestView contentId="ui-test-app:popout-test" showViewPicker />, location); } public static override get flyover(): string { return "open view popout"; } // if supporting localized key-ins return a localized string public static override get keyin(): string { return "open view popout"; } public static override get englishKeyin(): string { return "open view popout"; } public static getActionButtonDef(itemPriority: number, groupPriority?: number) { const overrides = { groupPriority, }; return ToolbarItemUtilities.createActionButton(OpenViewPopoutTool.toolId, itemPriority, OpenViewPopoutTool.iconSpec, OpenViewPopoutTool.flyover, async () => { await IModelApp.tools.run(OpenViewPopoutTool.toolId); }, overrides); } } // cSpell:ignore appui appuiprovider // eslint-disable-next-line @typescript-eslint/naming-convention export function IModelViewDialog({ x, y, id, title }: { x?: number, y?: number, id: string, title: string }) { const handleClose = React.useCallback(() => { ContentDialogManager.closeDialog(id); }, [id]); return ( <ContentDialog title={title} inset={false} opened={true} onClose={handleClose} onEscape={handleClose} width={"40vw"} height={"40vh"} dialogId={id} x={x} y={y} > <PopupTestView contentId={id} /> </ContentDialog> ); } export class OpenViewDialogTool extends Tool { private static _counter = 0; public static override toolId = "OpenViewDialog"; public static override iconSpec = IconSpecUtilities.createWebComponentIconSpec(tool4IconSvg); public static get dialogId(): string { return `ui-test-app:popup-view-dialog-${OpenViewDialogTool._counter}`; } public static override get minArgs() { return 0; } public static override get maxArgs() { return 0; } public override async run(): Promise<boolean> { await this._run(); return true; } private async _run(): Promise<void> { OpenViewDialogTool._counter = OpenViewDialogTool._counter + 1; let x: number | undefined; let y: number | undefined; const stage = FrontstageManager.activeFrontstageDef; if (stage && stage.nineZoneState) { const floatingContentCount = stage.floatingContentControls?.length ?? 0; // we should not really every support more than 8 floating views if (floatingContentCount < 8 && stage.nineZoneState.size.width > 800 && stage.nineZoneState.size.height > 600) { x = (.3 * stage.nineZoneState.size.width) + (40 * (floatingContentCount - 1)); y = (.3 * stage.nineZoneState.size.height) + (40 * (floatingContentCount - 1)); } } ContentDialogManager.openDialog(<IModelViewDialog x={x} y={y} id={OpenViewDialogTool.dialogId} title={`IModel View (${OpenViewDialogTool._counter})`} />, OpenViewDialogTool.dialogId); } public static override get flyover(): string { return "open view dialog"; } // if supporting localized key-ins return a localized string public static override get keyin(): string { return "open view dialog"; } public static override get englishKeyin(): string { return "open view dialog"; } public static getActionButtonDef(itemPriority: number, groupPriority?: number) { const overrides = { groupPriority, }; return ToolbarItemUtilities.createActionButton(OpenViewDialogTool.toolId, itemPriority, OpenViewDialogTool.iconSpec, OpenViewDialogTool.flyover, async () => { await IModelApp.tools.run(OpenViewDialogTool.toolId); }, overrides); } }
the_stack
import React, { Component } from 'react' import { connect } from 'redaction' import actions from 'redux/actions' import erc20Like from 'common/erc20Like' import helpers, { constants } from 'helpers' import swapsHelper from 'helpers/swaps' import Link from 'local_modules/sw-valuelink' import config from 'app-config' import { BigNumber } from 'bignumber.js' import styles from './AddOffer.scss' import cssModules from 'react-css-modules' import Select from './Select/Select' import ExchangeRateGroup from './ExchangeRateGroup/ExchangeRateGroup' import SelectGroup from 'components/SelectGroup' import Button from 'components/controls/Button/Button' import Toggle from 'components/controls/Toggle/Toggle' import Tooltip from 'components/ui/Tooltip/Tooltip' import { FormattedMessage } from 'react-intl' import COINS_WITH_DYNAMIC_FEE from 'common/helpers/constants/COINS_WITH_DYNAMIC_FEE' import TurboIcon from 'shared/components/ui/TurboIcon/TurboIcon' import MIN_AMOUNT_OFFER from 'common/helpers/constants/MIN_AMOUNT' import turboSwap from 'common/helpers/turboSwap' import getCoinInfo from 'common/coins/getCoinInfo' const mathConstants = { high_precision: 10e-8, low_precision: 10e-5, } const isNumberStringFormatCorrect = number => { const stringified = String(number) const firstDotIndex = stringified.indexOf('.') const lastDotIndex = stringified.lastIndexOf('.') // first and last dot positions match, so it has only one dot return firstDotIndex === lastDotIndex } @connect( ({ currencies, }) => ({ currencies: swapsHelper.isExchangeAllowed(currencies.partialItems), addSelectedItems: swapsHelper.isExchangeAllowed(currencies.addPartialItems), currenciesOrig: currencies, }) ) @cssModules(styles, { allowMultiple: true }) export default class AddOffer extends Component<any, any> { isSending: any constructor(props) { super(props) const { initialData } = props if (config?.isWidget) { if (window?.widgetEvmLikeTokens?.length) { window.widgetEvmLikeTokens.forEach((token) => { MIN_AMOUNT_OFFER[token.name.toLowerCase()] = 1 }) } else { MIN_AMOUNT_OFFER[config.erc20token] = 1 } } const { exchangeRate, buyAmount, sellAmount, buyCurrency, sellCurrency } = initialData || {} this.state = { balance: null, isTokenSell: false, isTokenBuy: false, isPartial: true, isTurbo: false, isSending: false, manualRate: true, buyAmount: buyAmount || '', sellAmount: sellAmount || '', exchangeRate: exchangeRate || 1, buyCurrency: buyCurrency || 'btc', sellCurrency: sellCurrency || 'eth', buyBlockchain: ``, sellBlockchain: ``, minimalestAmountForBuy: MIN_AMOUNT_OFFER[buyCurrency] || MIN_AMOUNT_OFFER.btc, minimalestAmountForSell: MIN_AMOUNT_OFFER[sellCurrency] || MIN_AMOUNT_OFFER.eth, tokenBaseCurrencyBalance: 0, // @to-do buy and sell for support token-token orders balanceForBuyTokenFee: 0, balanceForSellTokenFee: 0, } } componentDidMount() { const { sellCurrency, buyCurrency } = this.state actions.pairs.selectPairPartial(sellCurrency) this.checkBalance(sellCurrency) this.updateExchangeRate(sellCurrency, buyCurrency) this.isTokenOffer(sellCurrency, buyCurrency) this.getFee() this.checkBalanceForTokenFee() const { coin: sellName, blockchain: sellBlockchain, } = getCoinInfo(sellCurrency) const { coin: buyName, blockchain: buyBlockchain, } = getCoinInfo(buyCurrency) if (sellBlockchain) { this.setState(() => ({ sellBlockchain })) this.updateTokenBaseWalletBalance(sellBlockchain) } if (buyBlockchain) { this.setState(() => ({ buyBlockchain })) this.updateTokenBaseWalletBalance(buyBlockchain) } } updateTokenBaseWalletBalance = async (baseCurrency) => { const tokenBaseCurrencyBalance = await actions[baseCurrency.toLowerCase()].getBalance() this.setState(() => ({ tokenBaseCurrencyBalance, })) } getFee = () => { const { sellCurrency, buyCurrency } = this.state this.correctMinAmountSell(sellCurrency) this.correctMinAmountBuy(buyCurrency) } checkBalanceForTokenFee = async () => { const { sellBlockchain, buyBlockchain, } = this.state const balanceForBuyTokenFee = (buyBlockchain !== ``) ? await actions[buyBlockchain.toLowerCase()].getBalance() : 0 const balanceForSellTokenFee = (sellBlockchain !== ``) ? await actions[sellBlockchain.toLowerCase()].getBalance() : 0 this.setState(() => ({ balanceForBuyTokenFee, balanceForSellTokenFee, })) } checkBalance = async (sellCurrency) => { const sellWallet = actions.core.getWallet({ currency: sellCurrency }) let balance = new BigNumber( await actions.core.fetchWalletBalance(sellWallet) ) let { unconfirmedBalance } = sellWallet unconfirmedBalance = new BigNumber(unconfirmedBalance) const currentBalance = unconfirmedBalance.isNaN() && unconfirmedBalance.isLessThan(0) ? balance.plus(unconfirmedBalance) : balance const balanceWithoutFee = !erc20Like.isToken({ name: sellCurrency }) ? currentBalance : currentBalance.minus(this.state.minimalestAmountForSell) const finalBalance = balanceWithoutFee.isGreaterThan(0) ? balanceWithoutFee : new BigNumber(0) this.setState({ balance: finalBalance.toString(), }) } isTokenOffer = (sellCurrency, buyCurrency) => { const isTokenSell = erc20Like.isToken({ name: sellCurrency }) const isTokenBuy = erc20Like.isToken({ name: buyCurrency }) this.setState(() => ({ isTokenBuy, isTokenSell, })) } correctMinAmountSell = async (sellCurrency) => { const isToken = erc20Like.isToken({ name: sellCurrency }) if (COINS_WITH_DYNAMIC_FEE.includes(sellCurrency) && !isToken) { const minimalestAmountForSell = await helpers[sellCurrency].estimateFeeValue({ method: 'swap', speed: 'fast' }) this.setState({ minimalestAmountForSell, }) } } correctMinAmountBuy = async (buyCurrency) => { const isToken = erc20Like.isToken({ name: buyCurrency }) if (COINS_WITH_DYNAMIC_FEE.includes(buyCurrency) && !isToken) { const minimalestAmountForBuy = await helpers[buyCurrency].estimateFeeValue({ method: 'swap', speed: 'fast' }) this.setState({ minimalestAmountForBuy, }) } } updateExchangeRate = async (sellCurrency, buyCurrency) => { const exchangeRateSell: any = await actions.user.getExchangeRate(sellCurrency, 'usd') const exchangeRateBuy: any = await actions.user.getExchangeRate(buyCurrency, 'usd') const exchangeRate = sellCurrency === 'swap' || buyCurrency === 'swap' ? await actions.user.getExchangeRate(sellCurrency, buyCurrency) : new BigNumber(exchangeRateSell).div(exchangeRateBuy).dp(4, BigNumber.ROUND_CEIL) return new Promise((resolve, reject) => { this.setState({ exchangeRate }, () => resolve(true)) }) } handleBuyCurrencySelect = async (selectedItem) => { const { value, blockchain } = selectedItem const { sellCurrency, buyAmount, sellAmount } = this.state this.setState({ isTurbo: false, }) if (sellCurrency === value) { this.switching() } else { this.checkPair(sellCurrency) await this.checkBalance(sellCurrency) await this.updateExchangeRate(sellCurrency, value) this.isTokenOffer(sellCurrency, value) this.setState(() => ({ buyCurrency: value, buyBlockchain: blockchain, }), () => { const { isTokenBuy } = this.state if (isTokenBuy) { this.checkBalanceForTokenFee() this.updateTokenBaseWalletBalance(blockchain) } }) if (sellAmount > 0 || buyAmount > 0) { this.handleBuyAmountChange(buyAmount) this.handleSellAmountChange(sellAmount) } this.getFee() } } handleSellCurrencySelect = async (selectedItem) => { const { value, blockchain } = selectedItem const { buyCurrency, sellCurrency, sellAmount, buyAmount } = this.state this.setState({ isTurbo: false, }) if (buyCurrency === value) { this.switching() } else { this.checkPair(value) await this.checkBalance(value) await this.updateExchangeRate(value, buyCurrency) this.isTokenOffer(value, buyCurrency) this.setState(() => ({ sellCurrency: value, sellBlockchain: blockchain, }), () => { const { isTokenSell } = this.state if (isTokenSell) { this.checkBalanceForTokenFee() this.updateTokenBaseWalletBalance(blockchain) } }) if (sellAmount > 0 || buyAmount > 0) { this.handleBuyAmountChange(buyAmount) this.handleSellAmountChange(sellAmount) } this.getFee() } } handleExchangeRateChange = (value) => { if (!isNumberStringFormatCorrect(value)) { return undefined } this.handleAnyChange({ type: 'rate', value, }) return value } handleBuyAmountChange = (value) => { if (!isNumberStringFormatCorrect(value)) { return undefined } this.handleAnyChange({ type: 'buy', value, }) return value } handleSellAmountChange = (value) => { if (!isNumberStringFormatCorrect(value)) { return undefined } this.handleAnyChange({ type: 'sell', value, }) return value } handleAnyChange = ({ type, value }) => { const { manualRate, exchangeRate, buyAmount, sellAmount, buyCurrency, sellCurrency } = this.state if (type === 'sell' || type === 'buy') { if (!this.isSending) { this.setState({ isSending: true }) } } /* XR = S / B B = S / XR S = XR * B */ switch (type) { case 'sell': { /* S++ -> XR++ -> B (Manual Rate) S++ -> XR -> B++ (Auto Rate) */ const newSellAmount = new BigNumber(value || 0) if (manualRate) { const newExchangeRate = new BigNumber(value).dividedBy(buyAmount) this.setState({ exchangeRate: newExchangeRate.isGreaterThan(0) ? newExchangeRate.toString() : '', sellAmount: newSellAmount.toString(), }) } else { const newBuyAmount = newSellAmount.multipliedBy(exchangeRate || 0) .dp(constants.tokenDecimals[buyCurrency.toLowerCase()], BigNumber.ROUND_DOWN) this.setState({ sellAmount: newSellAmount.toString(), buyAmount: newBuyAmount.toString(), }) } break } case 'buy': { /* B++ -> XR-- -> S (Manual Rate) B++ -> XR -> S++ (Auto Rate) */ const newBuyAmount = new BigNumber(value || 0) if (manualRate) { const newExchangeRate = new BigNumber(sellAmount).dividedBy(value) this.setState({ exchangeRate: newExchangeRate.isGreaterThan(0) ? newExchangeRate.toString() : '', buyAmount: newBuyAmount.toString(), }) } else { const newSellAmount = newBuyAmount.dividedBy(exchangeRate || 0) .dp(constants.tokenDecimals[sellCurrency.toLowerCase()], BigNumber.ROUND_DOWN) this.setState({ sellAmount: newSellAmount.toString(), buyAmount: newBuyAmount.toString(), }) } break } case 'rate': { if (new BigNumber(sellAmount).isGreaterThan(mathConstants.high_precision)) { // If user has set sell value change buy value /* XR++ -> S -> B-- */ const newBuyAmount = new BigNumber(sellAmount).dividedBy(value || 0) this.setState({ buyAmount: newBuyAmount.toString(), }) } else { // Otherwise change sell value if buy value is not null /* XR++ -> S++ -> B */ const newSellAmount = new BigNumber(value || 0).multipliedBy(buyAmount) this.setState({ sellAmount: newSellAmount.toString(), }) } break } default: console.error('Unknown type') break } } handleNext = () => { const { onNext } = this.props onNext(this.state) } changeBalance = (value) => { this.setState(() => ({ sellAmount: new BigNumber(value).toString(), })) this.handleSellAmountChange(value) } handleManualRate = (value) => { if (!value) { const { sellCurrency } = this.state this.handleSellCurrencySelect({ value: sellCurrency }) } this.setState(() => ({ manualRate: value })) } switching = async () => { const { sellCurrency, buyCurrency, balanceForSellTokenFee, balanceForBuyTokenFee, buyBlockchain, sellBlockchain, } = this.state this.setState(() => ({ sellCurrency: buyCurrency, sellBlockchain: buyBlockchain, sellAmount: '', balanceForSellTokenFee: balanceForBuyTokenFee, // ---- buyCurrency: sellCurrency, buyBlockchain: sellBlockchain, buyAmount: '', balanceForBuyTokenFee: balanceForSellTokenFee, }), async () => { await this.checkBalance(buyCurrency) await this.updateExchangeRate(buyCurrency, sellCurrency) actions.pairs.selectPairPartial(buyCurrency) this.isTokenOffer(this.state.sellCurrency, this.state.buyCurrency) this.getFee() }) } checkPair = (value) => { const selected = actions.pairs.selectPairPartial(value) const check = selected.map(item => item.value).includes(this.state.buyCurrency) if (!check) { this.setState(() => ({ buyCurrency: selected[0].value, })) } } render() { const { currencies, addSelectedItems } = this.props const { exchangeRate, buyAmount, sellAmount, buyCurrency, sellCurrency, minimalestAmountForSell, minimalestAmountForBuy, balance, tokenBaseCurrencyBalance, manualRate, isPartial, isTurbo, isTokenSell, isTokenBuy, } = this.state // @to-do - fetch eth miner fee for swap const minAmountForSwap = 0.004 const needEthBalance = (new BigNumber(tokenBaseCurrencyBalance).isLessThan(minAmountForSwap) && (isTokenBuy || isTokenSell)) const linked = Link.all(this, 'exchangeRate', 'buyAmount', 'sellAmount') const minimalAmountSell = !isTokenSell ? COINS_WITH_DYNAMIC_FEE.includes(sellCurrency) ? minimalestAmountForSell : MIN_AMOUNT_OFFER[buyCurrency] : 0.001 const minimalAmountBuy = !isTokenBuy ? COINS_WITH_DYNAMIC_FEE.includes(buyCurrency) ? minimalestAmountForBuy : MIN_AMOUNT_OFFER[buyCurrency] : 0.001 // temporary: hide turboswaps on mainnet const isShowSwapModeSwitch = !process.env.MAINNET const isTurboAllowed = turboSwap.isAssetSupported(buyCurrency) && turboSwap.isAssetSupported(sellCurrency) const isDisabled = !exchangeRate || !buyAmount && !sellAmount || new BigNumber(sellAmount).isGreaterThan(balance) || new BigNumber(sellAmount).isLessThan(minimalAmountSell) || new BigNumber(buyAmount).isLessThan(minimalAmountBuy) || needEthBalance if (linked.sellAmount.value !== '' && linked.sellAmount.value > 0) { linked.sellAmount.check((value) => (new BigNumber(value).isGreaterThan(minimalAmountSell)), <span> <FormattedMessage id="transaction444" defaultMessage="Sell amount must be greater than " /> {' '} {minimalAmountSell} </span> ) } if (linked.buyAmount.value !== '' && linked.buyAmount.value > 0) { linked.buyAmount.check((value) => (new BigNumber(value).isGreaterThan(minimalAmountBuy)), <span> <FormattedMessage id="transaction450" defaultMessage="Buy amount must be greater than " /> {' '} {minimalAmountBuy} </span> ) } return ( <div styleName={`wrapper addOffer`}> <div styleName="offerTitle"> <FormattedMessage id="offerMessageToUser" defaultMessage="You must be online all the time, otherwise your order will not be visible to other users" /> </div> <SelectGroup label={<FormattedMessage id="addoffer381" defaultMessage="Sell" />} tooltip={<FormattedMessage id="partial462" defaultMessage="The amount you have on swap.online or an external wallet that you want to exchange" />} inputValueLink={linked.sellAmount.pipe(this.handleSellAmountChange)} dontDisplayError selectedValue={sellCurrency} onSelect={this.handleSellCurrencySelect} id="sellAmount" balance={balance} currencies={currencies} placeholder="0.00000000" /> <Select changeBalance={this.changeBalance} balance={balance} switching={this.switching} /> <SelectGroup label={<FormattedMessage id="addoffer396" defaultMessage="Buy" />} tooltip={<FormattedMessage id="partial478" defaultMessage="The amount you will receive after the exchange" />} inputValueLink={linked.buyAmount.pipe(this.handleBuyAmountChange)} dontDisplayError selectedValue={buyCurrency} onSelect={this.handleBuyCurrencySelect} id="buyAmount" currencies={addSelectedItems} placeholder="0.00000000" /> <div styleName="exchangeRate"> <ExchangeRateGroup label={<FormattedMessage id="addoffer406" defaultMessage="Exchange rate" />} inputValueLink={linked.exchangeRate.pipe(this.handleExchangeRateChange)} disabled={!manualRate} id="exchangeRate" placeholder="Enter exchange rate amount" buyCurrency={buyCurrency} sellCurrency={sellCurrency} /> </div> <div styleName="controlsToggles"> <div styleName="toggle"> <Toggle checked={manualRate} onChange={this.handleManualRate} /> <div styleName="toggleText"> <FormattedMessage id="AddOffer418" defaultMessage="Custom exchange rate" /> {' '} <Tooltip id="add264"> <FormattedMessage id="add408" defaultMessage="To change the exchange rate " /> </Tooltip> </div> </div> <div styleName="toggle"> <Toggle checked={isPartial} onChange={() => this.setState((state) => ({ isPartial: !state.isPartial }))} /> <div styleName="toggleText"> <FormattedMessage id="AddOffer423" defaultMessage="Enable partial fills" /> {' '} <Tooltip id="add547"> <div style={{ textAlign: 'center' }} > <FormattedMessage id="addOfferPartialTooltip" defaultMessage={`You will receive exchange requests or the {p} amount less than the total amount you want {p} sell. For example you want to sell 1 BTC, other users can send you exchange requests {p}for 0.1, 0.5 BTC`} values={{ p: <br /> }} /> </div> </Tooltip> </div> </div> {isShowSwapModeSwitch && <div styleName="toggle"> <div styleName="toggleText"> <FormattedMessage id="AtomicSwap_Title" defaultMessage="Atomic swap" /> </div> <Toggle checked={isTurbo} isDisabled={!isTurboAllowed} onChange={() => this.setState((state) => ({ isTurbo: !state.isTurbo }))} /> <div styleName="toggleText"> <TurboIcon /> <span> <FormattedMessage id="TurboSwap_Title" defaultMessage="Turbo swap" /> &nbsp; <a href="https://github.com/swaponline/MultiCurrencyWallet/blob/master/docs/TURBO_SWAPS.md" target="_blank">(?)</a> </span> </div> </div> } </div> {needEthBalance && ( <div styleName="Error"> {isTokenBuy && ( <FormattedMessage id="CreateOffer_BuyToken_NeedEth" defaultMessage="Для покупки {buyCurrency} вам нужно иметь {ethAmount} ETH для оплаты коммисии" values={{ buyCurrency: buyCurrency.toUpperCase(), ethAmount: minAmountForSwap, }} /> )} {isTokenSell && ( <FormattedMessage id="CreateOffer_SellToken_NeedEth" defaultMessage="Для продажи {sellCurrency} вам нужно иметь {ethAmount} ETH для оплаты коммисии" values={{ sellCurrency: sellCurrency.toUpperCase(), ethAmount: minAmountForSwap, }} /> )} </div> )} { Object.values(linked).map((item, index) => Boolean(item.error) ? <div key={index} styleName="Error">{item.error}</div> : '' ) } <Button styleName="button" fullWidth blue disabled={isDisabled} onClick={this.handleNext}> <FormattedMessage id="AddOffer396" defaultMessage="Next" /> </Button> </div> ) } }
the_stack
import { nodesets } from "node-opcua-nodesets"; import { StructureDefinition, StructureType } from "node-opcua-types"; import { DataType } from "node-opcua-variant"; import { AddressSpace, dumpToBSD } from ".."; import { generateAddressSpace } from "../nodeJS"; describe("converting DataType to BSD schema files", () => { let addressSpace: AddressSpace; beforeEach(async () => { addressSpace = AddressSpace.create(); const nodesetFilename = [nodesets.standard]; await generateAddressSpace(addressSpace, nodesetFilename); addressSpace.registerNamespace("PRIVATE"); }); afterEach(async () => { addressSpace.dispose(); }); it("BSD1- should convert a DataType to a schema file", () => { const namespace = addressSpace.getOwnNamespace(); const dataType = namespace.createDataType({ browseName: "MyDataType", isAbstract: true, subtypeOf: "Structure" }); const xml = dumpToBSD(namespace); // tslint:disable-next-line: no-console // console.log(xml); xml.should.eql(`<?xml version="1.0"?> <opc:TypeDictionary xmlns:opc="http://opcfoundation.org/BinarySchema/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/" xmlns:n1="PRIVATE" DefaultByteOrder="LittleEndian" TargetNamespace="PRIVATE"> <opc:StructuredType Name="MyDataType" BaseType="ua:ExtensionObject"/> </opc:TypeDictionary>`); }); it("BSD2- structure 1", async () => { const namespace = addressSpace.getOwnNamespace(); const dataType = namespace.createDataType({ browseName: "MyDataType", isAbstract: true, subtypeOf: "Structure" }); (dataType as any).$definition = new StructureDefinition({ baseDataType: "", fields: [ { dataType: DataType.String, description: "the name", isOptional: false, name: "Name", valueRank: -1 }, { arrayDimensions: [1], dataType: DataType.Float, description: "the list of values", name: "Values", valueRank: 1 } ] }); const xml = dumpToBSD(namespace); // tslint:disable-next-line: no-console // console.log(xml); xml.should.eql(`<?xml version="1.0"?> <opc:TypeDictionary xmlns:opc="http://opcfoundation.org/BinarySchema/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/" xmlns:n1="PRIVATE" DefaultByteOrder="LittleEndian" TargetNamespace="PRIVATE"> <opc:StructuredType Name="MyDataType" BaseType="ua:ExtensionObject"> <opc:Field Name="Name" TypeName="opc:String"/> <opc:Field Name="NoOfValues" TypeName="opc:Int32"/> <opc:Field Name="Values" TypeName="opc:Float" LengthField="NoOfValues"/> </opc:StructuredType> </opc:TypeDictionary>`); }); it("BSD3 - Enumeration ", async () => { const namespace = addressSpace.getOwnNamespace(); namespace.addEnumerationType({ browseName: "MyEnumType2", enumeration: ["RUNNING", "BLOCKED", "IDLE", "UNDER MAINTENANCE"] }); const xml = dumpToBSD(namespace); // tslint:disable-next-line: no-console // console.log(xml); xml.should.eql(`<?xml version="1.0"?> <opc:TypeDictionary xmlns:opc="http://opcfoundation.org/BinarySchema/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/" xmlns:n1="PRIVATE" DefaultByteOrder="LittleEndian" TargetNamespace="PRIVATE"> <opc:EnumeratedType Name="MyEnumType2" LengthInBits="32"> <opc:EnumeratedValue Name="RUNNING" Value="0"/> <opc:EnumeratedValue Name="BLOCKED" Value="1"/> <opc:EnumeratedValue Name="IDLE" Value="2"/> <opc:EnumeratedValue Name="UNDER MAINTENANCE" Value="3"/> </opc:EnumeratedType> </opc:TypeDictionary>`); }); it("BSD4- structure 2", async () => { const namespace = addressSpace.getOwnNamespace(); const dataType = namespace.createDataType({ browseName: "MyDataType", isAbstract: true, subtypeOf: "Structure" }); const dataTypeEx = namespace.createDataType({ browseName: "MyDataTypeEx", isAbstract: true, subtypeOf: dataType.nodeId }); (dataType as any).$definition = new StructureDefinition({ baseDataType: "", fields: [ { dataType: DataType.String, description: "the name", isOptional: false, name: "Name", valueRank: -1 }, { arrayDimensions: [1], dataType: DataType.NodeId, description: "the list of NodeId", name: "Values", valueRank: 1 } ] }); (dataTypeEx as any).$definition = new StructureDefinition({ baseDataType: dataType.nodeId, fields: [ { dataType: DataType.LocalizedText, description: "extra prop", isOptional: false, name: "Extra", valueRank: -1 } ], structureType: StructureType.Structure }); const xml = dumpToBSD(namespace); // tslint:disable-next-line: no-console // console.log(xml); xml.should.eql(`<?xml version="1.0"?> <opc:TypeDictionary xmlns:opc="http://opcfoundation.org/BinarySchema/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/" xmlns:n1="PRIVATE" DefaultByteOrder="LittleEndian" TargetNamespace="PRIVATE"> <opc:StructuredType Name="MyDataType" BaseType="ua:ExtensionObject"> <opc:Field Name="Name" TypeName="opc:String"/> <opc:Field Name="NoOfValues" TypeName="opc:Int32"/> <opc:Field Name="Values" TypeName="ua:NodeId" LengthField="NoOfValues"/> </opc:StructuredType> <opc:StructuredType Name="MyDataTypeEx" BaseType="n1:MyDataType"> <opc:Field Name="Extra" TypeName="ua:LocalizedText"/> </opc:StructuredType> </opc:TypeDictionary>`); }); it("BSD5 - Opaque", async () => { /* to do : <opc: OpaqueType Name = "AudioDataType"> </opc:OpaqueType> */ }); it("BSD6 - WithOptionalValue", async () => { /* <opc:StructuredType Name="DataValue"> <opc:Documentation>A value with an associated timestamp, and quality.</opc:Documentation> <opc:Field Name="ValueSpecified" TypeName="opc:Bit" /> <opc:Field Name="StatusCodeSpecified" TypeName="opc:Bit" /> <opc:Field Name="SourceTimestampSpecified" TypeName="opc:Bit" /> <opc:Field Name="ServerTimestampSpecified" TypeName="opc:Bit" /> <opc:Field Name="SourcePicosecondsSpecified" TypeName="opc:Bit" /> <opc:Field Name="ServerPicosecondsSpecified" TypeName="opc:Bit" /> <opc:Field Name="Reserved1" TypeName="opc:Bit" Length="2" /> <opc:Field Name="Value" TypeName="ua:Variant" SwitchField="ValueSpecified" /> <opc:Field Name="StatusCode" TypeName="ua:StatusCode" SwitchField="StatusCodeSpecified" /> <opc:Field Name="SourceTimestamp" TypeName="opc:DateTime" SwitchField="SourceTimestampSpecified" /> <opc:Field Name="SourcePicoseconds" TypeName="opc:UInt16" SwitchField="SourcePicosecondsSpecified" /> <opc:Field Name="ServerTimestamp" TypeName="opc:DateTime" SwitchField="ServerTimestampSpecified" /> <opc:Field Name="ServerPicoseconds" TypeName="opc:UInt16" SwitchField="ServerPicosecondsSpecified" /> </opc:StructuredType> */ const namespace = addressSpace.getOwnNamespace(); const dataType = namespace.createDataType({ browseName: "MyDataWithSwitch", isAbstract: true, subtypeOf: "Structure" }); (dataType as any).$definition = new StructureDefinition({ baseDataType: "", fields: [ { dataType: DataType.String, description: "OptionalName", isOptional: true, name: "OptionalName", valueRank: -1 }, { arrayDimensions: [1], dataType: DataType.NodeId, description: "Optional list of NodeId", isOptional: true, name: "Values", valueRank: 1 } ] }); const xml = dumpToBSD(namespace); // tslint:disable-next-line: no-console // console.log(xml); xml.should.eql(`<?xml version="1.0"?> <opc:TypeDictionary xmlns:opc="http://opcfoundation.org/BinarySchema/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/" xmlns:n1="PRIVATE" DefaultByteOrder="LittleEndian" TargetNamespace="PRIVATE"> <opc:StructuredType Name="MyDataWithSwitch" BaseType="ua:ExtensionObject"> <opc:Field Name="OptionalNameSpecified" TypeName="opc:Bit"/> <opc:Field Name="ValuesSpecified" TypeName="opc:Bit"/> <opc:Field Name="Reserved1" TypeName="opc:Bit" Length="30"/> <opc:Field Name="OptionalName" TypeName="opc:String" SwitchField="OptionalNameSpecified"/> <opc:Field Name="NoOfValues" TypeName="opc:Int32" SwitchField="ValuesSpecified"/> <opc:Field Name="Values" TypeName="ua:NodeId" LengthField="NoOfValues" SwitchField="ValuesSpecified"/> </opc:StructuredType> </opc:TypeDictionary>`); }); });
the_stack
import * as assert from 'assert'; import { URI } from 'vs/base/common/uri'; import { join } from 'vs/base/common/path'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IUntitledTextEditorService, UntitledTextEditorService } from 'vs/workbench/services/untitled/common/untitledTextEditorService'; import { workbenchInstantiationService, TestServiceAccessor } from 'vs/workbench/test/browser/workbenchTestServices'; import { snapshotToString } from 'vs/workbench/services/textfile/common/textfiles'; import { ModesRegistry, PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry'; import { IIdentifiedSingleEditOperation } from 'vs/editor/common/model'; import { Range } from 'vs/editor/common/core/range'; import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput'; import { IUntitledTextEditorModel } from 'vs/workbench/services/untitled/common/untitledTextEditorModel'; import { CancellationToken } from 'vs/base/common/cancellation'; import { EditorInputCapabilities } from 'vs/workbench/common/editor'; import { DisposableStore } from 'vs/base/common/lifecycle'; suite('Untitled text editors', () => { let disposables: DisposableStore; let instantiationService: IInstantiationService; let accessor: TestServiceAccessor; setup(() => { disposables = new DisposableStore(); instantiationService = workbenchInstantiationService(undefined, disposables); accessor = instantiationService.createInstance(TestServiceAccessor); }); teardown(() => { (accessor.untitledTextEditorService as UntitledTextEditorService).dispose(); disposables.dispose(); }); test('basics', async () => { const service = accessor.untitledTextEditorService; const workingCopyService = accessor.workingCopyService; const input1 = instantiationService.createInstance(UntitledTextEditorInput, service.create()); await input1.resolve(); assert.strictEqual(service.get(input1.resource), input1.model); assert.ok(service.get(input1.resource)); assert.ok(!service.get(URI.file('testing'))); assert.ok(input1.hasCapability(EditorInputCapabilities.Untitled)); assert.ok(!input1.hasCapability(EditorInputCapabilities.Readonly)); assert.ok(!input1.hasCapability(EditorInputCapabilities.Singleton)); assert.ok(!input1.hasCapability(EditorInputCapabilities.RequiresTrust)); const input2 = instantiationService.createInstance(UntitledTextEditorInput, service.create()); assert.strictEqual(service.get(input2.resource), input2.model); // toUntyped() const untypedInput = input1.toUntyped({ preserveViewState: 0 }); assert.strictEqual(untypedInput.forceUntitled, true); // get() assert.strictEqual(service.get(input1.resource), input1.model); assert.strictEqual(service.get(input2.resource), input2.model); // revert() await input1.revert(0); assert.ok(input1.isDisposed()); assert.ok(!service.get(input1.resource)); // dirty const model = await input2.resolve(); assert.strictEqual(await service.resolve({ untitledResource: input2.resource }), model); assert.ok(service.get(model.resource)); assert.ok(!input2.isDirty()); const resourcePromise = awaitDidChangeDirty(accessor.untitledTextEditorService); model.textEditorModel?.setValue('foo bar'); const resource = await resourcePromise; assert.strictEqual(resource.toString(), input2.resource.toString()); assert.ok(input2.isDirty()); const dirtyUntypedInput = input2.toUntyped({ preserveViewState: 0 }); assert.strictEqual(dirtyUntypedInput.contents, 'foo bar'); const dirtyUntypedInputWithoutContent = input2.toUntyped(); assert.strictEqual(dirtyUntypedInputWithoutContent.contents, undefined); assert.ok(workingCopyService.isDirty(input2.resource)); assert.strictEqual(workingCopyService.dirtyCount, 1); await input1.revert(0); await input2.revert(0); assert.ok(!service.get(input1.resource)); assert.ok(!service.get(input2.resource)); assert.ok(!input2.isDirty()); assert.ok(!model.isDirty()); assert.ok(!workingCopyService.isDirty(input2.resource)); assert.strictEqual(workingCopyService.dirtyCount, 0); await input1.revert(0); assert.ok(input1.isDisposed()); assert.ok(!service.get(input1.resource)); input2.dispose(); assert.ok(!service.get(input2.resource)); }); function awaitDidChangeDirty(service: IUntitledTextEditorService): Promise<URI> { return new Promise(resolve => { const listener = service.onDidChangeDirty(async model => { listener.dispose(); resolve(model.resource); }); }); } test('associated resource is dirty', async () => { const service = accessor.untitledTextEditorService; const file = URI.file(join('C:\\', '/foo/file.txt')); let onDidChangeDirtyModel: IUntitledTextEditorModel | undefined = undefined; const listener = service.onDidChangeDirty(model => { onDidChangeDirtyModel = model; }); const model = service.create({ associatedResource: file }); const untitled = instantiationService.createInstance(UntitledTextEditorInput, model); assert.ok(untitled.isDirty()); assert.strictEqual(model, onDidChangeDirtyModel); const resolvedModel = await untitled.resolve(); assert.ok(resolvedModel.hasAssociatedFilePath); assert.strictEqual(untitled.isDirty(), true); untitled.dispose(); listener.dispose(); }); test('no longer dirty when content gets empty (not with associated resource)', async () => { const service = accessor.untitledTextEditorService; const workingCopyService = accessor.workingCopyService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); // dirty const model = await input.resolve(); model.textEditorModel?.setValue('foo bar'); assert.ok(model.isDirty()); assert.ok(workingCopyService.isDirty(model.resource, model.typeId)); model.textEditorModel?.setValue(''); assert.ok(!model.isDirty()); assert.ok(!workingCopyService.isDirty(model.resource, model.typeId)); input.dispose(); model.dispose(); }); test('via create options', async () => { const service = accessor.untitledTextEditorService; const model1 = await instantiationService.createInstance(UntitledTextEditorInput, service.create()).resolve(); model1.textEditorModel!.setValue('foo bar'); assert.ok(model1.isDirty()); model1.textEditorModel!.setValue(''); assert.ok(!model1.isDirty()); const model2 = await instantiationService.createInstance(UntitledTextEditorInput, service.create({ initialValue: 'Hello World' })).resolve(); assert.strictEqual(snapshotToString(model2.createSnapshot()!), 'Hello World'); const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); const model3 = await instantiationService.createInstance(UntitledTextEditorInput, service.create({ untitledResource: input.resource })).resolve(); assert.strictEqual(model3.resource.toString(), input.resource.toString()); const file = URI.file(join('C:\\', '/foo/file44.txt')); const model4 = await instantiationService.createInstance(UntitledTextEditorInput, service.create({ associatedResource: file })).resolve(); assert.ok(model4.hasAssociatedFilePath); assert.ok(model4.isDirty()); model1.dispose(); model2.dispose(); model3.dispose(); model4.dispose(); input.dispose(); }); test('associated path remains dirty when content gets empty', async () => { const service = accessor.untitledTextEditorService; const file = URI.file(join('C:\\', '/foo/file.txt')); const input = instantiationService.createInstance(UntitledTextEditorInput, service.create({ associatedResource: file })); // dirty const model = await input.resolve(); model.textEditorModel?.setValue('foo bar'); assert.ok(model.isDirty()); model.textEditorModel?.setValue(''); assert.ok(model.isDirty()); input.dispose(); model.dispose(); }); test('initial content is dirty', async () => { const service = accessor.untitledTextEditorService; const workingCopyService = accessor.workingCopyService; const untitled = instantiationService.createInstance(UntitledTextEditorInput, service.create({ initialValue: 'Hello World' })); assert.ok(untitled.isDirty()); // dirty const model = await untitled.resolve(); assert.ok(model.isDirty()); assert.strictEqual(workingCopyService.dirtyCount, 1); untitled.dispose(); model.dispose(); }); test('created with files.defaultLanguage setting', () => { const defaultLanguage = 'javascript'; const config = accessor.testConfigurationService; config.setUserConfiguration('files', { 'defaultLanguage': defaultLanguage }); const service = accessor.untitledTextEditorService; const input = service.create(); assert.strictEqual(input.getMode(), defaultLanguage); config.setUserConfiguration('files', { 'defaultLanguage': undefined }); input.dispose(); }); test('created with files.defaultLanguage setting (${activeEditorLanguage})', async () => { const config = accessor.testConfigurationService; config.setUserConfiguration('files', { 'defaultLanguage': '${activeEditorLanguage}' }); accessor.editorService.activeTextEditorMode = 'typescript'; const service = accessor.untitledTextEditorService; const model = service.create(); assert.strictEqual(model.getMode(), 'typescript'); config.setUserConfiguration('files', { 'defaultLanguage': undefined }); accessor.editorService.activeTextEditorMode = undefined; model.dispose(); }); test('created with mode overrides files.defaultLanguage setting', () => { const mode = 'typescript'; const defaultLanguage = 'javascript'; const config = accessor.testConfigurationService; config.setUserConfiguration('files', { 'defaultLanguage': defaultLanguage }); const service = accessor.untitledTextEditorService; const input = service.create({ mode }); assert.strictEqual(input.getMode(), mode); config.setUserConfiguration('files', { 'defaultLanguage': undefined }); input.dispose(); }); test('can change mode afterwards', async () => { const mode = 'untitled-input-test'; ModesRegistry.registerLanguage({ id: mode, }); const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create({ mode })); assert.strictEqual(input.getMode(), mode); const model = await input.resolve(); assert.strictEqual(model.getMode(), mode); input.setMode('plaintext'); assert.strictEqual(input.getMode(), PLAINTEXT_MODE_ID); input.dispose(); model.dispose(); }); test('remembers that mode was set explicitly', async () => { const mode = 'untitled-input-test'; ModesRegistry.registerLanguage({ id: mode, }); const service = accessor.untitledTextEditorService; const model = service.create(); const input = instantiationService.createInstance(UntitledTextEditorInput, model); assert.ok(!input.model.hasModeSetExplicitly); input.setMode('plaintext'); assert.ok(input.model.hasModeSetExplicitly); assert.strictEqual(input.getMode(), PLAINTEXT_MODE_ID); input.dispose(); model.dispose(); }); test('service#onDidChangeEncoding', async () => { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; service.onDidChangeEncoding(model => { counter++; assert.strictEqual(model.resource.toString(), input.resource.toString()); }); // encoding const model = await input.resolve(); await model.setEncoding('utf16'); assert.strictEqual(counter, 1); input.dispose(); model.dispose(); }); test('service#onDidChangeLabel', async () => { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; service.onDidChangeLabel(model => { counter++; assert.strictEqual(model.resource.toString(), input.resource.toString()); }); // label const model = await input.resolve(); model.textEditorModel?.setValue('Foo Bar'); assert.strictEqual(counter, 1); input.dispose(); model.dispose(); }); test('service#onWillDispose', async () => { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; service.onWillDispose(model => { counter++; assert.strictEqual(model.resource.toString(), input.resource.toString()); }); const model = await input.resolve(); assert.strictEqual(counter, 0); model.dispose(); assert.strictEqual(counter, 1); }); test('service#getValue', async () => { // This function is used for the untitledocumentData API const service = accessor.untitledTextEditorService; const model1 = await instantiationService.createInstance(UntitledTextEditorInput, service.create()).resolve(); model1.textEditorModel!.setValue('foo bar'); assert.strictEqual(service.getValue(model1.resource), 'foo bar'); model1.dispose(); // When a model doesn't exist, it should return undefined assert.strictEqual(service.getValue(URI.parse('https://www.microsoft.com')), undefined); }); test('model#onDidChangeContent', async function () { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; const model = await input.resolve(); model.onDidChangeContent(() => counter++); model.textEditorModel?.setValue('foo'); assert.strictEqual(counter, 1, 'Dirty model should trigger event'); model.textEditorModel?.setValue('bar'); assert.strictEqual(counter, 2, 'Content change when dirty should trigger event'); model.textEditorModel?.setValue(''); assert.strictEqual(counter, 3, 'Manual revert should trigger event'); model.textEditorModel?.setValue('foo'); assert.strictEqual(counter, 4, 'Dirty model should trigger event'); input.dispose(); model.dispose(); }); test('model#onDidRevert and input disposed when reverted', async function () { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; const model = await input.resolve(); model.onDidRevert(() => counter++); model.textEditorModel?.setValue('foo'); await model.revert(); assert.ok(input.isDisposed()); assert.ok(counter === 1); }); test('model#onDidChangeName and input name', async function () { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; let model = await input.resolve(); model.onDidChangeName(() => counter++); model.textEditorModel?.setValue('foo'); assert.strictEqual(input.getName(), 'foo'); assert.strictEqual(model.name, 'foo'); assert.strictEqual(counter, 1); model.textEditorModel?.setValue('bar'); assert.strictEqual(input.getName(), 'bar'); assert.strictEqual(model.name, 'bar'); assert.strictEqual(counter, 2); model.textEditorModel?.setValue(''); assert.strictEqual(input.getName(), 'Untitled-1'); assert.strictEqual(model.name, 'Untitled-1'); model.textEditorModel?.setValue(' '); assert.strictEqual(input.getName(), 'Untitled-1'); assert.strictEqual(model.name, 'Untitled-1'); model.textEditorModel?.setValue('([]}'); // require actual words assert.strictEqual(input.getName(), 'Untitled-1'); assert.strictEqual(model.name, 'Untitled-1'); model.textEditorModel?.setValue('([]}hello '); // require actual words assert.strictEqual(input.getName(), '([]}hello'); assert.strictEqual(model.name, '([]}hello'); model.textEditorModel?.setValue('12345678901234567890123456789012345678901234567890'); // trimmed at 40chars max assert.strictEqual(input.getName(), '1234567890123456789012345678901234567890'); assert.strictEqual(model.name, '1234567890123456789012345678901234567890'); model.textEditorModel?.setValue('123456789012345678901234567890123456789🌞'); // do not break grapehems (#111235) assert.strictEqual(input.getName(), '123456789012345678901234567890123456789'); assert.strictEqual(model.name, '123456789012345678901234567890123456789'); assert.strictEqual(counter, 6); model.textEditorModel?.setValue('Hello\nWorld'); assert.strictEqual(counter, 7); function createSingleEditOp(text: string, positionLineNumber: number, positionColumn: number, selectionLineNumber: number = positionLineNumber, selectionColumn: number = positionColumn): IIdentifiedSingleEditOperation { let range = new Range( selectionLineNumber, selectionColumn, positionLineNumber, positionColumn ); return { identifier: null, range, text, forceMoveMarkers: false }; } model.textEditorModel?.applyEdits([createSingleEditOp('hello', 2, 2)]); assert.strictEqual(counter, 7); // change was not on first line input.dispose(); model.dispose(); const inputWithContents = instantiationService.createInstance(UntitledTextEditorInput, service.create({ initialValue: 'Foo' })); model = await inputWithContents.resolve(); assert.strictEqual(inputWithContents.getName(), 'Foo'); inputWithContents.dispose(); model.dispose(); }); test('model#onDidChangeDirty', async function () { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; const model = await input.resolve(); model.onDidChangeDirty(() => counter++); model.textEditorModel?.setValue('foo'); assert.strictEqual(counter, 1, 'Dirty model should trigger event'); model.textEditorModel?.setValue('bar'); assert.strictEqual(counter, 1, 'Another change does not fire event'); input.dispose(); model.dispose(); }); test('model#onDidChangeEncoding', async function () { const service = accessor.untitledTextEditorService; const input = instantiationService.createInstance(UntitledTextEditorInput, service.create()); let counter = 0; const model = await input.resolve(); model.onDidChangeEncoding(() => counter++); await model.setEncoding('utf16'); assert.strictEqual(counter, 1, 'Dirty model should trigger event'); await model.setEncoding('utf16'); assert.strictEqual(counter, 1, 'Another change to same encoding does not fire event'); input.dispose(); model.dispose(); }); test('backup and restore (simple)', async function () { return testBackupAndRestore('Some very small file text content.'); }); test('backup and restore (large, #121347)', async function () { const largeContent = '국어한\n'.repeat(100000); return testBackupAndRestore(largeContent); }); async function testBackupAndRestore(content: string) { const service = accessor.untitledTextEditorService; const originalInput = instantiationService.createInstance(UntitledTextEditorInput, service.create()); const restoredInput = instantiationService.createInstance(UntitledTextEditorInput, service.create()); const originalModel = await originalInput.resolve(); originalModel.textEditorModel?.setValue(content); const backup = await originalModel.backup(CancellationToken.None); const modelRestoredIdentifier = { typeId: originalModel.typeId, resource: restoredInput.resource }; await accessor.workingCopyBackupService.backup(modelRestoredIdentifier, backup.content); const restoredModel = await restoredInput.resolve(); assert.strictEqual(restoredModel.textEditorModel?.getValue(), content); assert.strictEqual(restoredModel.isDirty(), true); originalInput.dispose(); originalModel.dispose(); restoredInput.dispose(); restoredModel.dispose(); } });
the_stack
import {assert} from '../../platform/assert-web.js'; import {Refinement, AtLeastAsSpecific, RefinementExpressionLiteral} from './refiner.js'; import {SlotInfo} from './slot-info.js'; import {AnnotationRef} from '../../runtime/arcs-types/annotation.js'; import {Direction, SlotDirection} from '../../runtime/arcs-types/enums.js'; import {ParticleSpec} from '../../runtime/arcs-types/particle-spec.js'; import {CRDTTypeRecord, CRDTEntity, CRDTModel, CRDTCount, CRDTCollection, CRDTSingleton, SingletonEntityModel, CollectionEntityModel, Referenceable} from '../../crdt/lib-crdt.js'; import {Dictionary, Predicate, Literal, IndentingStringBuilder} from '../../utils/lib-utils.js'; import {Flags} from '../../runtime/flags.js'; import {mergeMapInto} from '../../utils/lib-utils.js'; import {Primitive, SourceLocation} from '../../runtime/manifest-ast-types/manifest-ast-nodes.js'; import {digest} from '../../platform/digest-web.js'; import {Consumer} from '../../utils/lib-utils.js'; import {SchemaPrimitiveTypeValue, KotlinPrimitiveTypeValue, SchemaFieldKind as Kind} from '../../runtime/manifest-ast-types/manifest-ast-nodes.js'; export interface TypeLiteral extends Literal { tag: string; // tslint:disable-next-line: no-any data: any; } export type Tag = 'Entity' | 'TypeVariable' | 'Collection' | 'BigCollection' | 'Tuple' | 'Interface' | 'Slot' | 'Reference' | 'Arc' | 'Handle' | 'Count' | 'Singleton' | 'Mux'; export abstract class Type { tag: Tag; protected constructor(tag: Tag) { this.tag = tag; } static fromLiteral(literal: TypeLiteral) : Type { switch (literal.tag) { case 'Entity': return new EntityType(Schema.fromLiteral(literal.data)); case 'TypeVariable': return new TypeVariable(TypeVariableInfo.fromLiteral(literal.data)); case 'Collection': return new CollectionType(Type.fromLiteral(literal.data)); case 'BigCollection': return new BigCollectionType(Type.fromLiteral(literal.data)); case 'Tuple': return new TupleType(literal.data.map(t => Type.fromLiteral(t))); case 'Interface': return new InterfaceType(InterfaceInfo.fromLiteral(literal.data)); case 'Slot': return new SlotType(SlotInfo.fromLiteral(literal.data)); case 'Reference': return new ReferenceType(Type.fromLiteral(literal.data)); case 'Mux': return new MuxType(Type.fromLiteral(literal.data)); case 'Handle': return new HandleType(); case 'Singleton': return new SingletonType(Type.fromLiteral(literal.data)); default: throw new Error(`fromLiteral: unknown type ${literal} (tag = ${literal.tag})`); } } abstract toLiteral(): TypeLiteral; // Combines type ranges of this and the given type, and returns the smallest // contained range. abstract restrictTypeRanges(type: Type): Type; static unwrapPair(type1: Type, type2: Type): [Type, Type] { if (type1.tag === type2.tag) { const contained1 = type1.getContainedType(); if (contained1 !== null) { return Type.unwrapPair(contained1, type2.getContainedType()); } } return [type1, type2]; } static tryUnwrapMulti(type1: Type, type2: Type): [Type[], Type[]] { [type1, type2] = this.unwrapPair(type1, type2); if (type1.tag === type2.tag) { const contained1 = type1.getContainedTypes(); if (contained1 !== null) { return [contained1, type2.getContainedTypes()]; } } return [null, null]; } /** Tests whether two types' constraints are compatible with each other. */ static canMergeConstraints(type1: Type, type2: Type): boolean { return Type._canMergeCanReadSubset(type1, type2) && Type._canMergeCanWriteSuperset(type1, type2); } static _canMergeCanReadSubset(type1: Type, type2: Type): boolean { if (type1.canReadSubset && type2.canReadSubset) { if (type1.canReadSubset.tag !== type2.canReadSubset.tag) { return false; } if (type1.canReadSubset instanceof EntityType && type2.canReadSubset instanceof EntityType) { return Schema.intersect(type1.canReadSubset.entitySchema, type2.canReadSubset.entitySchema) !== null; } throw new Error(`_canMergeCanReadSubset not implemented for types tagged with ${type1.canReadSubset.tag}`); } return true; } static _canMergeCanWriteSuperset(type1: Type, type2: Type): boolean { if (type1.canWriteSuperset && type2.canWriteSuperset) { if (type1.canWriteSuperset.tag !== type2.canWriteSuperset.tag) { return false; } if (type1.canWriteSuperset instanceof EntityType && type2.canWriteSuperset instanceof EntityType) { return Schema.union(type1.canWriteSuperset.entitySchema, type2.canWriteSuperset.entitySchema) !== null; } } return true; } isSlot(): this is SlotType { return this instanceof SlotType; } slandleType(): SlotType | undefined { if (this.isSlot()) { return this; } if (this.isCollectionType() && this.collectionType.isSlot()) { return this.collectionType; } return undefined; } // If you want to type-check fully, this is an improvement over just using // this instanceof CollectionType, // because instanceof doesn't propagate generic restrictions. isCollectionType<T extends Type>(): this is CollectionType<T> { return this instanceof CollectionType; } // If you want to type-check fully, this is an improvement over just using // this instaneceof BigCollectionType, // because instanceof doesn't propagate generic restrictions. isBigCollectionType<T extends Type>(): this is BigCollectionType<T> { return this instanceof BigCollectionType; } isReferenceType(): this is ReferenceType<Type> { return this instanceof ReferenceType; } isNullableType(): this is NullableField { return this instanceof NullableField; } isMuxType(): this is MuxType<EntityType> { return this instanceof MuxType && this.innerType instanceof EntityType; } isTupleType(): this is TupleType { return this instanceof TupleType; } isResolved(): boolean { // TODO: one of these should not exist. return !this.hasUnresolvedVariable; } mergeTypeVariablesByName(variableMap: Map<string, Type>): Type { return this; } _applyExistenceTypeTest(test: Predicate<Type>): boolean { return test(this); } get hasVariable(): boolean { return this._applyExistenceTypeTest(type => type instanceof TypeVariable); } get hasUnresolvedVariable(): boolean { return this._applyExistenceTypeTest(type => type instanceof TypeVariable && !type.variable.isResolved()); } getContainedType(): Type|null { return null; } getContainedTypes(): Type[]|null { return null; } isTypeContainer(): boolean { return false; } get isReference(): boolean { return false; } get isMux(): boolean { return false; } get isSingleton(): boolean { return false; } get isCollection(): boolean { return false; } get isEntity(): boolean { return false; } get isInterface(): boolean { return false; } get isTuple(): boolean { return false; } get isVariable(): boolean { return false; } collectionOf() { return new CollectionType(this); } singletonOf() { return new SingletonType(this); } bigCollectionOf() { return new BigCollectionType(this); } referenceTo() { return new ReferenceType(this); } muxTypeOf() { return new MuxType(this); } resolvedType(): Type { return this; } canResolve(): boolean { return this.isResolved() || this._canResolve(); } protected _canResolve(): boolean { return true; } maybeResolve(options = undefined): boolean { return true; } get canWriteSuperset(): Type { throw new Error(`canWriteSuperset not implemented for ${this}`); } get canReadSubset(): Type { throw new Error(`canReadSubset not implemented for ${this}`); } isAtLeastAsSpecificAs(type: Type): boolean { return this.tag === type.tag && this._isAtLeastAsSpecificAs(type); } protected _isAtLeastAsSpecificAs(type: Type): boolean { throw new Error(`isAtLeastAsSpecificAs not implemented for ${this}`); } /** * Clone a type object. * When cloning multiple types, variables that were associated with the same name * before cloning should still be associated after cloning. To maintain this * property, create a Map() and pass it into all clone calls in the group. */ clone(variableMap: Map<string, Type>) { return this.resolvedType()._clone(variableMap); } protected _clone(variableMap: Map<string, Type>) { return Type.fromLiteral(this.toLiteral()); } /** * Clone a type object, maintaining resolution information. * This function SHOULD NOT BE USED at the type level. In order for type variable * information to be maintained correctly, an entire context root needs to be * cloned. */ _cloneWithResolutions(variableMap): Type { return Type.fromLiteral(this.toLiteral()); } // TODO: is this the same as _applyExistenceTypeTest hasProperty(property): boolean { return property(this) || this._hasProperty(property); } protected _hasProperty(property): boolean { return false; } toString(options = undefined): string { return this.tag; } getEntitySchema(): Schema|null { return null; } toPrettyString(): string|null { return null; } crdtInstanceConstructor<T extends CRDTTypeRecord>(): (new () => CRDTModel<T>) | null { return null; } handleConstructor<T extends CRDTTypeRecord>() { return null; } } export class CountType extends Type { constructor() { super('Count'); } toLiteral(): TypeLiteral { return {tag: 'Count', data: {}}; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); throw new Error(`'restrictTypeRanges' is not supported for ${this.tag}`); } crdtInstanceConstructor() { return CRDTCount; } } export class SingletonType<T extends Type> extends Type { private readonly innerType: T; static handleClass = null; constructor(type: T) { super('Singleton'); this.innerType = type; } toLiteral(): TypeLiteral { return {tag: 'Singleton', data: this.innerType.toLiteral()}; } getContainedType(): T { return this.innerType; } crdtInstanceConstructor() { return CRDTSingleton; } handleConstructor<T>() { return SingletonType.handleClass; } get isSingleton(): boolean { return true; } getEntitySchema(): Schema { return this.innerType.getEntitySchema(); } toString(options = undefined): string { return `![${this.innerType.toString(options)}]`; } get canWriteSuperset(): Type { return this.innerType.canWriteSuperset; } get canReadSubset() { return this.innerType.canReadSubset; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); return new SingletonType(this.innerType.restrictTypeRanges(type)); } mergeTypeVariablesByName(variableMap: Map<string, Type>) { const innerType = this.innerType; const result = innerType.mergeTypeVariablesByName(variableMap); return (result === innerType) ? this : result.singletonOf(); } } export class EntityType extends Type { readonly entitySchema: Schema; constructor(schema: Schema) { super('Entity'); this.entitySchema = schema; } static make( names: string[], fields: {}, options: {description?, refinement?: Refinement, annotations?: AnnotationRef[]} = {} ): EntityType { return new EntityType(new Schema(names, fields, options)); } // These type identifier methods are being left in place for non-runtime code. get isEntity(): boolean { return true; } get canWriteSuperset(): EntityType { return this; } get canReadSubset(): EntityType { return this; } _isAtLeastAsSpecificAs(type: EntityType): boolean { return this.entitySchema.isAtLeastAsSpecificAs(type.entitySchema); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.entitySchema.toLiteral()}; } toString(options = undefined): string { return this.entitySchema.toInlineSchemaString(options); } getEntitySchema(): Schema { return this.entitySchema; } _cloneWithResolutions(variableMap): EntityType { if (variableMap.has(this.entitySchema)) { return variableMap.get(this.entitySchema); } const clonedEntityType = new EntityType(this.entitySchema); variableMap.set(this.entitySchema, clonedEntityType); return clonedEntityType; } toPrettyString(): string { if (this.entitySchema.description.pattern) { return this.entitySchema.description.pattern; } // Spit MyTypeFOO to My Type FOO if (this.entitySchema.name) { return this.entitySchema.name.replace(/([^A-Z])([A-Z])/g, '$1 $2') .replace(/([A-Z][^A-Z])/g, ' $1') .replace(/[\s]+/g, ' ') .trim(); } return JSON.stringify(this.entitySchema.toLiteral()); } crdtInstanceConstructor<T extends CRDTTypeRecord>(): new () => CRDTModel<T> { return this.entitySchema.crdtConstructor(); } handleConstructor<T>() { // Currently using SingletonHandle as the implementation for Entity handles. // TODO: Make an EntityHandle class that uses the proper Entity CRDT. throw new Error(`Entity handle not yet implemented - you probably want to use a SingletonType`); } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); assert(this.getEntitySchema().name === type.getEntitySchema().name); return new EntityType( Schema.intersect(this.getEntitySchema(), type.getEntitySchema())); } } export class TypeVariable extends Type { readonly variable: TypeVariableInfo; constructor(variable: TypeVariableInfo) { super('TypeVariable'); this.variable = variable; } static make(name: string, canWriteSuperset: Type = null, canReadSubset: Type = null, resolvesToMaxType = false): TypeVariable { return new TypeVariable(new TypeVariableInfo(name, canWriteSuperset, canReadSubset, resolvesToMaxType)); } get isVariable(): boolean { return true; } mergeTypeVariablesByName(variableMap: Map<string, Type>) { const name = this.variable.name; let variable = variableMap.get(name); if (!variable) { variable = this; variableMap.set(name, this); } else if (variable instanceof TypeVariable) { if (variable.variable.hasConstraint || this.variable.hasConstraint) { const mergedConstraint = variable.variable.maybeMergeConstraints(this.variable); if (!mergedConstraint) { throw new Error('could not merge type variables'); } } } return variable; } resolvedType() { return this.variable.resolution || this; } _canResolve() { return this.variable.canResolve(); } maybeResolve(options = undefined): boolean { return this.variable.maybeResolve(options); } get canWriteSuperset() { return this.variable.canWriteSuperset; } get canReadSubset() { return this.variable.canReadSubset; } _clone(variableMap) { const name = this.variable.name; if (variableMap.has(name)) { return new TypeVariable(variableMap.get(name)); } else { const newTypeVariable = TypeVariableInfo.fromLiteral(this.variable.toLiteral()); variableMap.set(name, newTypeVariable); return new TypeVariable(newTypeVariable); } } _cloneWithResolutions(variableMap: Map<TypeVariableInfo|Schema, TypeVariableInfo|Schema>): TypeVariable { if (variableMap.has(this.variable)) { return new TypeVariable(variableMap.get(this.variable) as TypeVariableInfo); } else { const newTypeVariable = TypeVariableInfo.fromLiteral(this.variable.toLiteralIgnoringResolutions()); if (this.variable.resolution) { newTypeVariable._resolution = this.variable._resolution._cloneWithResolutions(variableMap); } if (this.variable._canReadSubset) { newTypeVariable.canReadSubset = this.variable.canReadSubset._cloneWithResolutions(variableMap); } if (this.variable._canWriteSuperset) { newTypeVariable.canWriteSuperset = this.variable.canWriteSuperset._cloneWithResolutions(variableMap); } if (this.variable._originalCanReadSubset) { newTypeVariable._originalCanReadSubset = this.variable._originalCanReadSubset._cloneWithResolutions(variableMap); } if (this.variable._originalCanWriteSuperset) { newTypeVariable._originalCanWriteSuperset = this.variable._originalCanWriteSuperset._cloneWithResolutions(variableMap); } variableMap.set(this.variable, newTypeVariable); return new TypeVariable(newTypeVariable); } } toLiteral(): TypeLiteral { return this.variable.resolution ? this.variable.resolution.toLiteral() : {tag: this.tag, data: this.variable.toLiteral()}; } toString(options = undefined) { return `~${this.variable.name}`; } getEntitySchema(): Schema { return this.variable.isResolved() ? this.resolvedType().getEntitySchema() : null; } toPrettyString(): string { return this.variable.isResolved() ? this.resolvedType().toPrettyString() : `[~${this.variable.name}]`; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); const typeVar = type as TypeVariable; const restrictedTypeVar = this.variable.restrictTypeRanges(typeVar.variable); if (!restrictedTypeVar) { throw new Error(`Cannot restrict type ranges of ${this.variable.toPrettyString()}` + ` and ${typeVar.variable.toPrettyString()}`); } return new TypeVariable(restrictedTypeVar); } } export class CollectionType<T extends Type> extends Type { readonly collectionType: T; static handleClass = null; constructor(collectionType: T) { super('Collection'); this.collectionType = collectionType; } get isCollection(): boolean { return true; } _isAtLeastAsSpecificAs(type: CollectionType<T>): boolean { return this.getContainedType().isAtLeastAsSpecificAs(type.getContainedType()); } mergeTypeVariablesByName(variableMap: Map<string, Type>): CollectionType<Type> { const collectionType = this.collectionType; const result = collectionType.mergeTypeVariablesByName(variableMap); return (result === collectionType) ? this : result.collectionOf(); } _applyExistenceTypeTest(test: Predicate<Type>): boolean { return this.collectionType._applyExistenceTypeTest(test); } getContainedType(): T { return this.collectionType; } isTypeContainer(): boolean { return true; } resolvedType(): CollectionType<Type> { const collectionType = this.collectionType; const resolvedCollectionType = collectionType.resolvedType(); return (collectionType !== resolvedCollectionType) ? resolvedCollectionType.collectionOf() : this; } _canResolve(): boolean { return this.collectionType.canResolve(); } maybeResolve(options = undefined): boolean { return this.collectionType.maybeResolve(options); } get canWriteSuperset(): InterfaceType { return InterfaceType.make(this.tag, [], []); } get canReadSubset() { return InterfaceType.make(this.tag, [], []); } _clone(variableMap: Map<string, Type>) { const data = this.collectionType.clone(variableMap).toLiteral(); return Type.fromLiteral({tag: this.tag, data}); } _cloneWithResolutions(variableMap: Map<TypeVariableInfo|Schema, TypeVariableInfo|Schema>): CollectionType<Type> { return new CollectionType(this.collectionType._cloneWithResolutions(variableMap)); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.collectionType.toLiteral()}; } _hasProperty(property): boolean { return this.collectionType.hasProperty(property); } toString(options = undefined): string { return `[${this.collectionType.toString(options)}]`; } getEntitySchema(): Schema { return this.collectionType.getEntitySchema(); } toPrettyString(): string { const entitySchema = this.getEntitySchema(); if (entitySchema && entitySchema.description.plural) { return entitySchema.description.plural; } return `${this.collectionType.toPrettyString()} List`; } crdtInstanceConstructor() { return CRDTCollection; } handleConstructor<T>() { return CollectionType.handleClass; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); return new CollectionType(this.getContainedType().restrictTypeRanges(type.getContainedType())); } } export class BigCollectionType<T extends Type> extends Type { readonly bigCollectionType: T; constructor(bigCollectionType: T) { super('BigCollection'); this.bigCollectionType = bigCollectionType; } get isBigCollection(): boolean { return true; } mergeTypeVariablesByName(variableMap: Map<string, Type>): BigCollectionType<Type> { const collectionType = this.bigCollectionType; const result = collectionType.mergeTypeVariablesByName(variableMap); return (result === collectionType) ? this : result.bigCollectionOf(); } _applyExistenceTypeTest(test): boolean { return this.bigCollectionType._applyExistenceTypeTest(test); } getContainedType(): T { return this.bigCollectionType; } isTypeContainer(): boolean { return true; } resolvedType(): BigCollectionType<Type> { const collectionType = this.bigCollectionType; const resolvedCollectionType = collectionType.resolvedType(); return (collectionType !== resolvedCollectionType) ? resolvedCollectionType.bigCollectionOf() : this; } _canResolve(): boolean { return this.bigCollectionType.canResolve(); } maybeResolve(options = undefined): boolean { return this.bigCollectionType.maybeResolve(options); } get canWriteSuperset(): InterfaceType { return InterfaceType.make(this.tag, [], []); } get canReadSubset() { return InterfaceType.make(this.tag, [], []); } _clone(variableMap: Map<string, Type>) { const data = this.bigCollectionType.clone(variableMap).toLiteral(); return Type.fromLiteral({tag: this.tag, data}); } _cloneWithResolutions(variableMap: Map<TypeVariableInfo|Schema, TypeVariableInfo|Schema>): BigCollectionType<Type> { return new BigCollectionType(this.bigCollectionType._cloneWithResolutions(variableMap)); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.bigCollectionType.toLiteral()}; } _hasProperty(property): boolean { return this.bigCollectionType.hasProperty(property); } toString(options = undefined): string { return `BigCollection<${this.bigCollectionType.toString(options)}>`; } getEntitySchema(): Schema { return this.bigCollectionType.getEntitySchema(); } toPrettyString(): string { const entitySchema = this.getEntitySchema(); if (entitySchema && entitySchema.description.plural) { return entitySchema.description.plural; } return `Collection of ${this.bigCollectionType.toPrettyString()}`; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); throw new Error(`'restrictTypeRanges' is not supported for ${this.tag}`); } } export class TupleType extends Type { readonly innerTypes: Type[]; constructor(innerTypes: Type[]) { super('Tuple'); this.innerTypes = innerTypes; } get isTuple(): boolean { return true; } isTypeContainer(): boolean { return true; } getContainedTypes(): Type[]|null { return this.innerTypes; } get canWriteSuperset() { return new TupleType(this.innerTypes.map(t => t.canWriteSuperset)); } get canReadSubset() { return new TupleType(this.innerTypes.map(t => t.canReadSubset)); } resolvedType() { let returnSelf = true; const resolvedinnerTypes = []; for (const t of this.innerTypes) { const resolved = t.resolvedType(); if (resolved !== t) returnSelf = false; resolvedinnerTypes.push(resolved); } if (returnSelf) return this; return new TupleType(resolvedinnerTypes); } _canResolve(): boolean { return this.innerTypesSatisfy((type) => type.canResolve()); } maybeResolve(options = undefined): boolean { return this.innerTypesSatisfy((type) => type.maybeResolve(options)); } _isAtLeastAsSpecificAs(other: TupleType): boolean { if (this.innerTypes.length !== other.innerTypes.length) return false; return this.innerTypesSatisfy((type, idx) => type.isAtLeastAsSpecificAs(other.innerTypes[idx])); } private innerTypesSatisfy(predicate: ((type: Type, idx: number) => boolean)): boolean { return this.innerTypes.reduce((result: boolean, type: Type, idx: number) => result && predicate(type, idx), true); } _applyExistenceTypeTest(test: Predicate<Type>): boolean { return this.innerTypes.reduce((result: boolean, type: Type) => result || type._applyExistenceTypeTest(test), false); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.innerTypes.map(t => t.toLiteral())}; } toString(options = undefined ): string { return `(${this.innerTypes.map(t => t.toString(options)).join(', ')})`; } toPrettyString(): string { return 'Tuple of ' + this.innerTypes.map(t => t.toPrettyString()).join(', '); } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); return new TupleType(this.getContainedTypes().map((innerType, idx) => innerType.restrictTypeRanges(type.getContainedTypes()[idx]))); } _clone(variableMap: Map<string, Type>): TupleType { return new TupleType(this.innerTypes.map(t => t.clone(variableMap))); } _cloneWithResolutions(variableMap: Map<string, Type>): TupleType { return new TupleType(this.innerTypes.map(t => t._cloneWithResolutions(variableMap))); } mergeTypeVariablesByName(variableMap: Map<string, Type>): TupleType { let mergeSuccess = false; const results = []; for (const type of this.innerTypes) { const result = type.mergeTypeVariablesByName(variableMap); if (result !== type) { mergeSuccess = true; } results.push(result); } return mergeSuccess ? new TupleType(results) : this; } } export interface HandleConnection { type: Type; name?: string|TypeVariable; direction?: Direction; // TODO make required } // TODO(lindner) only tests use optional props export interface Slot { name?: string|TypeVariable; direction?: SlotDirection; isRequired?: boolean; isSet?: boolean; } export class InterfaceType extends Type { readonly interfaceInfo: InterfaceInfo; constructor(iface: InterfaceInfo) { super('Interface'); this.interfaceInfo = iface; } static make(name: string, handleConnections: HandleConnection[], slots: Slot[]) { return new InterfaceType(InterfaceInfo.make(name, handleConnections, slots)); } get isInterface(): boolean { return true; } mergeTypeVariablesByName(variableMap: Map<string, Type>) { const interfaceInfo = this.interfaceInfo.clone(new Map()); interfaceInfo.mergeTypeVariablesByName(variableMap); // TODO: only build a new type when a variable is modified return new InterfaceType(interfaceInfo); } _applyExistenceTypeTest(test) { return this.interfaceInfo._applyExistenceTypeTest(test); } resolvedType() { return new InterfaceType(this.interfaceInfo.resolvedType()); } _canResolve(): boolean { return this.interfaceInfo.canResolve(); } maybeResolve(options = undefined): boolean { return this.interfaceInfo.maybeResolve(); } get canWriteSuperset(): InterfaceType { return new InterfaceType(this.interfaceInfo.canWriteSuperset); } get canReadSubset() { return new InterfaceType(this.interfaceInfo.canReadSubset); } _isAtLeastAsSpecificAs(type: InterfaceType) { return this.interfaceInfo.isAtLeastAsSpecificAs(type.interfaceInfo); } _clone(variableMap: Map<string, Type>) { const data = this.interfaceInfo.clone(variableMap).toLiteral(); return Type.fromLiteral({tag: this.tag, data}); } _cloneWithResolutions(variableMap): InterfaceType { return new InterfaceType(this.interfaceInfo.cloneWithResolutions(variableMap)); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.interfaceInfo.toLiteral()}; } toString(options = undefined): string { return this.interfaceInfo.name; } toPrettyString(): string { return this.interfaceInfo.toPrettyString(); } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); throw new Error(`'restrictTypeRanges' is not supported for ${this.tag}`); } } export class SlotType extends Type { private readonly slot: SlotInfo; constructor(slot: SlotInfo) { super('Slot'); this.slot = slot; } static make(formFactor: string, handle: string) { return new SlotType(new SlotInfo(formFactor, handle)); } getSlot(): SlotInfo { return this.slot; } get canWriteSuperset(): SlotType { return this; } get canReadSubset() { return this; } _isAtLeastAsSpecificAs(type: SlotType) { // TODO: formFactor checking, etc. return true; } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.slot.toLiteral()}; } toString(options = undefined): string { const fields: string[] = []; for (const key of Object.keys(this.slot)) { if (this.slot[key] !== undefined) { fields.push(`${key}:${this.slot[key]}`); } } let fieldsString = ''; if (fields.length !== 0) { fieldsString = ` {${fields.join(', ')}}`; } return `Slot${fieldsString}`; } toPrettyString(): string { const fields: string[] = []; for (const key of Object.keys(this.slot)) { if (this.slot[key] !== undefined) { fields.push(`${key}:${this.slot[key]}`); } } let fieldsString = ''; if (fields.length !== 0) { fieldsString = ` {${fields.join(', ')}}`; } return `Slot${fieldsString}`; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); throw new Error(`'restrictTypeRanges' is not supported for ${this.tag}`); } } export class ReferenceType<T extends Type> extends Type { readonly referredType: T; constructor(reference: T) { super('Reference'); if (!reference) { throw new Error('invalid type! Reference types must include a referenced type declaration'); } this.referredType = reference; } get isReference(): boolean { return true; } getContainedType(): T { return this.referredType; } isTypeContainer(): boolean { return true; } resolvedType() { const referredType = this.referredType; const resolvedReferredType = referredType.resolvedType(); return (referredType !== resolvedReferredType) ? new ReferenceType(resolvedReferredType) : this; } _isAtLeastAsSpecificAs(type: ReferenceType<T>): boolean { return this.getContainedType().isAtLeastAsSpecificAs(type.getContainedType()); } _canResolve(): boolean { return this.referredType.canResolve(); } maybeResolve(options = undefined): boolean { return this.referredType.maybeResolve(options); } get canWriteSuperset() { // TODO(cypher1): Possibly cannot write to references. return this.referredType.canWriteSuperset; } get canReadSubset() { return this.referredType.canReadSubset; } _clone(variableMap: Map<string, Type>) { const data = this.referredType.clone(variableMap).toLiteral(); return Type.fromLiteral({tag: this.tag, data}); } _cloneWithResolutions(variableMap: Map<TypeVariableInfo|Schema, TypeVariableInfo|Schema>): ReferenceType<T> { return new ReferenceType<T>(this.referredType._cloneWithResolutions(variableMap) as T); } _applyExistenceTypeTest(test: Predicate<Type>): boolean { return this.referredType._applyExistenceTypeTest(test); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.referredType.toLiteral()}; } toString(options = undefined): string { return '&' + this.referredType.toString(); } toPrettyString(): string { return 'Reference to ' + this.referredType.toPrettyString(); } getEntitySchema(): Schema { return this.referredType.getEntitySchema(); } crdtInstanceConstructor<T extends CRDTTypeRecord>(): new () => CRDTModel<T> { return this.referredType.crdtInstanceConstructor(); } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); return new ReferenceType(this.getContainedType().restrictTypeRanges(type.getContainedType())); } mergeTypeVariablesByName(variableMap: Map<string, Type>) { const referredType = this.referredType; const result = referredType.mergeTypeVariablesByName(variableMap); return (result === referredType) ? this : result.referenceTo(); } } export class MuxType<T extends Type> extends Type { readonly innerType: T; static handleClass = null; constructor(type: T) { super('Mux'); if (!type) { throw new Error('invalid type! Mux types must include an inner type declaration'); } this.innerType = type; } get isMux(): boolean { return true; } getContainedType(): T { return this.innerType; } isTypeContainer(): boolean { return true; } resolvedType() { const innerType = this.innerType; const resolvedInnerType = innerType.resolvedType(); return (innerType !== resolvedInnerType) ? new MuxType(resolvedInnerType) : this; } _canResolve(): boolean { return this.innerType.canResolve(); } maybeResolve(options = undefined): boolean { return this.innerType.maybeResolve(options); } get canWriteSuperset() { return this.innerType.canWriteSuperset; } get canReadSubset() { return this.innerType.canReadSubset; } _clone(variableMap: Map<string, Type>) { const data = this.innerType.clone(variableMap).toLiteral(); return Type.fromLiteral({tag: this.tag, data}); } _cloneWithResolutions(variableMap: Map<TypeVariableInfo|Schema, TypeVariableInfo|Schema>): MuxType<T> { return new MuxType<T>(this.innerType._cloneWithResolutions(variableMap) as T); } toLiteral(): TypeLiteral { return {tag: this.tag, data: this.innerType.toLiteral()}; } toString(options = undefined): string { return '#' + this.innerType.toString(); } toPrettyString(): string { return 'Mux Type of ' + this.innerType.toPrettyString(); } getEntitySchema(): Schema { return this.innerType.getEntitySchema(); } crdtInstanceConstructor<T extends CRDTTypeRecord>(): new () => CRDTModel<T> { return this.innerType.crdtInstanceConstructor(); } handleConstructor<T>() { return MuxType.handleClass; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); throw new MuxType(this.getContainedType().restrictTypeRanges(type.getContainedType())); } mergeTypeVariablesByName(variableMap: Map<string, Type>) { const innerType = this.innerType; const result = innerType.mergeTypeVariablesByName(variableMap); return (result === innerType) ? this : result.muxTypeOf(); } } export class HandleType extends Type { constructor() { super('Handle'); } get isHandle(): boolean { return true; } toLiteral(): TypeLiteral { return {tag: this.tag, data: {}}; } restrictTypeRanges(type: Type): Type { assert(this.tag === type.tag); throw new Error(`'restrictTypeRanges' is not supported for ${this.tag}`); } } interface TypeVariableInfoLiteral { name: string; canWriteSuperset?: TypeLiteral; canReadSubset?: TypeLiteral; resolveToMaxType: boolean; } export class TypeVariableInfo { name: string; _canWriteSuperset?: Type|null; _canReadSubset?: Type|null; _resolution?: Type|null; // Note: original types are needed, because type variable resolution destroys // the range values, and this shouldn't be happening. _originalCanWriteSuperset?: Type|null; _originalCanReadSubset?: Type|null; resolveToMaxType: boolean; constructor(name: string, canWriteSuperset?: Type, canReadSubset?: Type, resolveToMaxType: boolean = false) { this.name = name; this._canWriteSuperset = canWriteSuperset; this._canReadSubset = canReadSubset; this._resolution = null; this.resolveToMaxType = resolveToMaxType; } /** * Merge both the read subset (upper bound) and write superset (lower bound) constraints * of two variables together. Use this when two separate type variables need to resolve * to the same value. */ maybeMergeConstraints(variable: TypeVariableInfo): boolean { if (!this.maybeMergeCanReadSubset(variable.canReadSubset)) { return false; } return this.maybeMergeCanWriteSuperset(variable.canWriteSuperset); } /** * Merge a type variable's read subset (upper bound) constraints into this variable. * This is used to accumulate read constraints when resolving a handle's type. */ maybeMergeCanReadSubset(constraint: Type): boolean { const {result, success} = this._maybeMerge( this.canReadSubset, constraint, Schema.intersect ); this.canReadSubset = result; return success; } /** * merge a type variable's write superset (lower bound) constraints into this variable. * This is used to accumulate write constraints when resolving a handle's type. */ maybeMergeCanWriteSuperset(constraint: Type): boolean { const {result, success} = this._maybeMerge(this.canWriteSuperset, constraint, Schema.union); this.canWriteSuperset = result; return success; } // Helper to generalize canReadSubset and canWriteSuperset merging private _maybeMerge(target: Type, constraint: Type, merger: (left: Schema, right: Schema) => Schema): { success: boolean; result: Type } { if (!constraint) { return {success: true, result: target}; } if (!target) { return {success: true, result: constraint}; } if (target instanceof SlotType && constraint instanceof SlotType) { // TODO: formFactor compatibility, etc. return {success: true, result: target}; } if (target instanceof EntityType && constraint instanceof EntityType) { const mergedSchema = merger(target.entitySchema, constraint.entitySchema); if (!mergedSchema) { return {success: false, result: target}; } return {success: true, result: new EntityType(mergedSchema)}; } return {success: false, result: target}; } isSatisfiedBy(type: Type): boolean { const constraint = this._canWriteSuperset; if (!constraint) { return true; } if (!(constraint instanceof EntityType) || !(type instanceof EntityType)) { throw new Error(`constraint checking not implemented for ${this} and ${type}`); } return type.getEntitySchema().isAtLeastAsSpecificAs(constraint.getEntitySchema()); } get resolution(): Type|null { if (this._resolution) { return this._resolution.resolvedType(); } return null; } isValidResolutionCandidate(value: Type): {result: boolean, detail?: string} { const elementType = value.resolvedType().getContainedType(); if (elementType instanceof TypeVariable && elementType.variable === this) { return {result: false, detail: 'variable cannot resolve to collection of itself'}; } return {result: true}; } set resolution(value: Type) { assert(!this._resolution); const isValid = this.isValidResolutionCandidate(value); assert(isValid.result, isValid.detail); let probe = value; while (probe) { if (!(probe instanceof TypeVariable)) { break; } if (this.resolveToMaxType) { probe.variable.resolveToMaxType = true; } if (probe.variable === this) { return; } probe = probe.variable.resolution; } this._resolution = value; this._originalCanWriteSuperset = this._canWriteSuperset; this._canWriteSuperset = null; this._originalCanReadSubset = this._canReadSubset; this._canReadSubset = null; } get canWriteSuperset(): Type | null { if (this._resolution) { assert(!this._canWriteSuperset); if (this._resolution instanceof TypeVariable) { return this._resolution.variable.canWriteSuperset; } return null; } return this._canWriteSuperset; } set canWriteSuperset(value: Type|null) { assert(!this._resolution); this._canWriteSuperset = value; } get canReadSubset(): Type | null { if (this._resolution) { assert(!this._canReadSubset); if (this._resolution instanceof TypeVariable) { return this._resolution.variable.canReadSubset; } return null; } return this._canReadSubset; } set canReadSubset(value: Type|null) { assert(!this._resolution); this._canReadSubset = value; } get hasConstraint() { return this._canReadSubset !== null || this._canWriteSuperset !== null; } canResolve() { if (this._resolution) { return this._resolution.canResolve(); } if (this._canWriteSuperset || this._canReadSubset) { return true; } return false; } maybeResolve(options = undefined) { if (this._resolution) { return this._resolution.maybeResolve(options); } if (this.resolveToMaxType && this._canReadSubset) { this.resolution = this._canReadSubset; return true; } if (this._canWriteSuperset) { this.resolution = this._canWriteSuperset; return true; } if (options && options.restrictToMinBound) { const entitySchema = this._canReadSubset ? this._canReadSubset.getEntitySchema() : null; this.resolution = new EntityType(new Schema( entitySchema ? entitySchema.names : [], {}, entitySchema || {})); return true; } if (this._canReadSubset) { this.resolution = this._canReadSubset; return true; } return false; } toLiteral() { assert(!this.resolution); return this.toLiteralIgnoringResolutions(); } toLiteralIgnoringResolutions(): TypeVariableInfoLiteral { return { name: this.name, canWriteSuperset: this._canWriteSuperset && this._canWriteSuperset.toLiteral(), canReadSubset: this._canReadSubset && this._canReadSubset.toLiteral(), resolveToMaxType: this.resolveToMaxType }; } static fromLiteral(data: TypeVariableInfoLiteral) { return new TypeVariableInfo( data.name, data.canWriteSuperset ? Type.fromLiteral(data.canWriteSuperset) : null, data.canReadSubset ? Type.fromLiteral(data.canReadSubset) : null, data.resolveToMaxType ); } isResolved(): boolean { return this._resolution && this._resolution.isResolved(); } restrictTypeRanges(other: TypeVariableInfo): TypeVariableInfo { const thisCanWriteSuperset = this.canWriteSuperset || this._originalCanWriteSuperset; const otherCanWriteSuperset = other.canWriteSuperset || other._originalCanWriteSuperset; let newCanWriteSuperset = thisCanWriteSuperset || otherCanWriteSuperset; if (thisCanWriteSuperset && otherCanWriteSuperset) { const unionSchema = Schema.union( thisCanWriteSuperset.getEntitySchema(), otherCanWriteSuperset.getEntitySchema()); if (!unionSchema) { throw new Error(`Cannot union schemas: ${thisCanWriteSuperset.toString()} and ${otherCanWriteSuperset.toString()}`); } newCanWriteSuperset = new EntityType(unionSchema); } const thisCanReadSubset = this.canReadSubset || this._originalCanReadSubset; const otherCanReadSubset = other.canReadSubset || other._originalCanReadSubset; let newCanReadSubset = thisCanReadSubset || otherCanReadSubset; if (thisCanReadSubset && otherCanReadSubset) { newCanReadSubset = new EntityType(Schema.intersect( thisCanReadSubset.getEntitySchema(), otherCanReadSubset.getEntitySchema())); } if (newCanWriteSuperset && newCanReadSubset && !newCanReadSubset.isAtLeastAsSpecificAs(newCanWriteSuperset)) { // Max bound must be at least as specific as min bound. return null; } return new TypeVariableInfo(this.name, newCanWriteSuperset, newCanReadSubset, this.resolveToMaxType); } toPrettyString() { return `[${(this.canWriteSuperset || 'undefined').toString()} - ${(this.canReadSubset || 'undefined').toString()}]`; } } // The interface for InterfaceInfo must live here to avoid circular dependencies. export interface HandleConnectionLiteral { type?: TypeLiteral; name?: string|TypeLiteral; direction?: Direction; } export interface SlotLiteral { name?: string|TypeLiteral; direction?: SlotDirection; isRequired?: boolean; isSet?: boolean; } export interface TypeVarReference { object: HandleConnection|Slot; field: string; } export interface InterfaceInfoLiteral { name: string; handleConnections: HandleConnectionLiteral[]; slots: SlotLiteral[]; } export type MatchResult = {var: TypeVariable, value: Type, direction: Direction}; type Maker = (name: string, handleConnections: HandleConnection[], slots: Slot[]) => InterfaceInfo; type HandleConnectionMatcher = (interfaceHandleConnection: HandleConnection, particleHandleConnection: HandleConnection) => boolean|MatchResult[]; type Deliteralizer = (data: InterfaceInfoLiteral) => InterfaceInfo; type SlotMatcher = (interfaceSlot: Slot, particleSlot: Slot) => boolean; export abstract class InterfaceInfo { name: string; handleConnections: HandleConnection[]; slots: Slot[]; // TODO(lindner) only accessed in tests public readonly typeVars: TypeVarReference[]; constructor(name: string, handleConnections: HandleConnection[], slots: Slot[]) { assert(name); assert(handleConnections !== undefined); assert(slots !== undefined); this.name = name; this.handleConnections = handleConnections; this.slots = slots; this.typeVars = []; } toPrettyString(): string { return 'InterfaceInfo'; } mergeTypeVariablesByName(variableMap: Map<string, Type>) { this.typeVars.forEach(({object, field}) => object[field] = (object[field] as Type).mergeTypeVariablesByName(variableMap)); } abstract readonly canReadSubset : InterfaceInfo; abstract readonly canWriteSuperset : InterfaceInfo; abstract isAtLeastAsSpecificAs(other: InterfaceInfo): boolean; abstract _applyExistenceTypeTest(test: Predicate<TypeVarReference>) : boolean; abstract toManifestString(builder?: IndentingStringBuilder) : string; static make : Maker = null; static fromLiteral : Deliteralizer = null; abstract toLiteral(): InterfaceInfoLiteral; abstract clone(variableMap: Map<string, Type>) : InterfaceInfo; abstract cloneWithResolutions(variableMap: Map<string, Type>) : InterfaceInfo; abstract canResolve() : boolean; abstract maybeResolve() : boolean; abstract tryMergeTypeVariablesWith(other: InterfaceInfo) : InterfaceInfo; abstract resolvedType() : InterfaceInfo; abstract equals(other: InterfaceInfo) : boolean; static _updateTypeVar(typeVar: TypeVarReference, update: (t: Type) => Type): void { typeVar.object[typeVar.field] = update(typeVar.object[typeVar.field]); } static isTypeVar(reference: TypeVariable | Type | string | boolean): boolean { return reference instanceof TypeVariable || reference instanceof Type && reference.hasVariable; } static mustMatch(reference: TypeVariable | Type | string | boolean): boolean { return !( reference === null || reference === undefined || InterfaceInfo.isTypeVar(reference)); } static handleConnectionsMatch : HandleConnectionMatcher = null; static slotsMatch : SlotMatcher = null; abstract particleMatches(particleSpec: ParticleSpec): boolean; abstract restrictType(particleSpec: ParticleSpec): boolean; } // Moved from ./schema-field.ts export type SchemaFieldLiteralShape = {kind: Kind, schema?: SchemaFieldLiteralShape, model?: TypeLiteral}; export abstract class FieldType { public refinement: Refinement = null; public annotations: AnnotationRef[] = []; protected constructor(public readonly kind: Kind) {} get isPrimitive(): boolean { return this.kind === Kind.Primitive; } get isKotlinPrimitive(): boolean { return this.kind === Kind.KotlinPrimitive; } get isCollection(): boolean { return this.kind === Kind.Collection; } get isReference(): boolean { return this.kind === Kind.Reference; } get isOrderedList(): boolean { return this.kind === Kind.OrderedList; } get isUnion(): boolean { return this.kind === Kind.Union; } get isTuple(): boolean { return this.kind === Kind.Tuple; } get isNested(): boolean { return this.kind === Kind.Nested; } get isInline(): boolean { return this.kind === Kind.Inline || this.kind === Kind.TypeName; } get isNullable(): boolean { return this.kind === Kind.Nullable; } getType(): SchemaPrimitiveTypeValue | KotlinPrimitiveTypeValue { return null; } getFieldTypes(): FieldType[] { return null; } getFieldType(): FieldType { return null; } getEntityType(): EntityType { return null; } abstract toString(): string; abstract normalizeForHash(): string; clone(): FieldType { // tslint:disable-next-line: no-any const literal: any = this.toLiteral(); if (literal.refinement) { literal.refinement = Refinement.fromLiteral(literal.refinement); } return FieldType.fromLiteral(literal); } // tslint:disable-next-line: no-any toLiteral(): {} { return { kind: this.kind, annotations: this.annotations, refinement: this.refinement ? this.refinement.toLiteral() : null }; } equals(other: FieldType): boolean { // TODO(cypher1): structural check instead of stringification. return this.toString() === other.toString(); } // TODO(shans): output AtLeastAsSpecific here. This is necessary to support // refinements on nested structures and references. _isAtLeastAsSpecificAs(other: FieldType): boolean { // Default implementation for all field types. // Override this where custom behaviour is needed. return this.kind === other.kind && this.equals(other); } // TODO(shans): output AtLeastAsSpecific here. This is necessary to support // refinements on nested structures and references. isAtLeastAsSpecificAs(other: FieldType): boolean { // Generic implementation for all field types. // Do not override this. if (other instanceof NullableField && !(this instanceof NullableField)) { // Non nullable types are `atLeastAsSpecificAs` nullable types of a // type that they are `atLeastAsSpecificAs`. // i.e. T :> U? iff T :> U. // additionally T? :> U iff U == V? return this._isAtLeastAsSpecificAs(other.schema); } return this._isAtLeastAsSpecificAs(other); } static fromLiteral(field: SchemaFieldLiteralShape|string): FieldType { return FieldType.create(field); } static create(theField: SchemaFieldLiteralShape|string): FieldType { let newField = null; // tslint:disable-next-line: no-any const field = theField as any; if (typeof(field) === 'string') { assert(['Text', 'URL', 'Number', 'Boolean', 'Bytes'].includes(field), `non-primitive schema type ${field} need to be defined as a parser production`); newField = new PrimitiveField(field as SchemaPrimitiveTypeValue); } else { switch (field.kind) { case Kind.Primitive: newField = new PrimitiveField(field.type); break; case Kind.KotlinPrimitive: newField = new KotlinPrimitiveField(field.type); break; case Kind.Collection: newField = new CollectionField(FieldType.create(field.schema)); break; case Kind.Reference: newField = new ReferenceField(FieldType.create(field.schema)); break; case Kind.OrderedList: newField = new OrderedListField(FieldType.create(field.schema)); break; case Kind.Inline: case Kind.TypeName: { assert(field.model.tag === 'Entity'); let model = field.model; if (!(model instanceof EntityType)) { // TODO(b/178046886): remove this when models are always literals. model = Type.fromLiteral(model) as EntityType; } newField = new InlineField(model); break; } case Kind.Union: newField = new UnionField(field.types.map(type => FieldType.create(type))); break; case Kind.Tuple: newField = new TupleField(field.types.map(type => FieldType.create(type))); break; case Kind.Nested: newField = new NestedField(FieldType.create(field.schema)); break; case Kind.Nullable: newField = new NullableField(FieldType.create(field.schema)); break; default: throw new Error(`Unsupported schema field ${field.kind}`); } } newField.refinement = field.refinement || null; newField.annotations = field.annotations || []; return newField; } } export class PrimitiveField extends FieldType { constructor(public readonly type: SchemaPrimitiveTypeValue) { super(Kind.Primitive); assert(this.type); } getType(): SchemaPrimitiveTypeValue { return this.type; } toString(): string { return this.type; } normalizeForHash(): string { return `${this.type}|`; } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), type: this.type}; } } export class KotlinPrimitiveField extends FieldType { constructor(public readonly type: KotlinPrimitiveTypeValue) { super(Kind.KotlinPrimitive); } getType(): KotlinPrimitiveTypeValue { return this.type; } toString(): string { return this.type; } normalizeForHash(): string { return `${this.type}|`; } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), type: this.type}; } } export class CollectionField extends FieldType { constructor(public readonly schema: FieldType) { super(Kind.Collection); } getFieldType(): FieldType { return this.schema; } getEntityType(): EntityType { return this.getFieldType().getFieldType() ? this.getFieldType().getFieldType().getEntityType() : null; } toString(): string { return `[${this.schema.toString()}]`; } normalizeForHash(): string { if (this.schema.isPrimitive || this.schema.isKotlinPrimitive) { return `[${this.schema.getType()}]`; } return `[${this.schema.normalizeForHash()}]`; } _isAtLeastAsSpecificAs(other: FieldType): boolean { assert(this.kind === other.kind); return this.getFieldType().isAtLeastAsSpecificAs(other.getFieldType()); } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), schema: this.schema.toLiteral()}; } } export class ReferenceField extends FieldType { constructor(public readonly schema: FieldType) { super(Kind.Reference); assert(this.schema); } getFieldType(): FieldType { return this.schema; } getEntityType(): EntityType { return this.getFieldType().getEntityType(); } toString(): string { return `&${this.schema.toString()}`; } normalizeForHash(): string { return `&(${this.schema.getEntityType().entitySchema.normalizeForHash()})`; } _isAtLeastAsSpecificAs(other: FieldType): boolean { assert( this.kind === other.kind, `ReferenceField: Non-matching kinds ${this.kind} vs ${other.kind}.`); return this.getFieldType().getEntityType().isAtLeastAsSpecificAs(other.getFieldType().getEntityType()); } // tslint:disable-next-line: no-any toLiteral(): {} { return { ...super.toLiteral(), schema: {kind: this.schema.kind, model: this.schema.getEntityType().toLiteral()} }; } } export class NullableField extends FieldType { constructor(public readonly schema: FieldType) { super(Kind.Nullable); } getFieldType(): FieldType { return this.schema; } getEntityType(): EntityType { return this.getFieldType().getFieldType() ? this.getFieldType().getFieldType().getEntityType() : null; } toString(): string { return `${this.schema.toString()}?`; } normalizeForHash(): string { if (this.schema.isPrimitive || this.schema.isKotlinPrimitive) { return `${this.schema.getType()}?`; } return `${this.schema.normalizeForHash()}?`; } _isAtLeastAsSpecificAs(other: FieldType): boolean { return this.kind === other.kind && this.getFieldType().isAtLeastAsSpecificAs(other.getFieldType()); } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), schema: this.schema.toLiteral()}; } } export class OrderedListField extends FieldType { constructor(public readonly schema: FieldType) { super(Kind.OrderedList); } getFieldType(): FieldType { return this.schema; } getEntityType(): EntityType { return this.getFieldType().getFieldType() ? this.getFieldType().getFieldType().getEntityType() : null; } toString(): string { return `List<${this.schema.toString()}>`; } normalizeForHash(): string { if (this.schema.isPrimitive || this.schema.isKotlinPrimitive) { return `List<${this.schema.getType()}>`; } return `List<${this.schema.normalizeForHash()}>`; } _isAtLeastAsSpecificAs(other: FieldType): boolean { assert( this.kind === other.kind, `OrderedListField: Non-matching kinds ${this.kind} vs ${other.kind}.`); return this.getFieldType().isAtLeastAsSpecificAs(other.getFieldType()); } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), schema: this.schema.toLiteral()}; } } export class UnionField extends FieldType { constructor(public readonly types: FieldType[]) { super(Kind.Union); } getFieldTypes(): FieldType[] { return this.types; } toString(): string { return `(${this.types.map(type => type.toString()).join(' or ')})`; } normalizeForHash(): string { return `(${this.types.map(t => t.getType()).join('|')})`; } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), types: this.types.map(t => t.toLiteral())}; } } export class TupleField extends FieldType { constructor(public readonly types: FieldType[]) { super(Kind.Tuple); } getFieldTypes(): FieldType[] { return this.types; } toString(): string { return `(${this.types.map(type => type.toString()).join(', ')})`; } normalizeForHash(): string { return `(${this.types.map(t => t.getType()).join('|')})`; } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), types: this.types.map(t => t.toLiteral())}; } } export class NestedField extends FieldType { constructor(public readonly schema: FieldType) { super(Kind.Nested); assert(this.schema.isInline); } getFieldType(): FieldType { return this.schema; } getEntityType(): EntityType { return this.getFieldType().getEntityType(); } toString(): string { return `inline ${this.schema.toString()}`; } normalizeForHash(): string { return `inline ${this.getEntityType().entitySchema.normalizeForHash()}`; } _isAtLeastAsSpecificAs(other: FieldType): boolean { assert( this.kind === other.kind, `NestedField: Non-matching kinds ${this.kind} vs ${other.kind}.`); return this.getEntityType().isAtLeastAsSpecificAs(other.getEntityType()); } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), schema: this.schema.toLiteral()}; } } export class InlineField extends FieldType { constructor(public readonly model: EntityType) { super(Kind.Inline); } getEntityType(): EntityType { return this.model; } toString(): string { return this.getEntityType().getEntitySchema().toInlineSchemaString(); } normalizeForHash(): string { return this.getEntityType().getEntitySchema().normalizeForHash(); } // tslint:disable-next-line: no-any toLiteral(): {} { return {...super.toLiteral(), model: this.getEntityType()}; } } // Moved from ./schema.ts export type SchemaLiteral = { fields: {[index: string]: SchemaFieldLiteralShape}; names: string[]; description: {}; refinement: {kind: string, expression: RefinementExpressionLiteral}; }; export class Schema { readonly names: string[]; readonly fields: Dictionary<FieldType>; // tslint:disable-next-line: no-any refinement?: Refinement; description: Dictionary<string> = {}; isAlias: boolean; hashStr: string = null; _annotations: AnnotationRef[]; location?: SourceLocation = null; static fromLiteral(data: SchemaLiteral = {fields: {}, names: [], description: {}, refinement: null}) { const fields = {}; for (const key of Object.keys(data.fields)) { fields[key] = FieldType.fromLiteral(data.fields[key]); if (fields[key].refinement) { fields[key].refinement = Refinement.fromLiteral(fields[key].refinement); } } const result = new Schema(data.names, fields); result.description = data.description || {}; if (data.refinement) { result.refinement = Refinement.fromLiteral(data.refinement); } return result; } static EMPTY = new Schema([], {}); // For convenience, primitive field types can be specified as {name: 'Type'} // in `fields`; the constructor will convert these to the correct schema form. // tslint:disable-next-line: no-any constructor(names: string[], fields: Dictionary<any>, options: {description?, refinement?: Refinement, annotations?: AnnotationRef[]} = {} ) { this.names = names; this.fields = {}; this.refinement = options.refinement || null; const fNs = this.refinement && this.refinement.getFieldParams(); // if the schema level refinement is univariate, propogate it to the appropriate field if (fNs && fNs.size === 1 && Flags.fieldRefinementsAllowed) { const fN = fNs.keys().next().value; fields[fN].refinement = Refinement.intersectionOf(fields[fN].refinement, this.refinement); this.refinement = null; } for (const [name, field] of Object.entries(fields)) { this.fields[name] = field instanceof FieldType ? field : FieldType.create(field); } if (options.description && options.description.description) { // The descriptions should be passed ready for assignment into this.description. // TODO(cypher1): Refactor the schema construction code to do this rearrangement at the call site. options.description.description.forEach(desc => this.description[desc.name] = desc.pattern || desc.patterns[0]); } this.annotations = options.annotations || []; } private forEachRefinement(func: Consumer<Refinement>): void { const types = [this, ...Object.values(this.fields)]; types.forEach(type => type.refinement && func(type.refinement)); } getFieldParams(): Map<string, Primitive> { const params = new Map<string, Primitive>(); this.forEachRefinement( (ref: Refinement) => mergeMapInto(params, ref.getFieldParams()) ); return params; } getQueryParams(): Map<string, Primitive> { const params = new Map<string, Primitive>(); this.forEachRefinement( (ref: Refinement) => mergeMapInto(params, ref.getQueryParams()) ); return params; } getQueryType(): string { return this.getQueryParams().get('?'); } extractRefinementFromQuery(): Schema { const fields = []; for (const [name, fieldType] of Object.entries(this.fields)) { const field = {...fieldType}; field.refinement = field.refinement && field.refinement.extractRefinementFromQuery(); fields[name] = field; } const options = { refinement: this.refinement && this.refinement.extractRefinementFromQuery() }; const schema = new Schema(this.names, fields, options); if (this.description) { schema.description = this.description; } return schema; } toLiteral(): SchemaLiteral { const fields = {}; for (const key of Object.keys(this.fields)) { fields[key] = this.fields[key].toLiteral(); } const lit = { names: this.names, fields, description: this.description, refinement: this.refinement && this.refinement.toLiteral(), annotations: this.annotations }; if (this.location !== null) { lit['location'] = this.location; } return lit; } // TODO(cypher1): This should only be an ident used in manifest parsing. get name() { return this.names[0]; } get annotations(): AnnotationRef[] { return this._annotations; } set annotations(annotations: AnnotationRef[]) { annotations.every(a => assert(a.isValidForTarget('Schema'), `Annotation '${a.name}' is invalid for Schema`)); this._annotations = annotations; } getAnnotation(name: string): AnnotationRef | null { const annotations = this.findAnnotations(name); assert(annotations.length <= 1, `Multiple annotations found for '${name}'. Use findAnnotations instead.`); return annotations.length === 0 ? null : annotations[0]; } findAnnotations(name: string): AnnotationRef[] { return this.annotations.filter(a => a.name === name); } static typesEqual(fieldType1, fieldType2): boolean { return fieldType1.equals(fieldType2); } private static fieldTypeUnion(infield1: FieldType, infield2: FieldType): FieldType|null { // Ensure that changes to the field types are non-side-effecting const field1 = infield1 && infield1.clone(); const field2 = infield2 && infield2.clone(); if (field1.kind !== field2.kind) { if (field1.kind === 'schema-nullable') { return Schema.fieldTypeUnion(field1.getFieldType(), field2); } if (field2.kind === 'schema-nullable') { return Schema.fieldTypeUnion(field1, field2.getFieldType()); } return null; } switch (field1.kind) { case 'schema-collection': { const unionSchema = Schema.fieldTypeUnion(field1.getFieldType(), field2.getFieldType()); if (!unionSchema) { return null; } return new CollectionField(unionSchema); } case 'schema-reference': { const unionSchema = Schema.union( field1.getEntityType().entitySchema, field2.getEntityType().entitySchema); if (!unionSchema) { return null; } // Note: this is done because new EntityType(unionSchema) causes circular dependency. // tslint:disable-next-line: no-any const inlineUnionLiteral: any = field1.getFieldType().toLiteral(); inlineUnionLiteral.model.entitySchema = unionSchema; return new ReferenceField(FieldType.create(inlineUnionLiteral)); } case 'schema-nested': { const unionSchema = Schema.union( field1.getEntityType().entitySchema, field2.getEntityType().entitySchema); if (!unionSchema) { return null; } // Note: this is done because new EntityType(unionSchema) causes circular dependency. // tslint:disable-next-line: no-any const inlineUnionLiteral: any = field1.getFieldType().toLiteral(); inlineUnionLiteral.model.entitySchema = unionSchema; return new NestedField(FieldType.create(inlineUnionLiteral)); } case 'schema-ordered-list': { const unionSchema = Schema.fieldTypeUnion(field1.getFieldType(), field2.getFieldType()); if (!unionSchema) { return null; } return new OrderedListField(unionSchema); } case 'schema-nullable': { const unionSchema = Schema.fieldTypeUnion(field1.getFieldType(), field2.getFieldType()); if (!unionSchema) { return null; } return new NullableField(unionSchema); } default: return Schema.typesEqual(field1, field2) ? field1 : null; } } static union(schema1: Schema, schema2: Schema): Schema|null { const names = [...new Set([...schema1.names, ...schema2.names])]; const fields = {}; for (const [field, type] of [...Object.entries(schema1.fields), ...Object.entries(schema2.fields)]) { if (fields[field]) { const fieldUnionSchema = Schema.fieldTypeUnion(fields[field], type); if (!fieldUnionSchema) { return null; } if (!Schema.typesEqual(fields[field], fieldUnionSchema)) { fields[field] = {...fields[field], ...fieldUnionSchema}; } fields[field].refinement = Refinement.intersectionOf(fields[field].refinement, type.refinement); fields[field].annotations = [...(fields[field].annotations || []), ...(type.annotations || [])]; } else { fields[field] = type.clone(); } } return new Schema(names, fields, {refinement: Refinement.intersectionOf(schema1.refinement, schema2.refinement)}); } private static fieldTypeIntersection(infield1: FieldType, infield2: FieldType): FieldType|null { // Ensure that changes to the field types are non-side-effecting const field1 = infield1 && infield1.clone(); const field2 = infield2 && infield2.clone(); const missingField1 = (field1 === null || field1 === undefined); const missingField2 = (field2 === null || field2 === undefined); if (missingField1 || missingField2) { // TODO(b/174115805, b/144507619, b/144507352): Handle nullables // (with make it possible to store 'true' unions) return null; } if (field1.kind !== field2.kind) { if (field1.kind === 'schema-nullable') { return new NullableField(Schema.fieldTypeUnion(field1.getFieldType(), field2)); } if (field2.kind === 'schema-nullable') { return new NullableField(Schema.fieldTypeUnion(field1, field2.getFieldType())); } } // TODO: non-eq Kinds? if (field1.kind !== field2.kind) return null; switch (field1.kind) { case 'schema-collection': { const intersectSchema = Schema.fieldTypeIntersection(field1.getFieldType(), field2.getFieldType()); if (!intersectSchema) { return null; } return new CollectionField(intersectSchema); } case 'schema-reference': { const intersectSchema = Schema.intersect( field1.getEntityType().entitySchema, field2.getEntityType().entitySchema); if (!intersectSchema) { return null; } // Note: this is done because new EntityType(intersectSchema) causes circular dependency. // tslint:disable-next-line: no-any const inlineIntersectionLiteral: any = field1.getFieldType().toLiteral(); inlineIntersectionLiteral.model.entitySchema = intersectSchema; return new ReferenceField(FieldType.create(inlineIntersectionLiteral)); } case 'schema-nested': { const intersectSchema = Schema.intersect( field1.getEntityType().entitySchema, field2.getEntityType().entitySchema); if (!intersectSchema) { return null; } // Note: this is done because new EntityType(intersectSchema) causes circular dependency. // tslint:disable-next-line: no-any const inlineIntersectionLiteral: any = field1.getFieldType().toLiteral(); inlineIntersectionLiteral.model.entitySchema = intersectSchema; return new NestedField(FieldType.create(inlineIntersectionLiteral)); } case 'schema-ordered-list': { const intersectSchema = Schema.fieldTypeIntersection(field1.getFieldType(), field2.getFieldType()); if (!intersectSchema) { return null; } return new OrderedListField(intersectSchema); } case 'schema-nullable': { const intersectSchema = Schema.fieldTypeIntersection(field1.getFieldType(), field2.getFieldType()); if (!intersectSchema) { return null; } return new NullableField(intersectSchema); } default: return Schema.typesEqual(field1, field2) ? field1 : null; } } static intersect(schema1: Schema, schema2: Schema): Schema { const names = [...schema1.names].filter(name => schema2.names.includes(name)); const fields = {}; const fieldNames = new Set([...Object.keys(schema1.fields), ...Object.keys(schema2.fields)]); for (const field of fieldNames) { const type = schema1.fields[field]; const otherType = schema2.fields[field]; const intersectionType = Schema.fieldTypeIntersection(type, otherType); if (intersectionType) { fields[field] = intersectionType; fields[field].refinement = Refinement.unionOf(type && type.refinement, otherType && otherType.refinement); fields[field].annotations = (type.annotations || []).filter(a => (otherType.annotations || []).includes(a)); } } // if schema level refinement contains fields not present in the intersection, discard it const ref1 = !schema1.refinementHasFieldsNotIn(fields) ? schema1.refinement : null; const ref2 = !schema2.refinementHasFieldsNotIn(fields) ? schema2.refinement : null; return new Schema(names, fields, {refinement: Refinement.unionOf(ref1, ref2)}); } equals(otherSchema: Schema): boolean { if (this === otherSchema) { return true; } return (this.isEquivalentOrMoreSpecific(otherSchema) === AtLeastAsSpecific.YES) && (otherSchema.isEquivalentOrMoreSpecific(this) === AtLeastAsSpecific.YES); } isEquivalentOrMoreSpecific(otherSchema: Schema): AtLeastAsSpecific { const names = new Set(this.names); for (const name of otherSchema.names) { if (!names.has(name)) { return AtLeastAsSpecific.NO; } } // tslint:disable-next-line: no-any const fields: Dictionary<any> = {}; for (const [name, type] of Object.entries(this.fields)) { fields[name] = type; } let best = AtLeastAsSpecific.YES; for (const [name, type] of Object.entries(otherSchema.fields)) { if (!fields[name]) { return AtLeastAsSpecific.NO; } if (!fields[name].isAtLeastAsSpecificAs(type)) { return AtLeastAsSpecific.NO; } const fieldRes = Refinement.isAtLeastAsSpecificAs(fields[name].refinement, type.refinement); if (fieldRes === AtLeastAsSpecific.NO) { return AtLeastAsSpecific.NO; } else if (fieldRes === AtLeastAsSpecific.UNKNOWN) { best = AtLeastAsSpecific.UNKNOWN; } } const res = Refinement.isAtLeastAsSpecificAs(this.refinement, otherSchema.refinement); if (res === AtLeastAsSpecific.NO) { return AtLeastAsSpecific.NO; } else if (res === AtLeastAsSpecific.UNKNOWN) { best = AtLeastAsSpecific.UNKNOWN; } return best; } isAtLeastAsSpecificAs(otherSchema: Schema): boolean { // Implementation moved to isEquivalentOrMoreSpecific to allow handling 'unknowns' in code gen. return this.isEquivalentOrMoreSpecific(otherSchema) !== AtLeastAsSpecific.NO; } // Returns true if there are fields in this.refinement, that are not in fields refinementHasFieldsNotIn(fields): boolean { const amb = Object.keys(this.fields).filter(k => !(k in fields)); for (const field of amb) { if (this.refinement && this.refinement.containsField(field)) { return true; } } return false; } hasQuery(): boolean { if (!this.refinement) { return false; } const qParams: Map<string, string> = this.refinement.getQueryParams(); return qParams.size > 0; } crdtConstructor<S extends Dictionary<Referenceable>, C extends Dictionary<Referenceable>>() { const singletons = {}; const collections = {}; // This implementation only supports: // - singleton of a primitive, // - singleton of a reference, // - collection of primitives, // - collection of references for (const [fieldName, field] of Object.entries(this.fields)) { const type = field.getType(); const schema = field.getFieldType(); switch (field.kind) { case 'schema-primitive': { if (['Text', 'URL', 'Boolean', 'Number'].includes(type)) { singletons[fieldName] = new CRDTSingleton<{id: string}>(); } else { throw new Error(`Big Scary Exception: entity field ${fieldName} of type ${type} doesn't yet have a CRDT mapping implemented`); } break; } case 'schema-collection': { if (!schema) { throw new Error(`there is no schema for the entity field ${fieldName}`); } if (['Text', 'URL', 'Boolean', 'Number'].includes(schema.getType())) { collections[fieldName] = new CRDTCollection<{id: string}>(); } else if (schema.kind === 'schema-reference') { collections[fieldName] = new CRDTCollection<Referenceable>(); } else { throw new Error(`Big Scary Exception: entity field ${fieldName} of type ${schema.getType()} doesn't yet have a CRDT mapping implemented`); } break; } case 'schema-reference': { singletons[fieldName] = new CRDTSingleton<Referenceable>(); break; } case 'schema-ordered-list': { singletons[fieldName] = new CRDTSingleton<{id: string}>(); break; } default: { throw new Error(`Big Scary Exception: entity field ${fieldName} of type ${schema.getType()} doesn't yet have a CRDT mapping implemented`); } } } return class EntityCRDT extends CRDTEntity<S, C> { constructor() { super(singletons as SingletonEntityModel<S>, collections as CollectionEntityModel<C>); } }; } // TODO(jopra): Enforce that 'type' of a field is a Type. fieldToString([name, type]: [string, FieldType]) { const refExpr = type.refinement ? type.refinement.toString() : ''; const annotationsStr = (type.annotations || []).map(ann => ` ${ann.toString()}`).join(''); return `${name}: ${type.toString()}${refExpr}${annotationsStr}`; } toInlineSchemaString(options?: {hideFields?: boolean}): string { const names = this.names.join(' ') || '*'; const fields = Object.entries(this.fields).map(this.fieldToString).join(', '); return `${names} {${fields.length > 0 && options && options.hideFields ? '...' : fields}}${this.refinement ? this.refinement.toString() : ''}`; } toManifestString(builder = new IndentingStringBuilder()): string { builder.push(...this.annotations.map(a => a.toString())); builder.push(`schema ${this.names.join(' ')}`); builder.withIndent(builder => { builder.push(...Object.entries(this.fields).map(f => this.fieldToString(f))); if (this.refinement) { builder.push(this.refinement.toString()); } if (Object.keys(this.description).length > 0) { builder.push(`description \`${this.description.pattern}\``); builder.withIndent(builder => { for (const name of Object.keys(this.description)) { if (name !== 'pattern') { builder.push(`${name} \`${this.description[name]}\``); } } }); } }); return builder.toString(); } async hash(): Promise<string> { if (!this.hashStr) { this.hashStr = await digest(this.normalizeForHash()); } return this.hashStr; } normalizeForHash(): string { return this.names.slice().sort().join(' ') + '/' + Object.keys(this.fields).sort().map(field => `${field}:${this.fields[field].normalizeForHash()}` ).join('') + '/'; } }
the_stack
import { AriaAttributes, CSSProperties, CustomAttributes, } from '../../dom/types/attributes-core' export * from '../../dom/types/attributes-core' export interface SVGCoreAttributes<T> extends CustomAttributes<T> { /** * The `id` attribute assigns a unique name to an element. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/id](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/id) */ id?: string /** * The `tabindex` attribute allows you to control whether an element is * focusable and to define the relative order of the element for the purposes * of sequential focus navigation. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/tabindex](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/tabindex) */ tabIndex?: number /** * The `lang` attribute specifies the primary language used in contents and * attributes containing text content of particular elements. * * There is also an `xml:lang` attribute (with namespace). If both of them * are defined, the one with namespace is used and the one without is ignored. * * In SVG 1.1 there was a lang attribute defined with a different meaning and * only applying to `<glyph>` elements. That attribute specified a list of * languages in BCP 47 format. The glyph was meant to be used if the `xml:lang` * attribute exactly matched one of the languages given in the value of this * parameter, or if the `xml:lang` attribute exactly equaled a prefix of one * of the languages given in the value of this parameter such that the first * tag character following the prefix was "-". * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/lang](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/lang) */ lang?: string xmlBase?: string xmlLang?: string xmlSpace?: string role?: string } export interface SVGStyleAttributes { /** * Assigns a class name or set of class names to an element. You may assign * the same class name or names to any number of elements, however, multiple * class names must be separated by whitespace characters. * * An element's class name serves two key roles: * - As a style sheet selector, for when an author assigns style information * to a set of elements. * - For general use by the browser. * * You can use this class to style SVG content using CSS. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/class](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/class) */ class?: string /** * The `style` attribute allows to style an element using CSS declarations. * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style) */ style?: CSSProperties } export interface SVGConditionalProcessingAttributes { externalResourcesRequired?: boolean requiredExtensions?: string requiredFeatures?: string systemLanguage?: string } export interface SVGCommonAttributes<T> extends AriaAttributes, SVGCoreAttributes<T> {} export interface SVGXLinkAttributes { xlinkHref?: string xlinkType?: 'simple' xlinkRole?: string xlinkArcrole?: string xlinkTitle?: string xlinkShow?: 'new' | 'replace' | 'embed' | 'other' | 'none' xlinkActuate?: string } export interface SVGPresentationClipAttributes { clip?: string /** * The `clip-path` presentation attribute defines or associates a clipping * path with the element it is related to. * * **Note**: As a presentation attribute clip-path can be used as a CSS * property. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-path](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-path) */ clipPath?: string /** * The `clip-rule` attribute only applies to graphics elements that are * contained within a `<clipPath>` element. The `clip-rule` attribute * basically works as the `fill-rule` attribute, except that it applies to * `<clipPath>` definitions. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-rule](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-rule) */ clipRule?: 'nonzero' | 'evenodd' } export interface SVGPresentationColorAttributes { /** * The `color` attribute is used to provide a potential indirect value, * `currentcolor`, for the `fill`, `stroke`, `stop-color`, `flood-color`, * and `lighting-color` attributes. * * **Note**: As a presentation attribute, `color` can be used as a CSS * property. See [CSS color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) for further information. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color) */ color?: string /** * The `color-interpolation` attribute specifies the color space for gradient * interpolations, color animations, and alpha compositing. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-interpolation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-interpolation) */ colorInterpolation?: string /** * The `color-interpolation-filters` attribute specifies the color space for * imaging operations performed via filter effects. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-interpolation-filters](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-interpolation-filters) */ colorInterpolationFilters?: string /** * * The `color-profile` attribute is used to define which color profile a * raster image included through the `<image>` element should use. * * **Note**: As a presentation attribute, color-profile can be used as a * CSS property. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-profile](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-profile) * @deprecated Since SVG 2 * * This feature is no longer recommended. Though some browsers might still * support it, it may have already been removed from the relevant web * standards, may be in the process of being dropped, or may only be kept * for compatibility purposes. Avoid using it, and update existing code if * possible; see the compatibility table at the bottom of this page to guide * your decision. Be aware that this feature may cease to work at any time. */ colorProfile?: string /** * The `color-rendering` attribute provides a hint to the SVG user agent * about how to optimize its color interpolation and compositing operations. * * @deprecated This feature is no longer recommended. Though some browsers * might still support it, it may have already been removed from the relevant * web standards, may be in the process of being dropped, or may only be * kept for compatibility purposes. Avoid using it, and update existing code * if possible; see the compatibility table at the bottom of this page to * guide your decision. Be aware that this feature may cease to work at any * time. */ colorRendering?: string lightingColor?: string solidColor?: string solidOpacity?: number stopColor?: string stopOpacity?: number } export interface SVGPresentationFillAttributes { /** * The `fill` attribute has two different meanings. For shapes and text it's a * presentation attribute that defines the color (or any SVG paint servers * like gradients or patterns) used to paint the element; for animation it * defines the final state of the animation. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill) */ fill?: string /** * The `fill-opacity` attribute is a presentation attribute defining the * opacity of the paint server (color, gradient, pattern, etc) applied to * a shape. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity) */ fillOpacity?: number /** * The `fill-rule` attribute is a presentation attribute defining the * algorithm to use to determine the inside part of a shape. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule) */ fillRule?: 'nonzero' | 'evenodd' } export interface SVGPresentationFloodAttributes { /** * The `flood-color` attribute indicates what color to use to flood the * current filter primitive subregion. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/flood-color](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/flood-color) */ floodColor?: string /** * The `flood-opacity` attribute indicates the opacity value to use across * the current filter primitive subregion. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/flood-opacity](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/flood-opacity) */ floodOpacity?: number } export interface SVGPresentationFontAttributes { /** * The `font-family` attribute indicates which font family will be used to * render the text, specified as a prioritized list of font family names * and/or generic family names. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-family](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-family) */ fontFamily?: string /** * The `font-size` attribute refers to the size of the font from baseline to * baseline when multiple lines of text are set solid in a multiline layout * environment. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size) */ fontSize?: number | string /** * The `font-size-adjust` attribute allows authors to specify an aspect value * for an element that will preserve the x-height of the first choice font in * a substitute font. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size-adjust](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size-adjust) */ fontSizeAdjust?: number /** * The `font-stretch` attribute indicates the desired amount of condensing or * expansion in the glyphs used to render the text. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-stretch](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-stretch) */ fontStretch?: string /** * The `font-style` attribute specifies whether the text is to be rendered * using a normal, italic, or oblique face. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-style](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-style) */ fontStyle?: 'normal' | 'italic' | 'oblique' /** * The `font-variant` attribute indicates whether the text is to be rendered * using variations of the font's glyphs. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-variant](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-variant) */ fontVariant?: string /** * The `font-weight` attribute refers to the boldness or lightness of the * glyphs used to render the text, relative to other fonts in the same font * family. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-weight](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-weight) */ fontWeight?: number | 'normal' | 'bold' | 'bolder' | 'lighter' /** * The `letter-spacing` attribute controls spacing between text characters. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing) */ letterSpacing?: number /** * The `text-anchor` attribute is used to align (start-, middle- or * end-alignment) a string of pre-formatted text or auto-wrapped text where * the wrapping area is determined from the inline-size property relative to * a given point. It is not applicable to other types of auto-wrapped text. * For those cases you should use text-align. For multi-line text, the * alignment takes place for each line. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor) */ textAnchor?: 'start' | 'middle' | 'end' /** * The `text-decoration` attribute defines whether text is decorated with an * underline, overline and/or strike-through. It is a shorthand for the * text-decoration-line and text-decoration-style properties. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-decoration](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-decoration) */ textDecoration?: string /** * The `unicode-bidi` attribute specifies how the accumulation of the * background image is managed. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/unicode-bidi](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/unicode-bidi) */ unicodeBidi?: | 'normal' | 'embed' | 'isolate' | 'bidi-override' | 'isolate-override' | 'plaintext' /** * The `word-spacing` attribute specifies spacing behavior between words. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/word-spacing](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/word-spacing) */ wordSpacing?: number /** * The `writing-mode` attribute specifies whether the initial * inline-progression-direction for a `<text>` element shall be left-to-right, * right-to-left, or top-to-bottom. */ writingMode?: 'horizontal-tb' | 'vertical-rl' | 'vertical-lr' /** * The `alignment-baseline` attribute specifies how an object is aligned with * respect to its parent. This property specifies which baseline of this * element is to be aligned with the corresponding baseline of the parent. * * For example, this allows alphabetic baselines in Roman text to stay aligned * across font size changes. It defaults to the baseline with the same name as * the computed value of the `alignment-baseline` property. */ alignmentBaseline?: | 'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' | 'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'top' | 'center' | 'bottom' /** * The `baseline-shift` attribute allows repositioning of the * dominant-baseline relative to the dominant-baseline of the parent text * content element. The shifted object might be a sub- or superscript. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseline-shift](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseline-shift) */ baselineShift?: string | 'sub' | 'super' /** * The `dominant-baseline` attribute specifies the dominant baseline, which * is the baseline used to align the box’s text and inline-level contents. * It also indicates the default alignment baseline of any boxes participating * in baseline alignment in the box’s alignment context. * * @see [https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline) */ dominantBaseline?: string direction?: 'ltr' | 'rtl' glyphOrientationHorizontal?: 'auto' | number glyphOrientationVertical?: 'auto' | number } export interface SVGPresentationMarkerAttributes { markerEnd?: string markerStart?: string markerMid?: string } export interface SVGPresentationStrokeAttributes { stroke?: string strokeDasharray?: string strokeDashoffset?: string strokeLinecap?: string strokeLinejoin?: string strokeMiterlimit?: string strokeOpacity?: string strokeWidth?: string } export interface SVGPresentationTransformAttributes { transform?: string transformOrigin?: string } export interface SVGPresentationAttributes extends SVGPresentationClipAttributes, SVGPresentationColorAttributes, SVGPresentationFillAttributes, SVGPresentationStrokeAttributes, SVGPresentationTransformAttributes, SVGPresentationFloodAttributes, SVGPresentationFontAttributes, SVGPresentationMarkerAttributes, SVGPresentationStrokeAttributes { cursor?: string display?: string filter?: string mask?: string opacity?: number overflow?: 'visible' | 'hidden' | 'scroll' | 'auto' pointerEvents?: | 'bounding-box' | 'visiblePainted' | 'visibleFill' | 'visibleStroke' | 'visible' | 'painted' | 'fill' | 'stroke' | 'all' | 'none' shapeRendering?: | 'auto' | 'optimizeSpeed' | 'crispEdges' | 'geometricPrecision' imageRendering?: 'auto' | 'optimizeSpeed' | 'optimizeQuality' enableBackground?: string | number kerning?: 'auto' | number vectorEffect?: string visibility?: string } export interface SVGFilterPrimitiveAttributes { height?: number | string result?: string width?: number | string x?: number y?: number } export interface SVGTransferFunctionAttributes { type?: 'translate' | 'scale' | 'rotate' | 'skewX' | 'skewY' tableValues?: string slope?: number intercept?: number amplitude?: number exponent?: number offset?: number } export type AnimationAttributeTargetAttributeType = 'CSS' | 'XML' | 'auto' export interface AnimationAttributeTargetAttributes { /** * The `attributeName` attribute indicates the name of the CSS property or * attribute of the target element that is going to be changed during an * animation. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/attributeName */ attributeName?: string /** * The `attributeType` attribute specifies the namespace in which the target * attribute and its associated values are defined. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/attributeType * @deprecated This feature is no longer recommended. Though some browsers * might still support it, it may have already been removed from the relevant * web standards, may be in the process of being dropped, or may only be kept * for compatibility purposes. Avoid using it, and update existing code if * possible; see the compatibility table at the bottom of this page to guide * your decision. Be aware that this feature may cease to work at any time. */ attributeType?: AnimationAttributeTargetAttributeType } export type SVGAnimationTimingRestartMode = 'always' | 'whenNotActive' | 'never' export type SVGAnimationTimingRepeatCount = number | 'indefinite' export type SVGAnimationTimingRepeatDuration = string | 'indefinite' export type SVGAnimationTimingFillMode = 'freeze' | 'remove' export interface SVGAnimationTimingAttributes { /** * The `begin` attribute defines when an animation should begin or when an * element should be discarded. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/begin */ begin?: string /** * The `dur` attribute indicates the simple duration of an animation. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dur */ dur?: string /** * The `end` attribute defines an end value for the animation that can * constrain the active duration. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/end */ end?: string /** * The `min` attribute specifies the minimum value of the active animation * duration. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/min */ min?: string /** * The `max` attribute specifies the maximum value of the active animation * duration. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/max */ max?: string /** * The `restart` attribute specifies whether or not an animation can restart. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/restart */ restart?: SVGAnimationTimingRestartMode /** * The `repeatCount` attribute indicates the number of times an animation will * take place. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/repeatCount */ repeatCount?: SVGAnimationTimingRepeatCount /** * The `repeatDur` attribute specifies the total duration for repeating an * animation. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/repeatDur */ repeatDur?: SVGAnimationTimingRepeatDuration /** * The `fill` attribute defines the final state of the animation * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill#animate */ fill?: SVGAnimationTimingFillMode } export type SVGAnimationValueCalcMode = | 'discrete' | 'linear' | 'paced' | 'spline' export interface SVGAnimationValueAttributes { /** * The `calcMode` attribute specifies the interpolation mode for the animation. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/calcMode */ calcMode?: SVGAnimationValueCalcMode /** * The `values` attribute has different meanings, depending upon the context * where it's used, either it defines a sequence of values used over the * course of an animation, or it's a list of numbers for a color matrix, * which is interpreted differently depending on the type of color change * to be performed. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/values */ values?: string /** * The `keyTimes` attribute represents a list of time values used to control * the pacing of the animation. Each time in the list corresponds to a value * in the `values` attribute list, and defines when the value is used in the * animation. Each time value in the `keyTimes` list is specified as a * floating point value between `0` and `1` (inclusive), representing a * proportional offset into the duration of the animation element. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/keyTimes */ keyTimes?: string /** * The `keySplines` attribute defines a set of **Bézier curve** control * points associated with the keyTimes list, defining a cubic Bézier function * that controls interval pacing. * * This attribute is ignored unless the `calcMode` attribute is set to spline. * * If there are any errors in the `keySplines` specification (bad values, * too many or too few values), the animation will not occur. * * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/keySplines */ keySplines?: string /** * The `from` attribute indicates the initial value of the attribute that * will be modified during the animation. When used with the to attribute, * the animation will change the modified attribute from the `from` value to * the `to` value. When used with the `by` attribute, the animation will * change the attribute relatively from the `from` value by the value * specified in `by`. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/From */ from?: string | number /** * The `to` attribute indicates the final value of the attribute that will * be modified during the animation. The value of the attribute will change * between the `from` attribute value and this value. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/To */ to?: string | number /** * The `by` attribute specifies a relative offset value for an attribute * that will be modified during an animation. * * The starting value for the attribute is either indicated by specifying * it as value for the attribute given in the `attributeName` or the `from` * attribute. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/by */ by?: string | number } export type SVGAnimationAdditionAttributeAdditive = 'replace' | 'sum' export type SVGAnimationAdditionAttributeAccumulate = 'none' | 'sum' export interface SVGAnimationAdditionAttributes { /** * The `additive` attribute controls whether or not an animation is additive. * * It is frequently useful to define animation as an offset or delta to an * attribute's value, rather than as absolute values. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/additive */ additive?: SVGAnimationAdditionAttributeAdditive /** * The `accumulate` attribute controls whether or not an animation is * cumulative. * * It is frequently useful for repeated animations to build upon the * previous results, accumulating with each iteration. This attribute * said to the animation if the value is added to the previous animated * attribute's value on each iteration. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/accumulate */ accumulate?: SVGAnimationAdditionAttributeAccumulate }
the_stack
import { Injectable } from '@angular/core'; import { BaseParam } from './base-param'; import { EquipmentPiece } from '../../model/gearset/equipment-piece'; import { TeamcraftGearset } from '../../model/gearset/teamcraft-gearset'; import { MateriaService } from './materia.service'; import { EnvironmentService } from '../../core/environment.service'; import { combineLatest, EMPTY, Observable, of } from 'rxjs'; import { LazyDataFacade } from '../../lazy-data/+state/lazy-data.facade'; import { expand, last, map, shareReplay, switchMap } from 'rxjs/operators'; import { safeCombineLatest } from '../../core/rxjs/safe-combine-latest'; import { LazyItemStat } from '../../lazy-data/model/lazy-item-stat'; import { LazyItemSetBonus } from '../../lazy-data/model/lazy-item-set-bonus'; import { LazyMateria } from '../../lazy-data/model/lazy-materia'; import { Memoized } from '../../core/decorators/memoized'; @Injectable({ providedIn: 'root' }) export class StatsService { // Source: https://github.com/SapphireServer/Sapphire/blob/51d29df7ace88feaef1ef329ad3185ed4a5b4384/src/world/Math/CalcStats.cpp private static LEVEL_TABLE: number[][] = [ // MAIN,SUB,DIV,HP,ELMT,THREAT [1, 1, 1, 1, 1, 1], [20, 56, 56, 0, 52, 2], [21, 57, 57, 0, 54, 2], [22, 60, 60, 0, 56, 3], [24, 62, 62, 0, 58, 3], [26, 65, 65, 0, 60, 3], [27, 68, 68, 0, 62, 3], [29, 70, 70, 0, 64, 4], [31, 73, 73, 0, 66, 4], [33, 76, 76, 0, 68, 4], [35, 78, 78, 0, 70, 5], [36, 82, 82, 0, 73, 5], [38, 85, 85, 0, 75, 5], [41, 89, 89, 0, 78, 6], [44, 93, 93, 0, 81, 6], [46, 96, 96, 0, 84, 7], [49, 100, 100, 0, 86, 7], [52, 104, 104, 0, 89, 8], [54, 109, 109, 0, 93, 9], [57, 113, 113, 0, 95, 9], [60, 116, 116, 0, 98, 10], [63, 122, 122, 0, 102, 10], [67, 127, 127, 0, 105, 11], [71, 133, 133, 0, 109, 12], [74, 138, 138, 0, 113, 13], [78, 144, 144, 0, 117, 14], [81, 150, 150, 0, 121, 15], [85, 155, 155, 0, 125, 16], [89, 162, 162, 0, 129, 17], [92, 168, 168, 0, 133, 18], [97, 173, 173, 0, 137, 19], [101, 181, 181, 0, 143, 20], [106, 188, 188, 0, 148, 22], [110, 194, 194, 0, 153, 23], [115, 202, 202, 0, 159, 25], [119, 209, 209, 0, 165, 27], [124, 215, 215, 0, 170, 29], [128, 223, 223, 0, 176, 31], [134, 229, 229, 0, 181, 33], [139, 236, 236, 0, 186, 35], [144, 244, 244, 0, 192, 38], [150, 253, 253, 0, 200, 40], [155, 263, 263, 0, 207, 43], [161, 272, 272, 0, 215, 46], [166, 283, 283, 0, 223, 49], [171, 292, 292, 0, 231, 52], [177, 302, 302, 0, 238, 55], [183, 311, 311, 0, 246, 58], [189, 322, 322, 0, 254, 62], [196, 331, 331, 0, 261, 66], [202, 341, 341, 1700, 269, 70], [204, 342, 393, 1774, 270, 84], [205, 344, 444, 1851, 271, 99], [207, 345, 496, 1931, 273, 113], [209, 346, 548, 2015, 274, 128], [210, 347, 600, 2102, 275, 142], [212, 349, 651, 2194, 276, 157], [214, 350, 703, 2289, 278, 171], [215, 351, 755, 2388, 279, 186], [217, 352, 806, 2492, 280, 200], [218, 354, 858, 2600, 282, 215], [224, 355, 941, 2700, 283, 232], [228, 356, 1032, 2800, 284, 250], [236, 357, 1133, 2900, 286, 269], [244, 358, 1243, 3000, 287, 290], [252, 359, 1364, 3100, 288, 313], [260, 360, 1497, 3200, 290, 337], [268, 361, 1643, 3300, 292, 363], [276, 362, 1802, 3400, 293, 392], [284, 363, 1978, 3500, 294, 422], [292, 364, 2170, 3600, 295, 455], [296, 365, 2263, 3600, 466, 466], [300, 366, 2360, 3600, 295, 466], [305, 367, 2461, 3600, 295, 466], [310, 368, 2566, 3600, 295, 466], [315, 370, 2676, 3600, 295, 466], [320, 372, 2790, 3600, 295, 466], [325, 374, 2910, 3600, 295, 466], [330, 376, 3034, 3600, 295, 466], [335, 378, 3164, 3600, 295, 466], // Placeholder values for 6.0 [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569], [340, 380, 3300, 3600, 569, 569] ]; private static SUB_STATS: BaseParam[] = [ BaseParam.CRITICAL_HIT, BaseParam.DIRECT_HIT_RATE, BaseParam.SKILL_SPEED, BaseParam.SPELL_SPEED, BaseParam.TENACITY ]; private static MAIN_STATS: BaseParam[] = [ BaseParam.DETERMINATION, BaseParam.PIETY, BaseParam.VITALITY, BaseParam.STRENGTH, BaseParam.DEXTERITY, BaseParam.INTELLIGENCE, BaseParam.MIND ]; constructor(private lazyData: LazyDataFacade, private materiasService: MateriaService, private env: EnvironmentService) { } public getMaxValuesTable(job: number, equipmentPiece: EquipmentPiece): Observable<number[][]> { return combineLatest(this.getRelevantBaseStats(job) .map(baseParamId => { return this.getStartingValue(equipmentPiece, baseParamId).pipe( switchMap(startingValue => { return combineLatest([ of(baseParamId), this.materiasService.getTotalStat(startingValue, equipmentPiece, baseParamId), this.materiasService.getItemCapForStat(equipmentPiece.itemId, baseParamId), of(startingValue) ]); }) ); }) ); } public getStartingValue(equipmentPiece: EquipmentPiece, baseParamId: number): Observable<number> { return this.lazyData.getRow('itemStats', equipmentPiece.itemId, []).pipe( map(itemStats => { const matchingStat: any = itemStats.find((stat: any) => stat.ID === baseParamId); if (matchingStat) { if (equipmentPiece.hq) { return matchingStat.HQ; } else { return matchingStat.NQ; } } return 0; }) ); } public getStats(set: TeamcraftGearset, level: number, tribe: number, food?: any): Observable<{ id: number, value: number }[]> { return safeCombineLatest(this.getRelevantBaseStats(set.job).map(stat => { return this.getBaseValue(stat, set.job, level, tribe).pipe( map(value => { return { id: stat, value }; }) ); })).pipe( switchMap(statsSeed => { return safeCombineLatest( Object.keys(set) .filter(key => this.env.gameVersion < 6 || key !== 'belt') .map(key => set[key]) .filter(value => value && value.itemId !== undefined) .map((value: EquipmentPiece) => { return combineLatest([this.lazyData.getRow('itemStats', value.itemId, []), this.lazyData.getRow('itemSetBonuses', value.itemId, null)]).pipe( map(([itemStats, bonuses]) => [value, itemStats, bonuses]) ); }) ).pipe( switchMap((pieces: Array<[EquipmentPiece, LazyItemStat[], LazyItemSetBonus]>) => { return safeCombineLatest(pieces.map(([piece, ...rest]) => { return safeCombineLatest( piece.materias .filter(materia => materia > 0) .map((materia, index) => combineLatest([this.materiasService.getMateria(materia), this.materiasService.getMateriaBonus(piece, materia, index)])) ).pipe( map(materias => { return [piece, materias, ...rest]; }) ); })); }), switchMap((pieces: Array<[EquipmentPiece, [LazyMateria, { overcapped: boolean, value: number }][], LazyItemStat[], LazyItemSetBonus]>) => { const statsToCompute: Record<number, Observable<number>> = {}; pieces.forEach(([equipmentPiece, materias, itemStats, itemSetBonuses]) => { itemStats .filter((stat) => stat.ID !== undefined) .forEach(stat => { if (!statsToCompute[stat.ID]) { statsToCompute[stat.ID] = this.getBaseValue(stat.ID, set.job, level, tribe); } }); materias.forEach(([materia, bonus]) => { if (!statsToCompute[materia.baseParamId]) { statsToCompute[materia.baseParamId] = this.getBaseValue(materia.baseParamId, set.job, level, tribe); } }); if (itemSetBonuses) { itemSetBonuses.bonuses.forEach((bonus) => { if (!statsToCompute[bonus.baseParam]) { statsToCompute[bonus.baseParam] = this.getBaseValue(bonus.baseParam, set.job, level, tribe); } }); } }); return safeCombineLatest(Object.entries(statsToCompute).map(([key, observable]) => { return observable.pipe( map(value => [key, value]) ); })).pipe( map(res => { const baseValues = res.reduce((acc, [key, value]) => { return { ...acc, [key]: value }; }, {}); return { pieces, baseValues }; }) ); }), map(({ pieces, baseValues }) => { return pieces.reduce((acc, [equipmentPiece, materias, itemStats, itemSetBonuses]) => { if (itemSetBonuses) { acc.possibleSetBonuses.push(itemSetBonuses); } if (!itemStats) { return acc; } itemStats .filter((stat) => stat.ID !== undefined) .forEach((stat) => { let statsRow = acc.stats.find(s => s.id === stat.ID); if (statsRow === undefined) { acc.stats.push({ id: stat.ID, value: baseValues[stat.ID] }); statsRow = acc.stats[acc.stats.length - 1]; } if (equipmentPiece.hq) { statsRow.value += stat.HQ; } else { statsRow.value += stat.NQ; } }); materias.forEach(([materia, bonus]) => { let statsRow = acc.stats.find(s => s.id === materia.baseParamId); if (statsRow === undefined) { acc.stats.push({ id: materia.baseParamId, value: baseValues[materia.baseParamId] }); statsRow = acc.stats[acc.stats.length - 1]; } statsRow.value += bonus.value; }); return acc; }, { possibleSetBonuses: [], stats: statsSeed, baseValues }); }), map(acc => { const stats = acc.stats; const baseValues = acc.baseValues; if (food) { Object.values<any>(food.Bonuses).forEach(bonus => { let bonusValue: number; const stat = stats.find(s => s.id === bonus.ID); if (bonus.Relative) { const baseValue = stat ? stat.value : 0; const multiplier = (food.HQ ? bonus.ValueHQ : bonus.Value) / 100; const max = food.HQ ? bonus.MaxHQ : bonus.Max; bonusValue = Math.min(Math.floor(baseValue * multiplier), max); } else { bonusValue = food.HQ ? bonus.ValueHQ : bonus.Value; } if (stat) { stat.value += bonusValue; } }); } // Process set bonuses acc.possibleSetBonuses.forEach(possibleSetBonus => { const sameSetPieces = acc.possibleSetBonuses.filter(b => b.itemSeriesId === possibleSetBonus.itemSeriesId).length; possibleSetBonus.bonuses.forEach(bonus => { if (sameSetPieces >= bonus.amountRequired) { let statsRow = stats.find(s => s.id === bonus.baseParam); if (statsRow === undefined) { stats.push({ id: bonus.baseParam, value: baseValues[bonus.baseParamId] }); statsRow = stats[stats.length - 1]; } statsRow.value += bonus.value; } }); }); if (set.job >= 8 && set.job <= 18) { // Nobody cares about vitality for DoH/W and it lets us have more space if we take it out return stats.filter(s => s.id !== BaseParam.VITALITY); } return stats; }) ); }) ); } @Memoized() public getBaseValue(baseParamId: number, job: number, level: number, tribe: number): Observable<number> { if (baseParamId === BaseParam.CP) { return of(180); } if (baseParamId === BaseParam.GP) { return of(400); } return combineLatest([ this.getModifier(baseParamId, job), this.getTribeBonus(baseParamId, tribe) ]).pipe( map(([modifier, tribeBonus]) => { if (StatsService.MAIN_STATS.indexOf(baseParamId) > -1) { return Math.floor(StatsService.LEVEL_TABLE[level][0] * modifier) + tribeBonus + (this.getMainStat(job) === baseParamId ? this.getMainStatBonus(level) : 0); } if (StatsService.SUB_STATS.indexOf(baseParamId) > -1) { return Math.floor(StatsService.LEVEL_TABLE[level][1] * modifier) + tribeBonus + (this.getMainStat(job) === baseParamId ? this.getMainStatBonus(level) : 0); } return 0; }), shareReplay(1) ); } public getRelevantBaseStats(job: number): number[] { switch (job) { // DoH case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: return [BaseParam.CRAFTSMANSHIP, BaseParam.CONTROL, BaseParam.CP]; // DoL case 16: case 17: case 18: return [BaseParam.GATHERING, BaseParam.PERCEPTION, BaseParam.GP]; // Tanks case 1: case 3: case 19: case 21: case 32: case 37: return [BaseParam.STRENGTH, BaseParam.DIRECT_HIT_RATE, BaseParam.CRITICAL_HIT, BaseParam.DETERMINATION, BaseParam.SKILL_SPEED, BaseParam.VITALITY, BaseParam.TENACITY]; // STR-based DPS case 2: case 4: case 20: case 22: case 34: case 39: return [BaseParam.STRENGTH, BaseParam.DIRECT_HIT_RATE, BaseParam.CRITICAL_HIT, BaseParam.DETERMINATION, BaseParam.SKILL_SPEED, BaseParam.VITALITY]; // DEX-based DPS case 5: case 23: case 29: case 30: case 31: case 38: return [BaseParam.DEXTERITY, BaseParam.DIRECT_HIT_RATE, BaseParam.CRITICAL_HIT, BaseParam.DETERMINATION, BaseParam.SKILL_SPEED, BaseParam.VITALITY]; // Healers case 6: case 24: case 28: case 33: case 40: return [BaseParam.MIND, BaseParam.DIRECT_HIT_RATE, BaseParam.CRITICAL_HIT, BaseParam.DETERMINATION, BaseParam.SPELL_SPEED, BaseParam.PIETY, BaseParam.VITALITY]; // Caster DPS case 7: case 25: case 26: case 27: case 35: case 36: return [BaseParam.INTELLIGENCE, BaseParam.DIRECT_HIT_RATE, BaseParam.CRITICAL_HIT, BaseParam.DETERMINATION, BaseParam.SPELL_SPEED, BaseParam.PIETY, BaseParam.VITALITY]; } return []; } public getMainStat(job: number): BaseParam { switch (job) { // DoH case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: return BaseParam.CRAFTSMANSHIP; // DoL case 16: case 17: case 18: return BaseParam.GATHERING; // Tanks case 1: case 3: case 19: case 21: case 32: case 37: return BaseParam.VITALITY; // STR-based DPS case 2: case 4: case 20: case 22: case 34: case 39: return BaseParam.STRENGTH; // DEX-based DPS case 5: case 23: case 29: case 30: case 31: case 38: return BaseParam.DEXTERITY; // Healers case 6: case 24: case 28: case 33: case 40: return BaseParam.MIND; // Caster DPS case 7: case 25: case 26: case 27: case 35: case 36: return BaseParam.INTELLIGENCE; } return 0; } public getStatsDisplay(set: TeamcraftGearset, level: number, tribe: number, food?: any): Observable<{ baseParamIds: number[], name: string, value: number, next?: number, previous?: number, suffix?: string }[]> { return this.getAvgIlvl(set).pipe( switchMap(avgIlvl => { const display: { baseParamIds: number[], name: string, value: number, next?: number, previous?: number, suffix?: string }[] = [ { baseParamIds: [0], name: 'Ilvl', value: avgIlvl } ]; if (set.isCombatSet()) { return this.getStats(set, level, tribe, food).pipe( switchMap(stats => { return combineLatest([ { baseParamIds: [BaseParam.VITALITY], name: 'HP' }, { baseParamIds: [BaseParam.DIRECT_HIT_RATE], name: 'Direct_hit_chances', suffix: '%' }, { baseParamIds: [BaseParam.CRITICAL_HIT], name: 'Critical_hit_chances', suffix: '%' }, { baseParamIds: [BaseParam.CRITICAL_HIT], name: 'Critical_hit_multiplier', suffix: '%' }, { baseParamIds: [BaseParam.DETERMINATION], name: 'Determination_bonus', suffix: '%' }, { baseParamIds: [BaseParam.SKILL_SPEED, BaseParam.SPELL_SPEED], name: 'GCD', suffix: 's' } ].map(stat => { return combineLatest([ this.getStatValue(stat.name, level, set.job, stats), this.getNextBreakpoint(stat.name, level, set.job, stats), this.getPreviousBreakpoint(stat.name, level, set.job, stats) ]).pipe( map(([value, next, previous]) => { return { ...stat, value, next, previous }; }) ); })).pipe( map(statsDisplay => { return [ ...display, ...statsDisplay ]; }) ); }) ); } return of(display); }) ); } /** * Stats computing methods here, source: http://allaganstudies.akhmorning.com/guide/parameters/ */ public getAvgIlvl(set: TeamcraftGearset): Observable<number> { return this.lazyData.getEntry('ilvls').pipe( map(ilvls => { const withoutOffHand = ['mainHand', 'head', 'earRings', 'chest', 'necklace', 'gloves', 'bracelet', 'belt', 'ring1', 'legs', 'ring2', 'feet'] .filter(key => set[key]) .reduce((acc, row) => { return acc + ilvls[set[row].itemId]; }, 0); if (set.offHand) { return Math.floor((withoutOffHand + ilvls[set.offHand.itemId]) / 12); } return Math.floor(withoutOffHand / 11); }) ); } private getNextBreakpoint(displayName: string, level: number, job: number, stats: { id: number, value: number }[]): Observable<number> { return this.getStatValue(displayName, level, job, stats).pipe( map(baseValue => ([baseValue, 0, 0])), expand(([baseValue, currentValue, currentBonus]) => { if (Math.abs(currentBonus) < 100 && currentValue <= baseValue) { currentBonus++; return this.getStatValue(displayName, level, job, stats, currentBonus).pipe( map(newValue => ([baseValue, newValue, currentBonus])) ); } return EMPTY; }), last(), map(([, , bonus]) => bonus) ); } private getPreviousBreakpoint(displayName: string, level: number, job: number, stats: { id: number, value: number }[]): Observable<number> { return this.getStatValue(displayName, level, job, stats).pipe( map(baseValue => ([baseValue, Infinity, 0])), expand(([baseValue, currentValue, currentBonus]) => { if (Math.abs(currentBonus) < 100 && currentValue >= baseValue) { currentBonus--; return this.getStatValue(displayName, level, job, stats, currentBonus).pipe( map(newValue => ([baseValue, newValue, currentBonus])) ); } return EMPTY; }), last(), map(([, , bonus]) => bonus) ); } private getModifier(baseParamId: number, job: number): Observable<number> { return this.lazyData.getRow('classJobsModifiers', job).pipe( map(modifiers => { switch (baseParamId) { case BaseParam.DEXTERITY: return modifiers.ModifierDexterity / 100; case BaseParam.HP: return modifiers.ModifierHitPoints / 100; case BaseParam.INTELLIGENCE: return modifiers.ModifierIntelligence / 100; case BaseParam.MP: return modifiers.ModifierManaPoints / 100; case BaseParam.MIND: return modifiers.ModifierMind / 100; case BaseParam.PIETY: return modifiers.ModifierPiety / 100; case BaseParam.STRENGTH: return modifiers.ModifierStrength / 100; case BaseParam.VITALITY: return modifiers.ModifierVitality / 100; default: return 1; } }) ); } private getMainStatBonus(level: number): number { if (level >= 70) { return 48; } if (level >= 60) { // Probably not accurate, seems like it's one value per extension return 48; } if (level >= 50) { // Probably not accurate, seems like it's one value per extension return 48; } // Probably not accurate, seems like it's one value per extension return 8; } private getTribeBonus(baseParamId: number, tribe: number): Observable<number> { return this.lazyData.getRow('tribes', tribe).pipe( map(tribeData => { const abbr = this.getStatAbbr(baseParamId); if (abbr === null) { return 0; } return +tribeData[abbr]; }) ); } private getStatAbbr(baseParamId: number): string | null { switch (baseParamId) { case BaseParam.HP: return 'Hp'; case BaseParam.INTELLIGENCE: return 'INT'; case BaseParam.MIND: return 'MND'; case BaseParam.MP: return 'Mp'; case BaseParam.PIETY: return 'PIE'; case BaseParam.STRENGTH: return 'STR'; case BaseParam.VITALITY: return 'VIT'; case BaseParam.DEXTERITY: return 'DEX'; } return null; } private getStatValue(displayName: string, level: number, job: number, stats: { id: number, value: number }[], statBonus = 0): Observable<number> { switch (displayName) { case 'HP': return this.getMaxHp(job, level, (stats.find(stat => stat.id === BaseParam.VITALITY)?.value || 0) + statBonus); case 'Direct_hit_chances': return of(Math.floor(this.getDirectHitChances(level, (stats.find(stat => stat.id === BaseParam.DIRECT_HIT_RATE)?.value || 0) + statBonus)) / 10); case 'Critical_hit_chances': return of(Math.floor(this.getCriticalHitChances(level, (stats.find(stat => stat.id === BaseParam.CRITICAL_HIT)?.value || 0) + statBonus)) / 10); case 'Critical_hit_multiplier': return of(Math.floor(this.getCriticalMultiplier(level, (stats.find(stat => stat.id === BaseParam.CRITICAL_HIT)?.value || 0) + statBonus)) / 10); case 'Determination_bonus': return of(Math.floor(this.getDeterminationBonus(level, (stats.find(stat => stat.id === BaseParam.DETERMINATION)?.value || 0) + statBonus)) / 10); case 'GCD': return of(Math.floor(this.getGCD(level, (stats.find(stat => stat.id === BaseParam.SKILL_SPEED || stat.id === BaseParam.SPELL_SPEED)?.value || 0) + statBonus)) / 1000); default: return of(0); } } private getMaxHp(job: number, level: number, vitality: number): Observable<number> { if (level > this.env.maxLevel) { return of(0); } return this.lazyData.getRow('classJobsModifiers', job).pipe( map(modifiers => { const levelModHP = StatsService.LEVEL_TABLE[level][3]; const levelModMain = StatsService.LEVEL_TABLE[level][0]; const jobMod = modifiers.ModifierHitPoints; return Math.floor(levelModHP * (jobMod / 100)) + Math.floor((vitality - levelModMain) * 20.5); }) ); } private getDirectHitChances(level: number, directHit: number): number { const levelModSub = StatsService.LEVEL_TABLE[level][1]; const levelModDiv = StatsService.LEVEL_TABLE[level][2]; return 550 * (directHit - levelModSub) / levelModDiv; } private getCriticalHitChances(level: number, critical: number): number { const levelModSub = StatsService.LEVEL_TABLE[level][1]; const levelModDiv = StatsService.LEVEL_TABLE[level][2]; return 200 * (critical - levelModSub) / levelModDiv + 50; } private getGCD(level: number, speed: number): number { const levelModSub = StatsService.LEVEL_TABLE[level][1]; const levelModDiv = StatsService.LEVEL_TABLE[level][2]; return (1000 - Math.floor(130 * (speed - levelModSub) / levelModDiv)) * 2.5; } private getCriticalMultiplier(level: number, critical: number): number { const levelModSub = StatsService.LEVEL_TABLE[level][1]; const levelModDiv = StatsService.LEVEL_TABLE[level][2]; return 200 * (critical - levelModSub) / levelModDiv + 1400; } private getDeterminationBonus(level: number, determination: number): number { const levelModMain = StatsService.LEVEL_TABLE[level][0]; const levelModDiv = StatsService.LEVEL_TABLE[level][2]; return 130 * (determination - levelModMain) / levelModDiv + 1000; } }
the_stack
import Entity from "../entity/entity"; import { Search } from "./search"; import Where from "./where"; import { CircleFunction } from "./where-point"; /** * Interface with all the methods from all the concrete * classes under {@link WhereField}. */ interface WhereField<TEntity> extends Where { /** * Adds an equals comparison to the query. * * NOTE: this function is not available for strings where full-text * search is enabled. In that scenario, use `.match`. * @param value The value to be compared * @returns The {@link Search} that was called to create this {@link WhereField}. */ eq(value: string | number | boolean | Date): Search<TEntity>; /** * Adds an equals comparison to the query. * * NOTE: this function is not available for strings where full-text * search is enabled. In that scenario, use `.match`. * @param value The value to be compared * @returns The {@link Search} that was called to create this {@link WhereField}. */ equal(value: string | number | boolean | Date): Search<TEntity>; /** * Adds an equals comparison to the query. * * NOTE: this function is not available for strings where full-text * search is enabled. In that scenario, use `.match`. * @param value The value to be compared * @returns The {@link Search} that was called to create this {@link WhereField}. */ equals(value: string | number | boolean | Date): Search<TEntity>; /** * Adds an equals comparison to the query. * * NOTE: this function is not available for strings where full-text * search is enabled. In that scenario, use `.match`. * @param value The value to be compared * @returns The {@link Search} that was called to create this {@link WhereField}. */ equalTo(value: string | number | boolean | Date): Search<TEntity>; /** * Adds a full-text search comparison to the query. * @param value The word or phrase sought. * @returns The {@link Search} that was called to create this {@link WhereField}. */ match(value: string | number | boolean): Search<TEntity>; /** * Adds a full-text search comparison to the query. * @param value The word or phrase sought. * @returns The {@link Search} that was called to create this {@link WhereField}. */ matches(value: string | number | boolean): Search<TEntity>; /** * Adds a full-text search comparison to the query that matches an exact word or phrase. * @param value The word or phrase sought. * @returns The {@link Search} that was called to create this {@link WhereField}. */ matchExact(value: string | number | boolean): Search<TEntity>; /** * Adds a full-text search comparison to the query that matches an exact word or phrase. * @param value The word or phrase sought. * @returns The {@link Search} that was called to create this {@link WhereField}. */ matchExactly(value: string | number | boolean): Search<TEntity>; /** * Adds a full-text search comparison to the query that matches an exact word or phrase. * @param value The word or phrase sought. * @returns The {@link Search} that was called to create this {@link WhereField}. */ matchesExactly(value: string | number | boolean): Search<TEntity>; /** * Makes a call to {@link WhereField.match} a {@link WhereField.matchExact} call. Calling * this multiple times will have no effect. * @returns this. */ readonly exact: WhereField<TEntity>; /** * Makes a call to {@link WhereField.match} a {@link WhereField.matchExact} call. Calling * this multiple times will have no effect. * @returns this. */ readonly exactly: WhereField<TEntity>; /** * Adds a boolean match with a value of `true` to the query. * @returns The {@link Search} that was called to create this {@link WhereField}. */ true(): Search<TEntity>; /** * Adds a boolean match with a value of `false` to the query. * @returns The {@link Search} that was called to create this {@link WhereField}. */ false(): Search<TEntity>; /** * Adds a greater than comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ gt(value: string | number | Date): Search<TEntity>; /** * Adds a greater than comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ greaterThan(value: string | number | Date): Search<TEntity>; /** * Adds a greater than or equal to comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ gte(value: string | number | Date): Search<TEntity>; /** * Adds a greater than or equal to comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ greaterThanOrEqualTo(value: string | number | Date): Search<TEntity>; /** * Adds a less than comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ lt(value: string | number | Date): Search<TEntity>; /** * Adds a less than comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ lessThan(value: string | number | Date): Search<TEntity>; /** * Adds a less than or equal to comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ lte(value: string | number | Date): Search<TEntity>; /** * Adds a less than or equal to comparison against a field to the search query. * @param value The value to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ lessThanOrEqualTo(value: string | number | Date): Search<TEntity>; /** * Adds an inclusive range comparison against a field to the search query. * @param lower The lower bound of the range. * @param upper The upper bound of the range. * @returns The {@link Search} that was called to create this {@link WhereField}. */ between(lower: string | number | Date, upper: string | number | Date): Search<TEntity>; /** * Adds a whole-string match for a value within a string array to the search query. * @param value The string to be matched. * @returns The {@link Search} that was called to create this {@link WhereField}. */ contain(value: string): Search<TEntity>; /** * Adds a whole-string match for a value within a string array to the search query. * @param value The string to be matched. * @returns The {@link Search} that was called to create this {@link WhereField}. */ contains(value: string): Search<TEntity>; /** * Adds a whole-string match against a string array to the query. If any of the provided * strings in `value` is matched in the array, this matched. * @param value An array of strings that you want to match one of. * @returns The {@link Search} that was called to create this {@link WhereField}. */ containOneOf(...value: Array<string>): Search<TEntity>; /** * Adds a whole-string match against a string array to the query. If any of the provided * strings in `value` is matched in the array, this matched. * @param value An array of strings that you want to match one of. * @returns The {@link Search} that was called to create this {@link WhereField}. */ containsOneOf(...value: Array<string>): Search<TEntity>; /** * Adds a search for points that fall within a defined circle. * @param circleFn A function that returns a {@link Circle} instance defining the search area. * @returns The {@link Search} that was called to create this {@link WhereField}. */ inCircle(circleFn: CircleFunction): Search<TEntity>; /** * Adds a search for points that fall within a defined radius. * @param circleFn A function that returns a {@link Circle} instance defining the search area. * @returns The {@link Search} that was called to create this {@link WhereField}. */ inRadius(circleFn: CircleFunction): Search<TEntity>; /** * Add a search for an exact UTC datetime to the query. * @param value The datetime to match. * @returns The {@link Search} that was called to create this {@link WhereField}. */ on(value: string | number | Date): Search<TEntity>; /** * Add a search that matches all datetimes *before* the provided UTC datetime to the query. * @param value The datetime to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ before(value: string | number | Date): Search<TEntity>; /** * Add a search that matches all datetimes *after* the provided UTC datetime to the query. * @param value The datetime to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ after(value: string | number | Date): Search<TEntity>; /** * Add a search that matches all datetimes *on or before* the provided UTC datetime to the query. * @param value The datetime to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ onOrBefore(value: string | number | Date): Search<TEntity>; /** * Add a search that matches all datetimes *on or after* the provided UTC datetime to the query. * @param value The datetime to compare against. * @returns The {@link Search} that was called to create this {@link WhereField}. */ onOrAfter(value: string | number | Date): Search<TEntity>; } /** * Abstract base class that all fields you want to filter * with extend. When you call {@link Search.where}, a * subclass of this is returned. */ abstract class WhereField<TEntity extends Entity> { private negated: boolean = false; /** @internal */ protected search: Search<TEntity>; /** @internal */ protected field: String; /** @internal */ constructor(search: Search<TEntity>, field: string) { this.search = search; this.field = field; } /** * Returns the current instance. Syntactic sugar to make your code more fluent. * @returns this */ get is() { return this; } /** * Returns the current instance. Syntactic sugar to make your code more fluent. * @returns this */ get does() { return this; } /** * Negates the query on the field, cause it to match when the condition is * *not* met. Calling this multiple times will negate the negation. * @returns this */ get not() { this.negate(); return this; } abstract toString(): string; /** @internal */ protected negate() { this.negated = !this.negated; } /** @internal */ protected buildQuery(valuePortion: string): string { const negationPortion = this.negated ? '-' : ''; const fieldPortion = this.field; return `(${negationPortion}@${fieldPortion}:${valuePortion})`; } } export default WhereField;
the_stack
declare module '@stripe/stripe-js' { /** * The Source object. */ interface Source { /** * Unique identifier for the object. */ id: string; /** * String representing the object's type. Objects of the same type share the same value. */ object: 'source'; ach_credit_transfer?: Source.AchCreditTransfer; ach_debit?: Source.AchDebit; acss_debit?: Source.AcssDebit; alipay?: Source.Alipay; /** * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for `single_use` sources. */ amount: number | null; au_becs_debit?: Source.AuBecsDebit; bancontact?: Source.Bancontact; card?: Source.Card; card_present?: Source.CardPresent; /** * The client secret of the source. Used for client-side retrieval using a publishable key. */ client_secret: string; code_verification?: Source.CodeVerification; /** * Time at which the object was created. Measured in seconds since the Unix epoch. */ created: number; /** * Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. This is the currency for which the source will be chargeable once ready. Required for `single_use` sources. */ currency: string | null; /** * The ID of the customer to which this source is attached. This will not be present when the source has not been attached to a customer. */ customer?: string; eps?: Source.Eps; /** * The authentication `flow` of the source. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. */ flow: string; giropay?: Source.Giropay; ideal?: Source.Ideal; klarna?: Source.Klarna; /** * Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. */ livemode: boolean; /** * Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. */ metadata: Metadata | null; multibanco?: Source.Multibanco; /** * Information about the owner of the payment instrument that may be used or required by particular source types. */ owner: Source.Owner | null; p24?: Source.P24; receiver?: Source.Receiver; redirect?: Source.Redirect; sepa_credit_transfer?: Source.SepaCreditTransfer; sepa_debit?: Source.SepaDebit; sofort?: Source.Sofort; source_order?: Source.SourceOrder; /** * Extra information about a source. This will appear on your customer's statement every time you charge the source. */ statement_descriptor: string | null; /** * The status of the source, one of `canceled`, `chargeable`, `consumed`, `failed`, or `pending`. Only `chargeable` sources can be used to create a charge. */ status: string; three_d_secure?: Source.ThreeDSecure; /** * The `type` of the source. The `type` is a payment method, one of `ach_credit_transfer`, `ach_debit`, `alipay`, `bancontact`, `card`, `card_present`, `eps`, `giropay`, `ideal`, `multibanco`, `klarna`, `p24`, `sepa_debit`, `sofort`, `three_d_secure`, or `wechat`. An additional hash is included on the source with a name matching this value. It contains additional information specific to the [payment method](https://stripe.com/docs/sources) used. */ type: Source.Type; /** * Either `reusable` or `single_use`. Whether this source should be reusable or not. Some source types may or may not be reusable by construction, while others may leave the option at creation. If an incompatible value is passed, an error will be returned. */ usage: string | null; wechat?: Source.Wechat; } namespace Source { interface AchCreditTransfer { account_number?: string | null; bank_name?: string | null; fingerprint?: string | null; refund_account_holder_name?: string | null; refund_account_holder_type?: string | null; refund_routing_number?: string | null; routing_number?: string | null; swift_code?: string | null; } interface AchDebit { bank_name?: string | null; country?: string | null; fingerprint?: string | null; last4?: string | null; routing_number?: string | null; type?: string | null; } interface AcssDebit { bank_address_city?: string | null; bank_address_line_1?: string | null; bank_address_line_2?: string | null; bank_address_postal_code?: string | null; bank_name?: string | null; category?: string | null; country?: string | null; fingerprint?: string | null; last4?: string | null; routing_number?: string | null; } interface Alipay { data_string?: string | null; native_url?: string | null; statement_descriptor?: string | null; } interface AuBecsDebit { bsb_number?: string | null; fingerprint?: string | null; last4?: string | null; } interface Bancontact { bank_code?: string | null; bank_name?: string | null; bic?: string | null; iban_last4?: string | null; preferred_language?: string | null; statement_descriptor?: string | null; } interface Card { address_line1_check?: string | null; address_zip_check?: string | null; brand?: string | null; country?: string | null; cvc_check?: string | null; description?: string; dynamic_last4?: string | null; exp_month?: number | null; exp_year?: number | null; fingerprint?: string; funding?: string | null; iin?: string; issuer?: string; last4?: string | null; name?: string | null; three_d_secure?: string; tokenization_method?: string | null; } interface CardPresent { application_cryptogram?: string; application_preferred_name?: string; authorization_code?: string | null; authorization_response_code?: string; brand?: string | null; country?: string | null; cvm_type?: string; data_type?: string | null; dedicated_file_name?: string; description?: string; emv_auth_data?: string; evidence_customer_signature?: string | null; evidence_transaction_certificate?: string | null; exp_month?: number | null; exp_year?: number | null; fingerprint?: string; funding?: string | null; iin?: string; issuer?: string; last4?: string | null; pos_device_id?: string | null; pos_entry_mode?: string; read_method?: string | null; reader?: string | null; terminal_verification_results?: string; transaction_status_information?: string; } interface CodeVerification { /** * The number of attempts remaining to authenticate the source object with a verification code. */ attempts_remaining: number; /** * The status of the code verification, either `pending` (awaiting verification, `attempts_remaining` should be greater than 0), `succeeded` (successful verification) or `failed` (failed verification, cannot be verified anymore as `attempts_remaining` should be 0). */ status: string; } interface Eps { reference?: string | null; statement_descriptor?: string | null; } interface Giropay { bank_code?: string | null; bank_name?: string | null; bic?: string | null; statement_descriptor?: string | null; } interface Ideal { bank?: string | null; bic?: string | null; iban_last4?: string | null; statement_descriptor?: string | null; } interface Klarna { background_image_url?: string; client_token?: string | null; first_name?: string; last_name?: string; locale?: string; logo_url?: string; page_title?: string; pay_later_asset_urls_descriptive?: string; pay_later_asset_urls_standard?: string; pay_later_name?: string; pay_later_redirect_url?: string; pay_now_asset_urls_descriptive?: string; pay_now_asset_urls_standard?: string; pay_now_name?: string; pay_now_redirect_url?: string; pay_over_time_asset_urls_descriptive?: string; pay_over_time_asset_urls_standard?: string; pay_over_time_name?: string; pay_over_time_redirect_url?: string; payment_method_categories?: string; purchase_country?: string; purchase_type?: string; redirect_url?: string; shipping_first_name?: string; shipping_last_name?: string; } interface Multibanco { entity?: string | null; reference?: string | null; refund_account_holder_address_city?: string | null; refund_account_holder_address_country?: string | null; refund_account_holder_address_line1?: string | null; refund_account_holder_address_line2?: string | null; refund_account_holder_address_postal_code?: string | null; refund_account_holder_address_state?: string | null; refund_account_holder_name?: string | null; refund_iban?: string | null; } interface Owner { /** * Owner's address. */ address: Address | null; /** * Owner's email address. */ email: string | null; /** * Owner's full name. */ name: string | null; /** * Owner's phone number (including extension). */ phone: string | null; /** * Verified owner's address. Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. */ verified_address: Address | null; /** * Verified owner's email address. Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. */ verified_email: string | null; /** * Verified owner's full name. Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. */ verified_name: string | null; /** * Verified owner's phone number (including extension). Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. */ verified_phone: string | null; } interface P24 { reference?: string | null; } interface Receiver { /** * The address of the receiver source. This is the value that should be communicated to the customer to send their funds to. */ address: string | null; /** * The total amount that was charged by you. The amount charged is expressed in the source's currency. */ amount_charged: number; /** * The total amount received by the receiver source. `amount_received = amount_returned + amount_charged` is true at all time. The amount received is expressed in the source's currency. */ amount_received: number; /** * The total amount that was returned to the customer. The amount returned is expressed in the source's currency. */ amount_returned: number; /** * Type of refund attribute method, one of `email`, `manual`, or `none`. */ refund_attributes_method: string; /** * Type of refund attribute status, one of `missing`, `requested`, or `available`. */ refund_attributes_status: string; } interface Redirect { /** * The failure reason for the redirect, either `user_abort` (the customer aborted or dropped out of the redirect flow), `declined` (the authentication failed or the transaction was declined), or `processing_error` (the redirect failed due to a technical error). Present only if the redirect status is `failed`. */ failure_reason: string | null; /** * The URL you provide to redirect the customer to after they authenticated their payment. */ return_url: string; /** * The status of the redirect, either `pending` (ready to be used by your customer to authenticate the transaction), `succeeded` (succesful authentication, cannot be reused) or `not_required` (redirect should not be used) or `failed` (failed authentication, cannot be reused). */ status: string; /** * The URL provided to you to redirect a customer to as part of a `redirect` authentication flow. */ url: string; } interface SepaCreditTransfer { bank_name?: string | null; bic?: string | null; iban?: string | null; refund_account_holder_address_city?: string | null; refund_account_holder_address_country?: string | null; refund_account_holder_address_line1?: string | null; refund_account_holder_address_line2?: string | null; refund_account_holder_address_postal_code?: string | null; refund_account_holder_address_state?: string | null; refund_account_holder_name?: string | null; refund_iban?: string | null; } interface SepaDebit { bank_code?: string | null; branch_code?: string | null; country?: string | null; fingerprint?: string | null; last4?: string | null; mandate_reference?: string | null; mandate_url?: string | null; } interface Sofort { bank_code?: string | null; bank_name?: string | null; bic?: string | null; country?: string | null; iban_last4?: string | null; preferred_language?: string | null; statement_descriptor?: string | null; } interface SourceOrder { /** * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the order. */ amount: number; /** * Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). */ currency: string; /** * The email address of the customer placing the order. */ email?: string; /** * List of items constituting the order. */ items: Array<SourceOrder.Item> | null; shipping?: SourceOrder.Shipping; } namespace SourceOrder { interface Item { /** * The amount (price) for this order item. */ amount: number | null; /** * This currency of this order item. Required when `amount` is present. */ currency: string | null; /** * Human-readable description for this order item. */ description: string | null; /** * The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. */ quantity?: number; /** * The type of this order item. Must be `sku`, `tax`, or `shipping`. */ type: string | null; } interface Shipping { address?: Address; /** * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. */ carrier?: string | null; /** * Recipient name. */ name?: string | null; /** * Recipient phone (including extension). */ phone?: string | null; /** * The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. */ tracking_number?: string | null; } } interface ThreeDSecure { address_line1_check?: string | null; address_zip_check?: string | null; authenticated?: boolean | null; brand?: string | null; card?: string | null; country?: string | null; customer?: string | null; cvc_check?: string | null; description?: string; dynamic_last4?: string | null; exp_month?: number | null; exp_year?: number | null; fingerprint?: string; funding?: string | null; iin?: string; issuer?: string; last4?: string | null; name?: string | null; three_d_secure?: string; tokenization_method?: string | null; } type Type = | 'ach_credit_transfer' | 'ach_debit' | 'acss_debit' | 'alipay' | 'au_becs_debit' | 'bancontact' | 'card' | 'card_present' | 'eps' | 'giropay' | 'ideal' | 'klarna' | 'multibanco' | 'p24' | 'sepa_credit_transfer' | 'sepa_debit' | 'sofort' | 'three_d_secure' | 'wechat'; interface Wechat { prepay_id?: string; qr_code_url?: string | null; statement_descriptor?: string; } } interface SourceCreateParams { /** * Amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for `single_use` sources. Not supported for `receiver` type sources, where charge amount may not be specified until funds land. */ amount?: number; /** * Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. This is the currency for which the source will be chargeable once ready. */ currency?: string; /** * The `Customer` to whom the original source is attached to. Must be set when the original source is not a `Source` (e.g., `Card`). */ customer?: string; /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; /** * The authentication `flow` of the source to create. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. It is generally inferred unless a type supports multiple flows. */ flow?: SourceCreateParams.Flow; /** * Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. */ mandate?: SourceCreateParams.Mandate; metadata?: MetadataParam; /** * The source to share. */ original_source?: string; /** * Information about the owner of the payment instrument that may be used or required by particular source types. */ owner?: SourceCreateParams.Owner; /** * Optional parameters for the receiver flow. Can be set only if the source is a receiver (`flow` is `receiver`). */ receiver?: SourceCreateParams.Receiver; /** * Parameters required for the redirect flow. Required if the source is authenticated by a redirect (`flow` is `redirect`). */ redirect?: SourceCreateParams.Redirect; /** * Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. */ source_order?: SourceCreateParams.SourceOrder; /** * An arbitrary string to be displayed on your customer's statement. As an example, if your website is `RunClub` and the item you're charging for is a race ticket, you may want to specify a `statement_descriptor` of `RunClub 5K race ticket.` While many payment types will display this information, some may not display it at all. */ statement_descriptor?: string; /** * An optional token used to create the source. When passed, token properties will override source parameters. */ token?: string; /** * The `type` of the source to create. Required unless `customer` and `original_source` are specified (see the [Cloning card Sources](https://stripe.com/docs/sources/connect#cloning-card-sources) guide) */ type?: string; usage?: SourceCreateParams.Usage; } namespace SourceCreateParams { type Flow = 'code_verification' | 'none' | 'receiver' | 'redirect'; interface Mandate { /** * The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. */ acceptance?: Mandate.Acceptance; /** * The amount specified by the mandate. (Leave null for a mandate covering all amounts) */ amount?: number | ''; /** * The currency specified by the mandate. (Must match `currency` of the source) */ currency?: string; /** * The interval of debits permitted by the mandate. Either `one_time` (just permitting a single debit), `scheduled` (with debits on an agreed schedule or for clearly-defined events), or `variable`(for debits with any frequency) */ interval?: Mandate.Interval; /** * The method Stripe should use to notify the customer of upcoming debit instructions and/or mandate confirmation as required by the underlying debit network. Either `email` (an email is sent directly to the customer), `manual` (a `source.mandate_notification` event is sent to your webhooks endpoint and you should handle the notification) or `none` (the underlying debit network does not require any notification). */ notification_method?: Mandate.NotificationMethod; } namespace Mandate { interface Acceptance { /** * The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. */ date?: number; /** * The IP address from which the mandate was accepted or refused by the customer. */ ip?: string; /** * The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` */ offline?: Acceptance.Offline; /** * The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` */ online?: Acceptance.Online; /** * The status of the mandate acceptance. Either `accepted` (the mandate was accepted) or `refused` (the mandate was refused). */ status: Acceptance.Status; /** * The type of acceptance information included with the mandate. Either `online` or `offline` */ type?: Acceptance.Type; /** * The user agent of the browser from which the mandate was accepted or refused by the customer. */ user_agent?: string; } namespace Acceptance { interface Offline { /** * An email to contact you with if a copy of the mandate is requested, required if `type` is `offline`. */ contact_email: string; } interface Online { /** * The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. */ date?: number; /** * The IP address from which the mandate was accepted or refused by the customer. */ ip?: string; /** * The user agent of the browser from which the mandate was accepted or refused by the customer. */ user_agent?: string; } type Status = 'accepted' | 'pending' | 'refused' | 'revoked'; type Type = 'offline' | 'online'; } type Interval = 'one_time' | 'scheduled' | 'variable'; type NotificationMethod = | 'deprecated_none' | 'email' | 'manual' | 'none' | 'stripe_email'; } interface Owner { /** * Owner's address. */ address?: Owner.Address; /** * Owner's email address. */ email?: string; /** * Owner's full name. */ name?: string; /** * Owner's phone number. */ phone?: string; } namespace Owner { interface Address { /** * City, district, suburb, town, or village. */ city?: string; /** * Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). */ country?: string; /** * Address line 1 (e.g., street, PO Box, or company name). */ line1?: string; /** * Address line 2 (e.g., apartment, suite, unit, or building). */ line2?: string; /** * ZIP or postal code. */ postal_code?: string; /** * State, county, province, or region. */ state?: string; } } interface Receiver { /** * The method Stripe should use to request information needed to process a refund or mispayment. Either `email` (an email is sent directly to the customer) or `manual` (a `source.refund_attributes_required` event is sent to your webhooks endpoint). Refer to each payment method's documentation to learn which refund attributes may be required. */ refund_attributes_method?: Receiver.RefundAttributesMethod; } namespace Receiver { type RefundAttributesMethod = 'email' | 'manual' | 'none'; } interface Redirect { /** * The URL you provide to redirect the customer back to you after they authenticated their payment. It can use your application URI scheme in the context of a mobile application. */ return_url: string; } interface SourceOrder { /** * List of items constituting the order. */ items?: Array<SourceOrder.Item>; /** * Shipping address for the order. Required if any of the SKUs are for products that have `shippable` set to true. */ shipping?: SourceOrder.Shipping; } namespace SourceOrder { interface Item { amount?: number; currency?: string; description?: string; /** * The ID of the SKU being ordered. */ parent?: string; /** * The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. */ quantity?: number; type?: Item.Type; } namespace Item { type Type = 'discount' | 'shipping' | 'sku' | 'tax'; } interface Shipping { /** * Shipping address. */ address: AddressParam; /** * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. */ carrier?: string; /** * Recipient name. */ name?: string; /** * Recipient phone (including extension). */ phone?: string; /** * The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. */ tracking_number?: string; } } type Usage = 'reusable' | 'single_use'; } }
the_stack
import React, {FunctionComponent, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'; import {em, headerHeight, primaryColor, rem, zIndexes} from '~/utils/style'; import GridLoader from 'react-spinners/GridLoader'; import Icon from '~/components/Icon'; import RangeSlider from '~/components/RangeSlider'; import type {SamplePreviewerProps} from '~/components/SamplePage/SampleChart'; import styled from 'styled-components'; import {useTranslation} from 'react-i18next'; const Wrapper = styled.div` position: fixed; top: 0; left: 0; z-index: ${zIndexes.dialog}; height: 100vh; width: 100vw; background-color: var(--dark-mask-color); `; const Header = styled.div` position: relative; height: ${headerHeight}; width: 100%; background-color: var(--model-header-background-color); display: flex; justify-content: space-between; align-items: center; .step-slider { display: flex; align-items: center; flex-grow: 1; margin: 0 ${rem(20)}; .slider { width: 31.7213115%; margin: 0 ${rem(12)}; } .step-buttons { margin-left: ${em(10)}; display: flex; flex-direction: column; font-size: ${em(10)}; > a { display: inline-block; line-height: 1; height: ${em(14)}; &:hover { color: var(--text-lighter-color); } > i { display: inline-block; height: 100%; > svg { vertical-align: top; } } } } } .buttons { display: flex; align-items: center; font-size: ${rem(24)}; > * { margin-right: ${rem(30)}; } > a { height: ${rem(24)}; overflow: hidden; } > span { width: 1px; height: ${rem(30)}; background-color: var(--border-color); } } `; const Container = styled.div<{grabbing?: boolean}>` display: flex; justify-content: center; align-items: center; position: absolute; height: calc(100% - ${headerHeight}); width: 100%; top: ${headerHeight}; left: 0; overflow: hidden; > img { cursor: ${props => (props.grabbing ? 'grabbing' : 'grab')}; } `; const MAX_IMAGE_SCALE = 3; const MIN_IMAGE_SCALE = 0.1; type ImagePreviewerProps = SamplePreviewerProps; const ImagePreviewer: FunctionComponent<ImagePreviewerProps> = ({ data, loading, error, steps, step: propStep, onClose, onChange, onChangeComplete }) => { const {t} = useTranslation('sample'); const [step, setStep] = useState(propStep ?? 0); useEffect(() => setStep(propStep ?? 0), [propStep]); const changeStep = useCallback( (num: number) => { setStep(num); onChange?.(num); }, [onChange] ); const prevStep = useCallback(() => { if (step > 0) { changeStep(step - 1); } }, [step, changeStep]); const nextStep = useCallback(() => { if (step < steps.length - 1) { changeStep(step + 1); } }, [step, steps, changeStep]); const [url, setUrl] = useState(''); // use useLayoutEffect hook to prevent image render after url revoked useLayoutEffect(() => { if (data) { let objectUrl: string | null = null; objectUrl = URL.createObjectURL(data.data); setUrl(objectUrl); return () => { objectUrl && URL.revokeObjectURL(objectUrl); }; } }, [data]); const container = useRef<HTMLDivElement>(null); const image = useRef<HTMLImageElement>(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); useEffect(() => { if (url) { const img = new Image(); img.src = url; img.onload = () => { const rect = container.current?.getBoundingClientRect(); if (rect) { const r = rect.width / rect.height; const ir = img.naturalWidth / img.naturalHeight; if (r >= ir && img.naturalHeight > rect.height * 0.9) { setHeight(rect.height * 0.9); setWidth(ir * rect.height * 0.9); } else if (ir >= r && img.naturalWidth > rect.width * 0.9) { setWidth(rect.width * 0.9); setHeight(ir * rect.width * 0.9); } else { setWidth(img.naturalWidth); setHeight(img.naturalHeight); } } }; } return () => { setWidth(0); setHeight(0); }; }, [url]); const [scale, setScale] = useState(1); const scaleImage = useCallback( (step: number) => setScale(s => { if (s + step > MAX_IMAGE_SCALE) { return MAX_IMAGE_SCALE; } if (s + step < MIN_IMAGE_SCALE) { return MIN_IMAGE_SCALE; } return s + step; }), [] ); useEffect(() => { const img = container.current; const wheel = (e: WheelEvent) => { e.preventDefault(); setScale(s => { const t = s - e.deltaY * 0.007; if (t > MAX_IMAGE_SCALE) { return MAX_IMAGE_SCALE; } if (t < MIN_IMAGE_SCALE) { return MIN_IMAGE_SCALE; } return t; }); }; img?.addEventListener('wheel', wheel); return () => { img?.removeEventListener('wheel', wheel); }; }, []); const [grabbing, setGrabbing] = useState(false); const [x, setX] = useState(0); const [y, setY] = useState(0); useEffect(() => { const img = image.current; let trigger = false; let ox = 0; let oy = 0; const mousedown = (e: MouseEvent) => { e.preventDefault(); setGrabbing(true); trigger = true; ox = e.clientX; oy = e.clientY; }; const mousemove = (e: MouseEvent) => { e.preventDefault(); if (trigger) { setX(sx => { return sx + (e.clientX - ox); }); setY(sy => { return sy + (e.clientY - oy); }); ox = e.clientX; oy = e.clientY; } }; const mouseup = () => { setGrabbing(false); trigger = false; }; img?.addEventListener('mousedown', mousedown); img?.addEventListener('mousemove', mousemove); img?.addEventListener('mouseup', mouseup); img?.addEventListener('mouseout', mouseup); return () => { img?.removeEventListener('mousedown', mousedown); img?.removeEventListener('mousemove', mousemove); img?.removeEventListener('mouseup', mouseup); img?.removeEventListener('mouseout', mouseup); }; }, [url]); const reset = useCallback(() => { setScale(1); setX(0); setY(0); }, []); useEffect(() => reset, [url, reset]); const content = useMemo(() => { if (loading) { return <GridLoader color={primaryColor} size="10px" />; } if (error) { return <div>{t('common:error')}</div>; } return ( <img src={url} ref={image} onClick={e => e.stopPropagation()} style={{ width, height, transform: `translate(${x}px, ${y}px) scale(${scale})` }} /> ); }, [url, loading, error, width, height, x, y, scale, t]); return ( <Wrapper> <Header> <div className="step-slider"> <span>{t('common:time-mode.step')}</span> <RangeSlider className="slider" min={0} max={steps.length ? steps.length - 1 : 0} step={1} value={step} onChange={changeStep} onChangeComplete={onChangeComplete} /> <span>{steps[step]}</span> <div className="step-buttons"> <a href="javascript:void(0)" onClick={prevStep}> <Icon type="chevron-up" /> </a> <a href="javascript:void(0)" onClick={nextStep}> <Icon type="chevron-down" /> </a> </div> </div> <div className="buttons"> <a href="javascript:void(0)" onClick={() => scaleImage(0.1)}> <Icon type="plus-circle" /> </a> <a href="javascript:void(0)" onClick={() => scaleImage(-0.1)}> <Icon type="minus-circle" /> </a> <a href="javascript:void(0)" onClick={reset}> <Icon type="restore-circle" /> </a> <span></span> <a href="javascript:void(0)" onClick={onClose}> <Icon type="close" /> </a> </div> </Header> <Container ref={container} onClick={onClose} grabbing={grabbing}> {content} </Container> </Wrapper> ); }; export default ImagePreviewer;
the_stack
import * as loginPage from '../../Base/pages/Login.po'; import { LoginPageData } from '../../Base/pagedata/LoginPageData'; import * as invoicesPage from '../../Base/pages/Invoices.po'; import { InvoicesPageData } from '../../Base/pagedata/InvoicesPageData'; import * as organizationTagsUserPage from '../../Base/pages/OrganizationTags.po'; import { OrganizationTagsPageData } from '../../Base/pagedata/OrganizationTagsPageData'; import * as dashboardPage from '../../Base/pages/Dashboard.po'; import { CustomCommands } from '../../commands'; import * as faker from 'faker'; import * as manageEmployeesPage from '../../Base/pages/ManageEmployees.po'; import * as logoutPage from '../../Base/pages/Logout.po'; import { ContactsLeadsPageData } from '../../Base/pagedata/ContactsLeadsPageData'; import * as contactsLeadsPage from '../../Base/pages/ContactsLeads.po'; import * as organizationProjectsPage from '../../Base/pages/OrganizationProjects.po'; import { OrganizationProjectsPageData } from '../../Base/pagedata/OrganizationProjectsPageData'; import { Given, Then, When, And } from 'cypress-cucumber-preprocessor/steps'; const pageLoadTimeout = Cypress.config('pageLoadTimeout'); let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let username = faker.internet.userName(); let password = faker.internet.password(); let employeeEmail = faker.internet.email(); let imgUrl = faker.image.avatar(); let email = faker.internet.email(); let fullName = faker.name.firstName() + ' ' + faker.name.lastName(); let city = faker.address.city(); let postcode = faker.address.zipCode(); let street = faker.address.streetAddress(); let website = faker.internet.url(); let sendEmail = faker.internet.email(); // Login with email Given('Login with default credentials', () => { CustomCommands.login(loginPage, LoginPageData, dashboardPage); }); // Add new tag Then('User can add new tag', () => { dashboardPage.verifyAccountingDashboard(); CustomCommands.addTag(organizationTagsUserPage, OrganizationTagsPageData); }); // Add employee And('User can add new employee', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addEmployee( manageEmployeesPage, firstName, lastName, username, employeeEmail, password, imgUrl ); }); // Add project And('User can add new project', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addProject( organizationProjectsPage, OrganizationProjectsPageData ); }); // Add contact And('User can add new contact', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addContact( fullName, email, city, postcode, street, website, contactsLeadsPage, ContactsLeadsPageData ); }); // Add new invoice Then('User can visit Invoices page', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); cy.visit('/#/pages/accounting/invoices', { timeout: pageLoadTimeout }); }); And('User can see grid button', () => { invoicesPage.gridBtnExists(); }); And('User can click on second grid button to change view', () => { invoicesPage.gridBtnClick(1); }); And('User can see add Invoice button', () => { invoicesPage.addButtonVisible(); }); When('User click on add Invoice button', () => { invoicesPage.clickAddButton(); }); Then('User can see tags dropdown', () => { invoicesPage.tagsDropdownVisible(); }); When('User click on tags dropdown', () => { invoicesPage.clickTagsDropdwon(); }); Then('User can select tag from dropdown options', () => { invoicesPage.selectTagFromDropdown(0); invoicesPage.clickCardBody(); }); And('User can see discount input field', () => { invoicesPage.discountInputVisible(); }); And('User can enter value for discount', () => { invoicesPage.enterDiscountData(InvoicesPageData.discountValue); }); And('User can see discount type dropdown', () => { invoicesPage.discountTypeDropdownVisible(); }); When('User click on discount type dropdown', () => { invoicesPage.clickDiscountDropdown(); }); Then('User can select discount type from dropdown options', () => { invoicesPage.selectDiscountTypeFromDropdown( InvoicesPageData.discountType ); }); And('User can see contact dropdown', () => { invoicesPage.contactDropdownVisible(); }); When('User click on contact dropdown', () => { invoicesPage.clickContactDropdown(); }); Then('User can select contact from dropdown options', () => { invoicesPage.selectContactFromDropdwon(0); }); And('User can see tax input field', () => { invoicesPage.taxInputVisible(); }); And('User can enter value for tax', () => { invoicesPage.enterTaxData(InvoicesPageData.taxValue); }); And('User can see tax type dropdown', () => { invoicesPage.taxTypeDropdownVisible(); }); When('User click on tax type dropdown', () => { invoicesPage.clickTaxTypeDropdown(); }); Then('User can select tax type from dropdown options', () => { invoicesPage.selectTaxTypeFromDropdown(InvoicesPageData.taxType); }); And('User can see invoice type dropdown', () => { invoicesPage.invoiceTypeDropdownVisible(); }); When('User click on invoice type dropdown', () => { invoicesPage.clickInvoiceTypeDropdown(); }); Then('User can select invoice type from dropdown options', () => { invoicesPage.selectInvoiceTypeFromDropdown(InvoicesPageData.invoiceType); }); And('User can see employee dropdown', () => { invoicesPage.employeeDropdownVisible(); }); When('User click on employee dropdown', () => { invoicesPage.clickEmployeeDropdown(); }); Then('User can select employee from dropdown options', () => { invoicesPage.selectEmployeeFromDropdown(0); invoicesPage.clickKeyboardButtonByKeyCode(9); }); And('User can see generate items button', () => { invoicesPage.generateItemsButtonVisible(); }); When('User click on generate items button', () => { invoicesPage.clickGenerateItemsButton(); }); Then('Save as draft button will become active', () => { invoicesPage.saveAsDraftButtonVisible(); }); When('User click on Save as draft button', () => { invoicesPage.clickSaveAsDraftButton(InvoicesPageData.saveAsDraftButton); }); Then('Notification message will appear', () => { invoicesPage.waitMessageToHide(); }); And('User can verify invoice was created', () => { invoicesPage.verifyDraftBadgeClass(); }); // Search invoice And('User can see tab button', () => { invoicesPage.verifyTabButtonVisible(); }); When('User click on second tab button', () => { invoicesPage.clickTabButton(1); }); Then('User can see invoice number input field', () => { invoicesPage.veirifyEstimateNumberInputVisible(); }); And('User can enter invoice number', () => { invoicesPage.enterEstimateNumberInputData( InvoicesPageData.invoiceNumber ); }); And('User can see currency dropdown', () => { invoicesPage.verifyCurrencuDropdownVisible(); }); And('User can see invoice date input field', () => { invoicesPage.verifyEstimateDateInput(); }); And('User can see invoice due date input field', () => { invoicesPage.verifyEstimateDueDateInput(); }); And('User can see total value input field', () => { invoicesPage.verifyTotalValueInputVisible(); }); And('User can see status input field', () => { invoicesPage.verifyStatusInputVisible(); }); And('User can see search button', () => { invoicesPage.searchButtonVisible(); }); When('User click on search button', () => { invoicesPage.clickSearchButton(); }); Then('User can see reset button', () => { invoicesPage.resetButtonVisible(); }); When('User click on reset button', () => { invoicesPage.clickResetButton(); }); Then('User can click search button', () => { invoicesPage.clickSearchButton(); }); And('User can verify badge', () => { invoicesPage.verifyDraftBadgeClass(); }); And('User can edit invoice number', () => { invoicesPage.enterEstimateNumberInputData( InvoicesPageData.secondInvoiceNumber ); }); And('User can click search button again', () => { invoicesPage.clickSearchButton(); }); And('User can click on reset button', () => { invoicesPage.clickResetButton(); }); And('User can verify badge', () => { invoicesPage.verifyDraftBadgeClass(); }); And('User can click on next tab button', () => { invoicesPage.clickTabButton(2); }); And('User can verify badge', () => { invoicesPage.verifyDraftBadgeClass(); }); // Edit invoice When('User click on first tab button', () => { invoicesPage.clickTabButton(0); }); Then('User can select invoices first table row', () => { invoicesPage.selectTableRow(0); }); And('Edit button will become active', () => { invoicesPage.editButtonVisible(); }); When('User click on edit button', () => { invoicesPage.clickEditButton(0); }); Then('User can see discount input field', () => { invoicesPage.discountInputVisible(); }); And('User can enter value for discount', () => { invoicesPage.enterDiscountData(InvoicesPageData.editDiscountValue); }); And('User can see discount type dropdown', () => { invoicesPage.discountTypeDropdownVisible(); }); When('User click on discount type dropdown', () => { invoicesPage.clickDiscountDropdown(); }); Then('User can select discount type from dropdown options', () => { invoicesPage.selectDiscountTypeFromDropdown( InvoicesPageData.discountType ); }); And('User can see contact dropdown', () => { invoicesPage.contactDropdownVisible(); }); When('User click on contact dropdown', () => { invoicesPage.clickContactDropdown(); }); Then('User can select contact from dropdown options', () => { invoicesPage.selectContactFromDropdwon(0); }); And('User can see tax input field', () => { invoicesPage.taxInputVisible(); }); And('User can enter value for tax', () => { invoicesPage.enterTaxData(InvoicesPageData.taxValue); }); And('User can see tax type dropdown', () => { invoicesPage.taxTypeDropdownVisible(); }); When('User click on tax type dropdown', () => { invoicesPage.clickTaxTypeDropdown(); }); Then('User can select tax type from dropdown options', () => { invoicesPage.selectTaxTypeFromDropdown(InvoicesPageData.taxType); }); Then('Save as draft button will become active', () => { invoicesPage.saveAsDraftButtonVisible(); }); When('User click on Save as draft button', () => { invoicesPage.clickSaveAsDraftButton(InvoicesPageData.saveAsDraftButton); }); Then('Notification message will appear', () => { invoicesPage.waitMessageToHide(); }); // View invoice When('User select invoices first table row', () => { invoicesPage.selectTableRow(0); }); Then('View invoice button will become active', () => { invoicesPage.viewButtonVisible(); }); And('User can click on vew invoice button', () => { invoicesPage.clickViewButton(1); }); And('User can see back button', () => { invoicesPage.backButtonVisible(); }); When('User click on back button', () => { invoicesPage.clickBackButton(); }); // Send invoice by email Then('User can click again on invoices first table row', () => { invoicesPage.selectTableRow(0); }); And('More settings button will become active', () => { invoicesPage.moreButtonVisible(); }); When('User click more settings button', () => { invoicesPage.clickMoreButton(); }); Then('User can see email button', () => { invoicesPage.actionButtonVisible(); }); When('User click on email button', () => { cy.on('uncaught:exception', (err, runnable) => { return false; }); invoicesPage.clickActionButtonByText(InvoicesPageData.emailButton); }); Then('User can scroll down to email input field', () => { invoicesPage.scrollEmailInviteTemplate(); }) And('User can see email input field', () => { invoicesPage.emailInputVisible(); }); And('User can enter value for email', () => { invoicesPage.enterEmailData(sendEmail); }); And('User can see confirm send email button', () => { invoicesPage.confirmButtonVisible(); }); When('User click on confirm send email button', () => { invoicesPage.clickConfirmButton(); }); Then('Notification message will appear', () => { invoicesPage.waitMessageToHide(); }); When('User click more settings button', () => { invoicesPage.clickMoreButton(); }); Then('User can verify invoice was sent by email', () => { invoicesPage.verifySentBadgeClass(); }); // Delete invoice Then('User can click on invoices first row', () => { invoicesPage.selectTableRow(0); }); And('Settings button will become active', () => { invoicesPage.moreButtonVisible(); }); When('User click settings button', () => { invoicesPage.clickMoreButton(); }); Then('Delete button will become active', () => { invoicesPage.deleteButtonVisible(); }); When('User click on delete button', () => { invoicesPage.clickDeleteButton(); }); Then('User can see confirm delete button', () => { invoicesPage.confirmDeleteButtonVisible(); }); When('User click on confirm delete button', () => { invoicesPage.clickConfirmDeleteButton(); }); Then('Notification message will appear', () => { invoicesPage.waitMessageToHide(); });
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 { Numbers } from "../../system/runtime/Numbers"; import { Strings } from "../../system/runtime/Strings"; import { Coordinate } from "../geom/Coordinate"; import { CRS } from "./CRS"; import { OperationMethod } from "./OperationMethod"; import { Registry } from "./Registry"; /** * Class Operation defines an coordinate operation. The operation defines a specific method, * together with specific values for the parameters of the method, and a specific source and * destination coordinate reference system. * * 'Conversions' are operations that convert from projected systems to and from geographic systems (same datum). * 'Transformations' are Operations that convert from one geocentric system to another (different datum). * * @version 1.0 July 2005 */ /** @internal */ export class Operation { /** The type of a concatenated operation */ public static readonly CONCATENATED: int32 = 1; /** The type of a conversion operation (projected to geographic) */ public static readonly CONVERSION: int32 = 2; /** The type of a transformation operation (geocentric to geocentric) */ public static readonly TRANSFORMATION: int32 = 3; /** The code */ private _code: int32; /** The name */ private _name: string; /** The type */ private _type: int32; /** The code of the source CRS */ private _sourceCRScode: int32; /** The code of the target CRS */ private _targetCRScode: int32; /** The area on which the operation has been defined (0 if unknown) */ private _areaOfUse: int32; /** The method */ private _method: OperationMethod; /** Have we been initialised ? */ private _initialised: boolean; /** The source coordinate reference system */ private _sourceCRS: CRS; /** The target coordinate reference system */ private _targetCRS: CRS; /** The concatenated operations */ private _concatenatedOperations: AList<Operation>; /** * Create a new coordinate operation. * @param code the code. * @param name the name. * @param type the type (CONCATENATED, CONVERSION or TRANSFORMATION). * @param sourceCRScode the code of the source CRS. * @param targetCRScode the code of the target CRS. * @param areaOfUse the area on which the operation has been defined (0 if unknown). * @param method the method (null for concatenated operations). */ public constructor(code: int32, name: string, type: int32, sourceCRScode: int32, targetCRScode: int32, areaOfUse: int32, method: OperationMethod) { /* Store the parameters */ this._code = code; this._name = name; this._type = type; this._sourceCRScode = sourceCRScode; this._targetCRScode = targetCRScode; this._areaOfUse = areaOfUse; this._method = method; /* Clear */ this._initialised = false; this._sourceCRS = null; this._targetCRS = null; this._concatenatedOperations = null; } /** * Get the code. * @return the code. */ public getCode(): int32 { return this._code; } /** * Get the name. * @return the name. */ public getName(): string { return this._name; } /** * Get the type (CONCATENATED, CONVERSION or TRANSFORMATION). * @return the type. */ public getType(): int32 { return this._type; } /** * Get the code of the source CRS. * @return the code of the source CRS. */ public getSourceCRScode(): int32 { return this._sourceCRScode; } /** * Get the code of the target CRS. * @return the code of the target CRS. */ public getTargetCRScode(): int32 { return this._targetCRScode; } /** * Get the area on which the operation has been defined. * @return the area on which the operation has been defined (0 if unknown). */ public getAreaOfUse(): int32 { return this._areaOfUse; } /** * Get the method (null for concatenated operations). * @return the method. */ public getMethod(): OperationMethod { return this._method; } /** * Set the method. * @param method the new method (null for concatenated operations). */ public setMethod(method: OperationMethod): void { this._method = method; } /** * Get the concatenated operations. * @return the concatenated operations (null for a method). */ public getConcatenatedOperations(): AList<Operation> { return this._concatenatedOperations; } /** * Set the concatenated operations. * @param concatenatedOperations the concatenated operations (null for a method). */ public setConcatenatedOperations(concatenatedOperations: AList<Operation>): void { this._concatenatedOperations = concatenatedOperations; } /** * Initialise the operation. */ public initialise(): void { /* Initialize the systems */ if (this._sourceCRS == null) this._sourceCRS = Registry.getCRS(this._sourceCRScode); if (this._targetCRS == null) this._targetCRS = Registry.getCRS(this._targetCRScode); /* Already done ? */ if (this._initialised) return; this._initialised = true; /* Concatenated operations ? */ if (this._type == Operation.CONCATENATED) { /* Create the list of operations */ this._concatenatedOperations = new AList<Operation>(); //Registry.readConcatenatedOperations(this.code); } else { /* Initialise the method ? */ this._method.initialize(this); } } /** * Get the source CRS. * @return the source CRS. */ public getSourceCRS(): CRS { if (this._sourceCRS == null) this.initialise(); return this._sourceCRS; } /** * Set the source CRS. * @param sourceCRS the source CRS. */ public setSourceCRS(sourceCRS: CRS): void { this._sourceCRS = sourceCRS; } /** * Get the target CRS. * @return the target CRS. */ public getTargetCRS(): CRS { if (this._targetCRS == null) this.initialise(); return this._targetCRS; } /** * Set the target CRS. * @param targetCRS the target CRS. */ public setTargetCRS(targetCRS: CRS): void { this._targetCRS = targetCRS; } /** * Convert a source coordinate to a target coordinate. * @param source the coordinates in the source CRS. * @param target the coordinates in the target CRS (this is the result object). */ public forward(source: Coordinate, target: Coordinate): void { this.initialise(); /* Concatenated operations ? */ if (this._type == Operation.CONCATENATED) { /* Run all operations */ for (let i: number = 0; i < this._concatenatedOperations.size(); i++) { this._concatenatedOperations.get(i).forward(source, target); source = target; } } else { /* Let the method do it */ this._method.forward(this._sourceCRS, source, this._targetCRS, target); } } /** * Convert a target coordinate to a source coordinate. * @param source the coordinates in the source CRS (this is the result object). * @param target the coordinates in the target CRS. */ public reverse(source: Coordinate, target: Coordinate): void { this.initialise(); /* Concatenated operations ? */ if (this._type == Operation.CONCATENATED) { /* Run all operations */ for (let i: number = 0; i < this._concatenatedOperations.size(); i++) { this._concatenatedOperations.get(this._concatenatedOperations.size() - 1 - i).reverse(source, target); target = source; } } else { /* Let the method do it */ this._method.reverse(this._sourceCRS, source, this._targetCRS, target); } } /** * Check if another operation is compatible with this one. * @param other the other operation. * @return true if compatible. */ public isCompatible(other: Operation): boolean { if (other._code == this._code) return true; // all operations should have unique identifiers if (other._type != this._type) return false; if (other._sourceCRScode != this._sourceCRScode) return false; if (other._targetCRScode != this._targetCRScode) return false; if (other._method.isCompatible(this._method) == false) return false; if (Operation.areCompatibleOperations(other._concatenatedOperations, this._concatenatedOperations) == false) return false; return true; } /** * Check if two operations are compatible. * @param operation1 the first operation. * @param operation2 the second operation. * @return true if compatible. */ public static isCompatibleOperation(operation1: Operation, operation2: Operation): boolean { if (operation1 == null) return (operation2 == null); if (operation2 == null) return false; return (operation1.isCompatible(operation2)); } /** * Check if a list of operations is compatible with another one. * @param list1 the first list. * @param list2 the second list. * @return true if compatible. */ private static areCompatibleOperations(list1: AList<Operation>, list2: AList<Operation>): boolean { if (list1 == null) return (list2 == null); if (list2 == null) return false; if (list2.size() != list1.size()) return false; for (let i: number = 0; i < list2.size(); i++) if (list2.get(i).isCompatible(list1.get(i)) == false) return false; return true; } /** * The standard toString method. * @see Object#toString */ public toString(): string { return "[Operation:code=" + this._code + ",name='" + this._name + "',type=" + this._type + ",sourceCRS=" + this._sourceCRScode + ",targetCRS=" + this._targetCRScode + ",area=" + this._areaOfUse + ",method=" + this._method + "]"; } /** * Find an operation by name. * @param operations the list of operations. * @param name the name of the operation. * @return the index of the operation. */ public static findByName(operations: Array<Operation>, name: string): int32 { /* No list ? */ if (operations == null) return -1; /* Check */ for (let i: number = 0; i < operations.length; i++) if (Strings.equalsIgnoreCase(operations[i].getName(), name)) return i; /* Not found */ return -1; } /** * Get the version of a transformation. * @param transformationName the name of the transformation. * @return the version (0 if not found). */ private static getTransformationVersion(transformationName: string): int32 { /* Find the (...) sequence */ let index0: int32 = Strings.lastIndexOf(transformationName, "("); if (index0 < 0) return 0; let index1: int32 = Strings.lastIndexOf(transformationName, ")"); if ((index1 < 0) || (index1 < index0)) return 0; /* Parse the version */ let version: string = Strings.substring(transformationName, index0 + 1, index1); return Numbers.getInteger(version, 0); } /** * Get the latest transform from a set of transformations. * @param transformations the set of transformations. * @return the latest transform. */ public static getLatestTransformation(transformations: AList<Operation>): Operation { /* We need at least two transforms */ if (transformations == null) return null; if (transformations.size() == 0) return null; if (transformations.size() == 1) return transformations.get(0); /* Start with the first transform */ let bestIndex: int32 = 0; let bestVersion: int32 = Operation.getTransformationVersion(transformations.get(bestIndex).getName()); /* Check for better versions */ for (let i: number = 1; i < transformations.size(); i++) { /* Check */ let version: int32 = Operation.getTransformationVersion(transformations.get(i).getName()); if (version > bestVersion) { /* This one is later */ bestIndex = i; bestVersion = version; } } /* Return the best transform */ return transformations.get(bestIndex); } }
the_stack
import {Constant, Immediate, Operand, SIZE} from '../../operand'; import * as o from './operand'; import {Instruction, InstructionSet} from '../../instruction'; import * as p from './parts'; import {DisplacementValue} from "./operand/displacement"; import {RegisterK, RegisterX86} from "./operand/register"; import {MemoryX86} from "./operand/memory"; import MnemonicX86 from "./MnemonicX86"; import {IPushable} from "../../expression"; import ImmediatePart from "./parts/Immediate"; export interface IInstructionOptionsX86 { size: SIZE; mask?: RegisterK; z?: number | boolean; } export interface IInstructionX86 { lock(): this; bt(): this; bnt(): this; rep(): this; repe(): this; repz(): this; repnz(): this; repne(): this; cs(): this; ss(): this; ds(): this; es(): this; fs(): this; gs(): this; } // ## x86_64 `Instruction` // // `Instruction` object is created using instruction `Definition` and `Operands` provided by the user, // out of those `Instruction` generates `InstructionPart`s, which then can be packaged into machine // code using `.write()` method. export class InstructionX86 extends Instruction implements IInstructionX86 { mnemonic: MnemonicX86; ops: o.OperandsX86; opts: IInstructionOptionsX86; // Instruction parts. pfxOpSize: p.PrefixOperandSizeOverride = null; pfxAddrSize: p.PrefixAddressSizeOverride = null; pfxLock: p.PrefixLock = null; pfxRep: p.PrefixRep|p.PrefixRepe = null; pfxRepne: p.PrefixRepne = null; pfxSegment: p.PrefixStatic = null; prefixes: p.PrefixStatic[] = []; pfxEx: p.PrefixRex|p.PrefixVex|p.PrefixEvex = null; // One of REX, VEX, EVEX prefixes, only one allowed. opcode: p.Opcode = new p.Opcode; // required modrm: p.Modrm = null; sib: p.Sib = null; displacement: p.Displacement = null; immediates: ImmediatePart[] = []; // Direction for register-to-register `MOV` operations, whether REG field of Mod-R/M byte is destination. // We set this to `false` to be compatible with GAS assembly, which we use for testing. protected regToRegDirectionRegIsDst: boolean = false; build(): this { super.build(); this.pfxOpSize = null; this.pfxAddrSize = null; this.pfxLock = null; this.pfxRep = null; this.pfxRepne = null; this.pfxSegment = null; this.prefixes = []; this.pfxEx = null; this.opcode = new p.Opcode; // required this.modrm = null; this.sib = null; this.displacement = null; this.immediates = []; this.length = 0; this.lengthMax = 0; this.createPrefixes(); this.createOpcode(); this.createModrm(); this.createSib(); this.createDisplacement(); this.createImmediates(); return this; } protected writePrefixes(arr: IPushable) { if(this.pfxLock) this.pfxLock.write(arr); if(this.pfxRep) this.pfxRep.write(arr); if(this.pfxRepne) this.pfxRepne.write(arr); if(this.pfxAddrSize) this.pfxAddrSize.write(arr); if(this.pfxSegment) this.pfxSegment.write(arr); if(this.pfxOpSize) this.pfxOpSize.write(arr); for(var pfx of this.prefixes) pfx.write(arr); if(this.pfxEx) this.pfxEx.write(arr); } write (arr: IPushable) { this.writePrefixes(arr); this.opcode.write(arr); if (this.modrm) this.modrm.write(arr); if (this.sib) this.sib.write(arr); if (this.displacement) this.displacement.write(arr); if (this.immediates.length) for (var imm of this.immediates) imm.write(arr); } protected fixDisplacementSize() { if(this.displacement && this.displacement.value.variable) { const {variable} = this.displacement.value; const val = variable.evaluatePreliminary(this); const size = Constant.sizeClass(val); if(size > DisplacementValue.SIZE.DISP8) this.length += DisplacementValue.SIZE.DISP32 / 8; else this.length += DisplacementValue.SIZE.DISP8 / 8; } } getFixedSizeExpression() { // Determine size of displacement this.fixDisplacementSize(); return super.getFixedSizeExpression(); } evaluate(): boolean { this.ops.evaluate(this); var max = 2; // Up to 2 immediates. for(var j = 0; j < max; j++) { var rel = this.ops.getRelative(j); if(rel) { var res = (rel.result as number); // var res = (rel.result as number) - this.bytes(); this.immediates[j].value.setValue(res); } } // Evaluate displacement variable. if(this.displacement && this.displacement.value.variable) { var value = this.displacement.value; var variable = value.variable; var val = variable.evaluate(this); var size = value.size; value.setValue(val); if(value.size > size) throw Error(`Displacement does not fit in ${size} bits.`); else value.signExtend(size); } return super.evaluate(); } lock(): this { if(!this.mnemonic.lock) throw Error(`Instruction "${this.mnemonic.mnemonic}" does not support LOCK.`); this.pfxLock = new p.PrefixLock; this.length++; this.lengthMax++; return this; } bt() { // Branch taken prefix. return this.ds(); } bnt() { // Branch not taken prefix. return this.cs(); } rep(): this { if(p.PrefixRep.supported.indexOf(this.mnemonic.mnemonic) === -1) throw Error(`Instruction "${this.mnemonic.mnemonic}" does not support REP prefix.`); this.pfxRep = new p.PrefixRep; return this; } repe() { if(p.PrefixRepe.supported.indexOf(this.mnemonic.mnemonic) === -1) throw Error(`Instruction "${this.mnemonic.mnemonic}" does not support REPE/REPZ prefix.`); this.pfxRep = new p.PrefixRepe; return this; } repz() { return this.repe(); } repne(): this { if(p.PrefixRepne.supported.indexOf(this.mnemonic.mnemonic) === -1) throw Error(`Instruction "${this.mnemonic.mnemonic}" does not support REPNE/REPNZ prefix.`); this.pfxRepne = new p.PrefixRepne; return this; } repnz() { return this.repne(); } cs(): this { this.pfxSegment = new p.PrefixStatic(p.PREFIX.CS); return this; } ss(): this { this.pfxSegment = new p.PrefixStatic(p.PREFIX.SS); return this; } ds(): this { this.pfxSegment = new p.PrefixStatic(p.PREFIX.DS); return this; } es(): this { this.pfxSegment = new p.PrefixStatic(p.PREFIX.ES); return this; } fs(): this { this.pfxSegment = new p.PrefixStatic(p.PREFIX.FS); return this; } gs(): this { this.pfxSegment = new p.PrefixStatic(p.PREFIX.GS); return this; } protected toStringExpression() { let expression = super.toStringExpression(); if (this.pfxLock) expression += ` {${this.pfxLock.toString()}}`; if (this.pfxSegment) expression += ` {${this.pfxSegment.toString()}}`; if (this.opts.mask) expression += ` {${this.opts.mask.toString()}}`; if (this.opts.z) expression += ` {z}`; return expression; } protected needsOperandSizeOverride() { if((this.asm.opts.operandSize === SIZE.D) && (this.mnemonic.operandSize === SIZE.W)) return true; if((this.asm.opts.operandSize === SIZE.W) && (this.mnemonic.operandSize === SIZE.D)) return true; return false; } protected needsAddressSizeOverride() { var mem = this.ops.getMemoryOperand(); if(mem) { var reg = mem.reg(); if(reg && (reg.size !== this.asm.opts.addressSize)) return true; } return false; } protected createPrefixes() { if(this.needsOperandSizeOverride()) { this.pfxOpSize = new p.PrefixOperandSizeOverride; this.length++; this.lengthMax++; } if(this.needsAddressSizeOverride()) { this.pfxAddrSize = new p.PrefixAddressSizeOverride; this.length++; this.lengthMax++; } if(this.mnemonic.vex) this.createVexPrefix(); else if(this.mnemonic.evex) this.createEvexPrefix(); // Mandatory prefixes required by op-code. if(this.mnemonic.prefixes) { for(var val of this.mnemonic.prefixes) { this.prefixes.push(new p.PrefixStatic(val)); } this.length += this.mnemonic.prefixes.length; this.lengthMax += this.mnemonic.prefixes.length; } } protected createVexPrefix() { // These bits in VEX are inverted, so they actually all mean "0" zeros. var R = 1, X = 1, B = 1, vvvv = 0b1111; var pos = this.mnemonic.opEncoding.indexOf('v'); if(pos > -1) { var reg = this.ops.getAtIndexOfClass(pos, RegisterX86) as RegisterX86; if(!reg) throw Error(`Could not find Register operand at position ${pos} to encode VEX.vvvv`); vvvv = (~reg.get4bitId()) & 0b1111; // Inverted } pos = this.mnemonic.opEncoding.indexOf('r'); if(pos > -1) { var reg = this.ops.getAtIndexOfClass(pos, RegisterX86) as RegisterX86; if(!reg) throw Error(`Could not find Register operand at position ${pos} to encode VEX.R`); if(reg.idSize() > 3) R = 0; // Inverted } pos = this.mnemonic.opEncoding.indexOf('m'); if(pos > -1) { var reg = this.ops.getAtIndexOfClass(pos, RegisterX86) as RegisterX86; if(reg && (reg.idSize() > 3)) B = 0; // Inverted } var mem = this.ops.getMemoryOperand() as MemoryX86; if(mem) { if (mem.base && (mem.base.idSize() > 3)) B = 0; if (mem.index && (mem.index.idSize() > 3)) X = 0; } this.pfxEx = new p.PrefixVex(this.mnemonic.vex, R, X, B, vvvv); this.length += (this.pfxEx as p.PrefixVex).bytes; this.lengthMax += (this.pfxEx as p.PrefixVex).bytes; } protected createEvexPrefix() { const evex = this.pfxEx = new p.PrefixEvex(this.mnemonic.evex); this.length += 4; this.lengthMax += 4; let pos = this.mnemonic.opEncoding.indexOf('v'); if(pos > -1) { var reg = this.ops.getAtIndexOfClass(pos, RegisterX86) as RegisterX86; if(!reg) throw Error(`Could not find Register operand at position ${pos} to encode EVEX.vvvv`); evex.vvvv = (~reg.get4bitId()) & 0b1111; // Inverted evex.Vp = reg.id & 0b10000 ? 0 : 1; // Inverted } pos = this.mnemonic.opEncoding.indexOf('r'); if(pos > -1) { var reg = this.ops.getAtIndexOfClass(pos, RegisterX86) as RegisterX86; if(!reg) throw Error(`Could not find Register operand at position ${pos} to encode VEX.R`); var id_size = reg.idSize(); if(id_size > 3) evex.R = 0; // Inverted if(id_size > 4) { evex.Rp = 0; // Inverted if(reg.id & 0b1000) evex.R = 0; else evex.R = 1; } } pos = this.mnemonic.opEncoding.indexOf('m'); if(pos > -1) { var reg = this.ops.getAtIndexOfClass(pos, RegisterX86) as RegisterX86; if(reg) { if (reg.idSize() > 3) evex.B = 0; // Inverted if (reg.idSize() > 4) { evex.X = 0; // Inverted if(reg.id & 0b1000) evex.B = 0; else evex.B = 1; } } } var mem = this.ops.getMemoryOperand() as MemoryX86; if(mem) { if (mem.base && (mem.base.idSize() > 3)) evex.B = 0; // Inverted if (mem.index && (mem.index.idSize() > 3)) evex.X = 0; // Inverted } if(this.opts.mask) this.mask(this.opts.mask); if(typeof this.opts.z !== 'undefined') this.z(this.opts.z); } // Set mask register for `EVEX` instructions. mask(k: RegisterK): this { if(!(this.pfxEx instanceof p.PrefixEvex)) throw Error('Cannot set mask on non-EVEX instruction.'); if(k.id === 0) throw TypeError('Mask register 000 cannot be used as mask.'); (this.pfxEx as p.PrefixEvex).aaa = k.get3bitId(); return this; } // Set `z` bit for `EVEX` instructions. z(value: number|boolean = 1): this { if(!(this.pfxEx instanceof p.PrefixEvex)) throw Error('Cannot set z-bit on non-EVEX instruction.'); (this.pfxEx as p.PrefixEvex).z = value ? 1 : 0; return this; } protected createOpcode() { var def = this.mnemonic; var opcode = this.opcode; opcode.op = def.opcode; var [dst, src] = this.ops.list; if(def.regInOp) { // We have register encoded in op-code here. if(!dst || (!(dst as Operand).isRegister())) throw TypeError(`Operation needs destination Register.`); opcode.op = (opcode.op & p.Opcode.MASK_OP) | (dst as RegisterX86).get3bitId(); } else { // Direction bit `d` if(this.mnemonic.opcodeDirectionBit) { var direction = p.Opcode.DIRECTION.REG_IS_DST; if(src instanceof RegisterX86) { direction = p.Opcode.DIRECTION.REG_IS_SRC; } // *reg-to-reg* operation if((dst instanceof RegisterX86) && (src instanceof RegisterX86)) { if(this.regToRegDirectionRegIsDst) direction = p.Opcode.DIRECTION.REG_IS_DST; else direction = p.Opcode.DIRECTION.REG_IS_SRC; } opcode.op = (opcode.op & p.Opcode.MASK_DIRECTION) | direction; } // Size bit `s` // if(this.def.opcodeSizeBit) { // opcode.op = (opcode.op & p.Opcode.MASK_SIZE) | (p.Opcode.SIZE.WORD); // ... // } } var bytes = opcode.bytes(); this.length += bytes; this.lengthMax += bytes; } protected createModrm() { if(!this.mnemonic.useModrm) return; if(!this.ops.hasRegisterOrMemory()) return; var encoding = this.mnemonic.opEncoding; var mod = 0, reg = 0, rm = 0; var [dst, src] = this.ops.list; var has_opreg = (this.mnemonic.opreg > -1); var dst_in_modrm = !this.mnemonic.regInOp && !!dst; // Destination operand is NOT encoded in main op-code byte. if(has_opreg || dst_in_modrm) { // var reg_is_dst = !!(this.opcode.op & p.Opcode.DIRECTION.REG_IS_DST); var reg_is_dst = this.mnemonic.opEncoding[0] !== 'm' ? true : false; if(has_opreg) { // If we have `opreg`, then instruction has up to one operand. reg = this.mnemonic.opreg; var r: RegisterX86 = this.ops.getRegisterOperand() as RegisterX86; if (r) { mod = p.Modrm.MOD.REG_TO_REG; rm = r.get3bitId(); this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } } else { // Reg-to-reg instruction; if((encoding.length === 2) && (dst instanceof RegisterX86) && (src instanceof RegisterX86)) { mod = p.Modrm.MOD.REG_TO_REG; var regreg: RegisterX86 = (reg_is_dst ? dst : src) as RegisterX86; var rmreg: RegisterX86 = (reg_is_dst ? src : dst) as RegisterX86; reg = regreg.get3bitId(); rm = rmreg.get3bitId(); this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } var rpos = encoding.indexOf('r'); var rreg; if((rpos > -1) && (rreg = this.ops.getAtIndexOfClass(rpos, RegisterX86) as RegisterX86)) { reg = rreg.get3bitId(); } else { // var r: o.Register = this.op.getRegisterOperand(this.regToRegDirectionRegIsDst); var r: RegisterX86 = this.ops.getRegisterOperand(this.regToRegDirectionRegIsDst ? 0 : 1) as RegisterX86; if(!r) r = this.ops.getRegisterOperand() as RegisterX86; if(r) { mod = p.Modrm.MOD.REG_TO_REG; reg = r.get3bitId(); } } } var mpos = encoding.indexOf('m'); if(mpos > -1) { var mreg = this.ops.getAtIndexOfClass(mpos, RegisterX86) as RegisterX86; if(mreg) { mod = p.Modrm.MOD.REG_TO_REG; rm = (mreg as RegisterX86).get3bitId(); this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } } else { this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } if(!dst) { // No destination operand, just opreg. this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } // `o.Memory` class makes sure that ESP cannot be a SIB index register and // that EBP always has displacement value even if 0x00. // Memory operand can be encoded in only one way (Modrm.rm + SIB) so we // ignore here `def.opEncoding` field. var m: MemoryX86 = this.ops.getMemoryOperand() as MemoryX86; if(!m) { this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } if(!m.base && !m.index && !m.displacement) throw TypeError('Invalid Memory reference.'); if(m.index && !m.scale) throw TypeError('Memory Index reference needs Scale factor.'); // dispX // We use `disp32` with SIB byte version because the version without SIB byte // will be used for RIP-relative addressing. if(!m.base && !m.index && m.displacement) { m.displacement.signExtend(DisplacementValue.SIZE.DISP32); mod = p.Modrm.MOD.INDIRECT; rm = p.Modrm.RM.NEEDS_SIB; // SIB byte follows this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } // [BASE] // [BASE] + dispX // `o.Memory` class makes sure that EBP always has displacement value even if 0x00, // so EBP will not appear here. if(m.base && !m.index) { mod = p.Modrm.getModDispSize(m); if(mod === p.Modrm.MOD.DISP32) m.displacement.signExtend(DisplacementValue.SIZE.DISP32); // SIB byte follows in `[RSP]` case, and `[RBP]` is impossible as RBP // always has a displacement, [RBP] case is used for RIP-relative addressing. rm = m.base.get3bitId(); this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } // [BASE + INDEX x SCALE] + dispX if(m.base || m.index) { mod = p.Modrm.getModDispSize(m); if(m.displacement) if((mod === p.Modrm.MOD.DISP32) || (mod === p.Modrm.MOD.INDIRECT)) m.displacement.signExtend(DisplacementValue.SIZE.DISP32); rm = p.Modrm.RM.NEEDS_SIB; // SIB byte follows this.modrm = new p.Modrm(mod, reg, rm); this.length++; this.lengthMax++; return; } throw Error('Fatal error, unreachable code.'); } } protected createSib() { if(!this.modrm) return; if(this.modrm.mod === p.Modrm.MOD.REG_TO_REG) return; if((this.modrm.rm !== p.Modrm.RM.NEEDS_SIB)) return; var m: MemoryX86 = this.ops.getMemoryOperand() as MemoryX86; if(!m) throw Error('No Memory operand to encode SIB.'); var scalefactor = 0, I = 0, B = 0; if(m.scale) scalefactor = m.scale.value; if(m.index) { I = m.index.get3bitId(); // RSP register cannot be used as index, `o.Memory` class already ensures it // if used in normal way. if(I === p.Sib.INDEX_NONE) throw Error(`Register ${m.index.toString()} cannot be used as SIB index.`); } else { I = p.Sib.INDEX_NONE; } if(m.base) { B = m.base.get3bitId(); } else B = p.Sib.BASE_NONE; this.sib = new p.Sib(scalefactor, I, B); this.length++; this.lengthMax++; } protected createDisplacement() { var m: MemoryX86 = this.ops.getMemoryOperand() as MemoryX86; if(m && m.displacement) { this.displacement = new p.Displacement(m.displacement); if(m.displacement.variable) { // We don't know the size of displacement yet. // Displacement will be at least 1 byte, // but we skip `this.length` for now. this.lengthMax += DisplacementValue.SIZE.DISP32 / 8; // max 4 bytes } else { var size = this.displacement.value.size / 8; this.length += size; this.lengthMax += size; } } else if(this.modrm && this.sib && (this.sib.B === p.Sib.BASE_NONE)) { // Some SIB byte encodings require displacement, if we don't have displacement yet // add zero displacement. var disp: DisplacementValue = null; switch(this.modrm.mod) { case p.Modrm.MOD.INDIRECT: disp = new DisplacementValue(0); disp.signExtend(DisplacementValue.SIZE.DISP32); break; case p.Modrm.MOD.DISP8: disp = new DisplacementValue(0); disp.signExtend(DisplacementValue.SIZE.DISP8); break; case p.Modrm.MOD.DISP32: disp = new DisplacementValue(0); disp.signExtend(DisplacementValue.SIZE.DISP32); break; } if(disp) this.displacement = new p.Displacement(disp); var size = this.displacement.value.size / 8; this.length += size; this.lengthMax += size; } } protected createImmediates() { const max = 2; // Up to 2 immediates. for(let j = 0; j < max; j++) { const imm = this.ops.getImmediate(j); let immp: ImmediatePart; if(imm) { // If immediate does not have concrete size, use the size of instruction operands. // if(imm.constructor === o.Immediate) { // var ImmediateClass = this.def.getImmediateClass(); // if(ImmediateClass) imm = new ImmediateClass(imm.value, imm.signed); // else { // var size = this.op.size; // imm = o.Immediate.factory(size, imm.value, imm.signed); // imm.extend(size); // } // } // if (this.displacement && (this.displacement.value.size === SIZE.Q)) // throw TypeError(`Cannot have Immediate with ${SIZE.Q} bit Displacement.`); immp = new ImmediatePart(imm); this.immediates[j] = immp; var size = immp.value.size >> 3; this.length += size; this.lengthMax += size; } else { var rel = this.ops.getRelative(j); if(rel) { const immval = Immediate.factory(rel.size, 0); immp = new ImmediatePart(immval); this.immediates[j] = immp; var size = rel.size >> 3; this.length += size; this.lengthMax += size; } } } } } // Wrapper around multiple instructions when different machine instructions // can be used to perform the same task. For example, `jmp` with `rel8` or // `rel32` immediate, or when multiple instruction definitions match provided operands. export class InstructionSetX86 extends InstructionSet<InstructionX86> implements IInstructionX86 { protected cloneOperands() { return this.ops.clone(o.OperandsX86); } proxy (method: string, args: any[] = []): this { for (const ins of this.insn) ins[method].apply(ins, args); return this; } lock (): this { return this.proxy('lock'); } bt () { return this.proxy('bt'); } bnt (){ return this.proxy('bnt'); } rep (){ return this.proxy('rep'); } repe (){ return this.proxy('repe'); } repz (){ return this.proxy('repz'); } repnz (){ return this.proxy('repnz'); } repne (){ return this.proxy('repne'); } cs (){ return this.proxy('cs'); } ss (){ return this.proxy('ss'); } ds (){ return this.proxy('ds'); } es (){ return this.proxy('es'); } fs (){ return this.proxy('fs'); } gs (){ return this.proxy('gs'); } }
the_stack
import * as Types from '../../types'; import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; const defaultOptions = {} export type FetchLnUrlMutationVariables = Types.Exact<{ url: Types.Scalars['String']; }>; export type FetchLnUrlMutation = { __typename?: 'Mutation', fetchLnUrl?: Types.Maybe<{ __typename?: 'ChannelRequest', tag?: Types.Maybe<string>, k1?: Types.Maybe<string>, callback?: Types.Maybe<string>, uri?: Types.Maybe<string> } | { __typename?: 'PayRequest', callback?: Types.Maybe<string>, maxSendable?: Types.Maybe<string>, minSendable?: Types.Maybe<string>, metadata?: Types.Maybe<string>, commentAllowed?: Types.Maybe<number>, tag?: Types.Maybe<string> } | { __typename?: 'WithdrawRequest', callback?: Types.Maybe<string>, k1?: Types.Maybe<string>, maxWithdrawable?: Types.Maybe<string>, defaultDescription?: Types.Maybe<string>, minWithdrawable?: Types.Maybe<string>, tag?: Types.Maybe<string> }> }; export type AuthLnUrlMutationVariables = Types.Exact<{ url: Types.Scalars['String']; }>; export type AuthLnUrlMutation = { __typename?: 'Mutation', lnUrlAuth: { __typename?: 'AuthResponse', status: string, message: string } }; export type PayLnUrlMutationVariables = Types.Exact<{ callback: Types.Scalars['String']; amount: Types.Scalars['Int']; comment?: Types.Maybe<Types.Scalars['String']>; }>; export type PayLnUrlMutation = { __typename?: 'Mutation', lnUrlPay: { __typename?: 'PaySuccess', tag?: Types.Maybe<string>, description?: Types.Maybe<string>, url?: Types.Maybe<string>, message?: Types.Maybe<string>, ciphertext?: Types.Maybe<string>, iv?: Types.Maybe<string> } }; export type WithdrawLnUrlMutationVariables = Types.Exact<{ callback: Types.Scalars['String']; amount: Types.Scalars['Int']; k1: Types.Scalars['String']; description?: Types.Maybe<Types.Scalars['String']>; }>; export type WithdrawLnUrlMutation = { __typename?: 'Mutation', lnUrlWithdraw: string }; export type ChannelLnUrlMutationVariables = Types.Exact<{ callback: Types.Scalars['String']; k1: Types.Scalars['String']; uri: Types.Scalars['String']; }>; export type ChannelLnUrlMutation = { __typename?: 'Mutation', lnUrlChannel: string }; export const FetchLnUrlDocument = gql` mutation FetchLnUrl($url: String!) { fetchLnUrl(url: $url) { ... on WithdrawRequest { callback k1 maxWithdrawable defaultDescription minWithdrawable tag } ... on PayRequest { callback maxSendable minSendable metadata commentAllowed tag } ... on ChannelRequest { tag k1 callback uri } } } `; export type FetchLnUrlMutationFn = Apollo.MutationFunction<FetchLnUrlMutation, FetchLnUrlMutationVariables>; /** * __useFetchLnUrlMutation__ * * To run a mutation, you first call `useFetchLnUrlMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useFetchLnUrlMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [fetchLnUrlMutation, { data, loading, error }] = useFetchLnUrlMutation({ * variables: { * url: // value for 'url' * }, * }); */ export function useFetchLnUrlMutation(baseOptions?: Apollo.MutationHookOptions<FetchLnUrlMutation, FetchLnUrlMutationVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useMutation<FetchLnUrlMutation, FetchLnUrlMutationVariables>(FetchLnUrlDocument, options); } export type FetchLnUrlMutationHookResult = ReturnType<typeof useFetchLnUrlMutation>; export type FetchLnUrlMutationResult = Apollo.MutationResult<FetchLnUrlMutation>; export type FetchLnUrlMutationOptions = Apollo.BaseMutationOptions<FetchLnUrlMutation, FetchLnUrlMutationVariables>; export const AuthLnUrlDocument = gql` mutation AuthLnUrl($url: String!) { lnUrlAuth(url: $url) { status message } } `; export type AuthLnUrlMutationFn = Apollo.MutationFunction<AuthLnUrlMutation, AuthLnUrlMutationVariables>; /** * __useAuthLnUrlMutation__ * * To run a mutation, you first call `useAuthLnUrlMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAuthLnUrlMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [authLnUrlMutation, { data, loading, error }] = useAuthLnUrlMutation({ * variables: { * url: // value for 'url' * }, * }); */ export function useAuthLnUrlMutation(baseOptions?: Apollo.MutationHookOptions<AuthLnUrlMutation, AuthLnUrlMutationVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useMutation<AuthLnUrlMutation, AuthLnUrlMutationVariables>(AuthLnUrlDocument, options); } export type AuthLnUrlMutationHookResult = ReturnType<typeof useAuthLnUrlMutation>; export type AuthLnUrlMutationResult = Apollo.MutationResult<AuthLnUrlMutation>; export type AuthLnUrlMutationOptions = Apollo.BaseMutationOptions<AuthLnUrlMutation, AuthLnUrlMutationVariables>; export const PayLnUrlDocument = gql` mutation PayLnUrl($callback: String!, $amount: Int!, $comment: String) { lnUrlPay(callback: $callback, amount: $amount, comment: $comment) { tag description url message ciphertext iv } } `; export type PayLnUrlMutationFn = Apollo.MutationFunction<PayLnUrlMutation, PayLnUrlMutationVariables>; /** * __usePayLnUrlMutation__ * * To run a mutation, you first call `usePayLnUrlMutation` within a React component and pass it any options that fit your needs. * When your component renders, `usePayLnUrlMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [payLnUrlMutation, { data, loading, error }] = usePayLnUrlMutation({ * variables: { * callback: // value for 'callback' * amount: // value for 'amount' * comment: // value for 'comment' * }, * }); */ export function usePayLnUrlMutation(baseOptions?: Apollo.MutationHookOptions<PayLnUrlMutation, PayLnUrlMutationVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useMutation<PayLnUrlMutation, PayLnUrlMutationVariables>(PayLnUrlDocument, options); } export type PayLnUrlMutationHookResult = ReturnType<typeof usePayLnUrlMutation>; export type PayLnUrlMutationResult = Apollo.MutationResult<PayLnUrlMutation>; export type PayLnUrlMutationOptions = Apollo.BaseMutationOptions<PayLnUrlMutation, PayLnUrlMutationVariables>; export const WithdrawLnUrlDocument = gql` mutation WithdrawLnUrl($callback: String!, $amount: Int!, $k1: String!, $description: String) { lnUrlWithdraw( callback: $callback amount: $amount k1: $k1 description: $description ) } `; export type WithdrawLnUrlMutationFn = Apollo.MutationFunction<WithdrawLnUrlMutation, WithdrawLnUrlMutationVariables>; /** * __useWithdrawLnUrlMutation__ * * To run a mutation, you first call `useWithdrawLnUrlMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useWithdrawLnUrlMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [withdrawLnUrlMutation, { data, loading, error }] = useWithdrawLnUrlMutation({ * variables: { * callback: // value for 'callback' * amount: // value for 'amount' * k1: // value for 'k1' * description: // value for 'description' * }, * }); */ export function useWithdrawLnUrlMutation(baseOptions?: Apollo.MutationHookOptions<WithdrawLnUrlMutation, WithdrawLnUrlMutationVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useMutation<WithdrawLnUrlMutation, WithdrawLnUrlMutationVariables>(WithdrawLnUrlDocument, options); } export type WithdrawLnUrlMutationHookResult = ReturnType<typeof useWithdrawLnUrlMutation>; export type WithdrawLnUrlMutationResult = Apollo.MutationResult<WithdrawLnUrlMutation>; export type WithdrawLnUrlMutationOptions = Apollo.BaseMutationOptions<WithdrawLnUrlMutation, WithdrawLnUrlMutationVariables>; export const ChannelLnUrlDocument = gql` mutation ChannelLnUrl($callback: String!, $k1: String!, $uri: String!) { lnUrlChannel(callback: $callback, k1: $k1, uri: $uri) } `; export type ChannelLnUrlMutationFn = Apollo.MutationFunction<ChannelLnUrlMutation, ChannelLnUrlMutationVariables>; /** * __useChannelLnUrlMutation__ * * To run a mutation, you first call `useChannelLnUrlMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useChannelLnUrlMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [channelLnUrlMutation, { data, loading, error }] = useChannelLnUrlMutation({ * variables: { * callback: // value for 'callback' * k1: // value for 'k1' * uri: // value for 'uri' * }, * }); */ export function useChannelLnUrlMutation(baseOptions?: Apollo.MutationHookOptions<ChannelLnUrlMutation, ChannelLnUrlMutationVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useMutation<ChannelLnUrlMutation, ChannelLnUrlMutationVariables>(ChannelLnUrlDocument, options); } export type ChannelLnUrlMutationHookResult = ReturnType<typeof useChannelLnUrlMutation>; export type ChannelLnUrlMutationResult = Apollo.MutationResult<ChannelLnUrlMutation>; export type ChannelLnUrlMutationOptions = Apollo.BaseMutationOptions<ChannelLnUrlMutation, ChannelLnUrlMutationVariables>;
the_stack
import { list, mount, multi, patch, text, createBlock, VNode, withKey } from "../src"; import { makeTestFixture } from "./helpers"; //------------------------------------------------------------------------------ // Setup and helpers //------------------------------------------------------------------------------ let fixture: HTMLElement; beforeEach(() => { fixture = makeTestFixture(); }); afterEach(() => { fixture.remove(); }); function kText(str: string, key: any): VNode { return withKey(text(str), key); } function n(n: number) { return kText(String(n), n); } const span = createBlock("<span><block-text-0/></span>"); const p = createBlock("<p><block-text-0/></p>"); function kSpan(str: string, key: any): VNode { return withKey(span([str]), key); } function kPair(n: number): VNode { const bnodes = [p([String(n)]), p([String(n)])]; return withKey(multi(bnodes), n); } describe("list node: misc", () => { test("list node", async () => { const bnodes = [1, 2, 3].map((key) => kText(`text${key}`, key)); const tree = list(bnodes); mount(tree, fixture); expect(fixture.innerHTML).toBe("text1text2text3"); }); test("list vnode can be used as text", () => { mount(text(list([text("a"), text("b")]) as any), fixture); expect(fixture.innerHTML).toBe("ab"); }); test("a list block can be removed and leaves nothing", async () => { const bnodes = [ { id: 1, name: "sheep" }, { id: 2, name: "cow" }, ].map((elem) => kText(elem.name, elem.id)); const tree = list(bnodes); expect(fixture.childNodes.length).toBe(0); mount(tree, fixture); expect(fixture.childNodes.length).toBe(3); expect(fixture.innerHTML).toBe("sheepcow"); tree.remove(); expect(fixture.innerHTML).toBe(""); expect(fixture.childNodes.length).toBe(0); }); test("patching a list block inside an elem block", async () => { const block = createBlock("<div><block-child-0/></div>"); const tree = block(); mount(tree, fixture); expect(fixture.innerHTML).toBe("<div></div>"); patch(tree, block([], [list([1, 2, 3].map(n))])); expect(fixture.innerHTML).toBe("<div>123</div>"); patch(tree, block([], [list([])])); expect(fixture.innerHTML).toBe("<div></div>"); patch(tree, block([], [list([1, 2, 3].map(n))])); expect(fixture.innerHTML).toBe("<div>123</div>"); }); test("list of lists", async () => { const tree = list([ withKey(list([kText("a1", "1"), kText("a2", "2")]), "a"), withKey(list([kText("b1", "1"), kText("b2", "2")]), "b"), ]); mount(tree, fixture); expect(fixture.innerHTML).toBe("a1a2b1b2"); patch( tree, list([ withKey(list([kText("b1", "1"), kText("b2", "2")]), "b"), withKey(list([kText("a1", "1"), kText("a2", "2")]), "a"), ]) ); expect(fixture.innerHTML).toBe("b1b2a1a2"); patch( tree, list([ withKey(list([kText("a2", "2"), kText("a1", "1")]), "a"), withKey(list([kText("b2", "2"), kText("b1", "1")]), "b"), ]) ); expect(fixture.innerHTML).toBe("a2a1b2b1"); }); }); describe("adding/removing elements", () => { test("removing elements", () => { const tree = list([kText("a", "a")]); mount(tree, fixture); expect(fixture.innerHTML).toBe("a"); patch(tree, list([])); expect(fixture.innerHTML).toBe(""); }); test("removing 1 elements from 2", () => { const tree = list([kText("a", "a"), kText("b", "b")]); mount(tree, fixture); expect(fixture.innerHTML).toBe("ab"); patch(tree, list([kText("a", "a")])); expect(fixture.innerHTML).toBe("a"); }); test("removing elements", () => { const tree = list([kSpan("a", "a")]); mount(tree, fixture); expect(fixture.innerHTML).toBe("<span>a</span>"); patch(tree, list([])); expect(fixture.innerHTML).toBe(""); }); test("removing elements, variation", () => { const f = (i: number) => { const b = multi([span([`a${i}`]), span([`b${i}`])]); b.key = i; return b; }; const tree = list([f(1), f(2)]); mount(tree, fixture); expect(fixture.innerHTML).toBe("<span>a1</span><span>b1</span><span>a2</span><span>b2</span>"); patch(tree, list([])); expect(fixture.innerHTML).toBe(""); }); test("adding one element at the end", () => { const tree = list([n(1), n(2)]); mount(tree, fixture); expect(fixture.innerHTML).toBe("12"); patch(tree, list([n(1), n(2), n(3)])); expect(fixture.innerHTML).toBe("123"); }); test("adding one element at the end", () => { const tree = list([n(1)]); mount(tree, fixture); expect(fixture.innerHTML).toBe("1"); patch(tree, list([n(1), n(2), n(3)])); expect(fixture.innerHTML).toBe("123"); }); test("prepend elements: 4,5 => 1,2,3,4,5", () => { const tree = list([n(4), n(5)]); mount(tree, fixture); expect(fixture.innerHTML).toBe("45"); patch(tree, list([n(1), n(2), n(3), n(4), n(5)])); expect(fixture.innerHTML).toBe("12345"); }); test("prepend elements: 4,5 => 1,2,3,4,5 (with multi)", () => { const tree = list([kPair(4), kPair(5)]); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p>4</p><p>4</p><p>5</p><p>5</p>"); patch(tree, list([1, 2, 3, 4, 5].map(kPair))); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>" ); }); test("add element in middle: 1,2,4,5 => 1,2,3,4,5", () => { const tree = list([1, 2, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("1245"); patch(tree, list([1, 2, 3, 4, 5].map(n))); expect(fixture.innerHTML).toBe("12345"); }); test("add element in middle: 1,2,4,5 => 1,2,3,4,5 (multi)", () => { const tree = list([1, 2, 4, 5].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>4</p><p>4</p><p>5</p><p>5</p>" ); patch(tree, list([1, 2, 3, 4, 5].map(kPair))); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>" ); }); test("add element at beginning and end: 2,3,4 => 1,2,3,4,5", () => { const tree = list([2, 3, 4].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("234"); patch(tree, list([1, 2, 3, 4, 5].map(n))); expect(fixture.innerHTML).toBe("12345"); }); test("add element at beginning and end: 2,3,4 => 1,2,3,4,5 (multi)", () => { const tree = list([2, 3, 4].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p>"); patch(tree, list([1, 2, 3, 4, 5].map(kPair))); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>" ); }); test("adds children: [] => [1,2,3]", () => { const tree = list([].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe(""); patch(tree, list([1, 2, 3].map(n))); expect(fixture.innerHTML).toBe("123"); }); test("adds children: [] => [1,2,3] (multi)", () => { const tree = list([].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe(""); patch(tree, list([1, 2, 3].map(kPair))); expect(fixture.innerHTML).toBe("<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p>"); }); test("adds children: [] => [1,2,3] (inside elem)", () => { const block = createBlock("<p><block-child-0/></p>"); const tree = block([], []); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p></p>"); patch(tree, block([], [list([1, 2, 3].map(n))])); expect(fixture.innerHTML).toBe("<p>123</p>"); }); test("adds children: [] => [1,2,3] (inside elem, multi)", () => { const block = createBlock("<p><block-child-0/></p>"); const tree = block([], []); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p></p>"); patch(tree, block([], [list([1, 2, 3].map(kPair))])); expect(fixture.innerHTML).toBe("<p><p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p></p>"); }); test("remove children: [1,2,3] => []", () => { const tree = list([1, 2, 3].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("123"); patch(tree, list([].map(n))); expect(fixture.innerHTML).toBe(""); }); test("remove children: [1,2,3] => [] (multi)", () => { const tree = list([1, 2, 3].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p>"); patch(tree, list([].map(kPair))); expect(fixture.innerHTML).toBe(""); }); test("remove children: [1,2,3] => [] (inside elem)", () => { const block = createBlock("<p><block-child-0/></p>"); const tree = block([], [list([1, 2, 3].map(n))]); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p>123</p>"); patch(tree, block([], [list([])])); expect(fixture.innerHTML).toBe("<p></p>"); }); test("remove children from the beginning: [1,2,3,4,5] => [3,4,5]", () => { const tree = list([1, 2, 3, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("12345"); patch(tree, list([3, 4, 5].map(n))); expect(fixture.innerHTML).toBe("345"); }); test("remove children from the beginning: [1,2,3,4,5] => [3,4,5] (multi)", () => { const tree = list([1, 2, 3, 4, 5].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>" ); patch(tree, list([3, 4, 5].map(kPair))); expect(fixture.innerHTML).toBe("<p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>"); }); test("remove children from the end: [1,2,3,4,5] => [1,2,3]", () => { const tree = list([1, 2, 3, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("12345"); patch(tree, list([1, 2, 3].map(n))); expect(fixture.innerHTML).toBe("123"); }); test("remove children from the middle: [1,2,3,4,5] => [1,2,4,5]", () => { const tree = list([1, 2, 3, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("12345"); patch(tree, list([1, 2, 4, 5].map(n))); expect(fixture.innerHTML).toBe("1245"); }); }); describe("element reordering", () => { test("move element forward: [1,2,3,4] => [2,3,1,4]", () => { const tree = list([1, 2, 3, 4].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("1234"); patch(tree, list([2, 3, 1, 4].map(n))); expect(fixture.innerHTML).toBe("2314"); }); test("move element forward: [1,2,3,4] => [2,3,1,4] (multi)", () => { const tree = list([1, 2, 3, 4].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p>" ); patch(tree, list([2, 3, 1, 4].map(kPair))); expect(fixture.innerHTML).toBe( "<p>2</p><p>2</p><p>3</p><p>3</p><p>1</p><p>1</p><p>4</p><p>4</p>" ); }); test("move element to end: [1,2,3] => [2,3,1]", () => { const tree = list([1, 2, 3].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("123"); patch(tree, list([2, 3, 1].map(n))); expect(fixture.innerHTML).toBe("231"); }); test("move element to end: [1,2,3] => [2,3,1] (multi)", () => { const tree = list([1, 2, 3].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe("<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p>"); patch(tree, list([2, 3, 1].map(kPair))); expect(fixture.innerHTML).toBe("<p>2</p><p>2</p><p>3</p><p>3</p><p>1</p><p>1</p>"); }); test("move element backward: [1,2,3,4] => [1,4,2,3]", () => { const tree = list([1, 2, 3, 4].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("1234"); patch(tree, list([1, 4, 2, 3].map(n))); expect(fixture.innerHTML).toBe("1423"); }); test("swaps first and last: [1,2,3,4] => [4,3,2,1]", () => { const tree = list([1, 2, 3, 4].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("1234"); patch(tree, list([4, 3, 2, 1].map(n))); expect(fixture.innerHTML).toBe("4321"); }); }); describe("miscellaneous operations", () => { test("move to left and replace: [1,2,3,4,5] => [4,1,2,3,6]", () => { const tree = list([1, 2, 3, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("12345"); patch(tree, list([4, 1, 2, 3, 6].map(n))); expect(fixture.innerHTML).toBe("41236"); }); test("move to left and replace: [1,2,3,4,5] => [4,1,2,3,6] (multi)", () => { const tree = list([1, 2, 3, 4, 5].map(kPair)); mount(tree, fixture); expect(fixture.innerHTML).toBe( "<p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>4</p><p>4</p><p>5</p><p>5</p>" ); patch(tree, list([4, 1, 2, 3, 6].map(kPair))); expect(fixture.innerHTML).toBe( "<p>4</p><p>4</p><p>1</p><p>1</p><p>2</p><p>2</p><p>3</p><p>3</p><p>6</p><p>6</p>" ); }); test("move to left and leave hole: [1,4,5] => [4,6]", () => { const tree = list([1, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("145"); patch(tree, list([4, 6].map(n))); expect(fixture.innerHTML).toBe("46"); }); test("[2,4,5] => [4,5,3]", () => { const tree = list([2, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("245"); patch(tree, list([4, 5, 3].map(n))); expect(fixture.innerHTML).toBe("453"); }); test("reverse elements [1,2,3,4,5,6,7,8] => [8,7,6,5,4,3,2,1]", () => { const tree = list([1, 2, 3, 4, 5, 6, 7, 8].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("12345678"); patch(tree, list([8, 7, 6, 5, 4, 3, 2, 1].map(n))); expect(fixture.innerHTML).toBe("87654321"); }); test("some permutation [0,1,2,3,4,5] => [4,3,2,1,5,0]", () => { const tree = list([0, 1, 2, 3, 4, 5].map(n)); mount(tree, fixture); expect(fixture.innerHTML).toBe("012345"); patch(tree, list([4, 3, 2, 1, 5, 0].map(n))); expect(fixture.innerHTML).toBe("432150"); }); });
the_stack
import { action } from 'typesafe-actions' import { ChainId } from '@dcl/schemas' import { buildTransactionPayload } from 'decentraland-dapps/dist/modules/transaction/utils' import { Item } from 'modules/item/types' import { Collection, Mint, Access } from './types' // Fetch collections export const FETCH_COLLECTIONS_REQUEST = '[Request] Fetch Collections' export const FETCH_COLLECTIONS_SUCCESS = '[Success] Fetch Collections' export const FETCH_COLLECTIONS_FAILURE = '[Failure] Fetch Collections' export const fetchCollectionsRequest = (address?: string) => action(FETCH_COLLECTIONS_REQUEST, { address }) export const fetchCollectionsSuccess = (collections: Collection[]) => action(FETCH_COLLECTIONS_SUCCESS, { collections }) export const fetchCollectionsFailure = (error: string) => action(FETCH_COLLECTIONS_FAILURE, { error }) export type FetchCollectionsRequestAction = ReturnType<typeof fetchCollectionsRequest> export type FetchCollectionsSuccessAction = ReturnType<typeof fetchCollectionsSuccess> export type FetchCollectionsFailureAction = ReturnType<typeof fetchCollectionsFailure> // Fetch collection export const FETCH_COLLECTION_REQUEST = '[Request] Fetch Collection' export const FETCH_COLLECTION_SUCCESS = '[Success] Fetch Collection' export const FETCH_COLLECTION_FAILURE = '[Failure] Fetch Collection' export const fetchCollectionRequest = (id: string) => action(FETCH_COLLECTION_REQUEST, { id }) export const fetchCollectionSuccess = (id: string, collection: Collection) => action(FETCH_COLLECTION_SUCCESS, { id, collection }) export const fetchCollectionFailure = (id: string, error: string) => action(FETCH_COLLECTION_FAILURE, { id, error }) export type FetchCollectionRequestAction = ReturnType<typeof fetchCollectionRequest> export type FetchCollectionSuccessAction = ReturnType<typeof fetchCollectionSuccess> export type FetchCollectionFailureAction = ReturnType<typeof fetchCollectionFailure> // Save collection export const SAVE_COLLECTION_REQUEST = '[Request] Save Collection' export const SAVE_COLLECTION_SUCCESS = '[Success] Save Collection' export const SAVE_COLLECTION_FAILURE = '[Failure] Save Collection' export const saveCollectionRequest = (collection: Collection) => action(SAVE_COLLECTION_REQUEST, { collection }) export const saveCollectionSuccess = (collection: Collection) => action(SAVE_COLLECTION_SUCCESS, { collection }) export const saveCollectionFailure = (collection: Collection, error: string) => action(SAVE_COLLECTION_FAILURE, { collection, error }) export type SaveCollectionRequestAction = ReturnType<typeof saveCollectionRequest> export type SaveCollectionSuccessAction = ReturnType<typeof saveCollectionSuccess> export type SaveCollectionFailureAction = ReturnType<typeof saveCollectionFailure> // Delete collection export const DELETE_COLLECTION_REQUEST = '[Request] Delete Collection' export const DELETE_COLLECTION_SUCCESS = '[Success] Delete Collection' export const DELETE_COLLECTION_FAILURE = '[Failure] Delete Collection' export const deleteCollectionRequest = (collection: Collection) => action(DELETE_COLLECTION_REQUEST, { collection }) export const deleteCollectionSuccess = (collection: Collection) => action(DELETE_COLLECTION_SUCCESS, { collection }) export const deleteCollectionFailure = (collection: Collection, error: string) => action(DELETE_COLLECTION_FAILURE, { collection, error }) export type DeleteCollectionRequestAction = ReturnType<typeof deleteCollectionRequest> export type DeleteCollectionSuccessAction = ReturnType<typeof deleteCollectionSuccess> export type DeleteCollectionFailureAction = ReturnType<typeof deleteCollectionFailure> // Publish collection export const PUBLISH_COLLECTION_REQUEST = '[Request] Publish Collection' export const PUBLISH_COLLECTION_SUCCESS = '[Success] Publish Collection' export const PUBLISH_COLLECTION_FAILURE = '[Failure] Publish Collection' export const publishCollectionRequest = (collection: Collection, items: Item[], email: string) => action(PUBLISH_COLLECTION_REQUEST, { collection, items, email }) export const publishCollectionSuccess = (collection: Collection, items: Item[], chainId: ChainId, txHash: string) => action(PUBLISH_COLLECTION_SUCCESS, { collection, items, ...buildTransactionPayload(chainId, txHash, { collection, items }) }) export const publishCollectionFailure = (collection: Collection, items: Item[], error: string) => action(PUBLISH_COLLECTION_FAILURE, { collection, items, error }) export type PublishCollectionRequestAction = ReturnType<typeof publishCollectionRequest> export type PublishCollectionSuccessAction = ReturnType<typeof publishCollectionSuccess> export type PublishCollectionFailureAction = ReturnType<typeof publishCollectionFailure> // Mint collection tokens export const MINT_COLLECTION_ITEMS_REQUEST = '[Request] Mint collection items' export const MINT_COLLECTION_ITEMS_SUCCESS = '[Success] Mint collection items' export const MINT_COLLECTION_ITEMS_FAILURE = '[Failure] Mint collection items' export const mintCollectionItemsRequest = (collection: Collection, mints: Mint[]) => action(MINT_COLLECTION_ITEMS_REQUEST, { collection, mints }) export const mintCollectionItemsSuccess = (collection: Collection, mints: Mint[], chainId: ChainId, txHash: string) => action(MINT_COLLECTION_ITEMS_SUCCESS, { collection, mints, ...buildTransactionPayload(chainId, txHash, { collection, mints }) }) export const mintCollectionItemsFailure = (collection: Collection, mints: Mint[], error: string) => action(MINT_COLLECTION_ITEMS_FAILURE, { collection, mints, error }) export type MintCollectionItemsRequestAction = ReturnType<typeof mintCollectionItemsRequest> export type MintCollectionItemsSuccessAction = ReturnType<typeof mintCollectionItemsSuccess> export type MintCollectionItemsFailureAction = ReturnType<typeof mintCollectionItemsFailure> // Set collection minters export const SET_COLLECTION_MINTERS_REQUEST = '[Request] Set collection minters' export const SET_COLLECTION_MINTERS_SUCCESS = '[Success] Set collection minters' export const SET_COLLECTION_MINTERS_FAILURE = '[Failure] Set collection minters' export const setCollectionMintersRequest = (collection: Collection, accessList: Access[]) => action(SET_COLLECTION_MINTERS_REQUEST, { collection, accessList }) export const setCollectionMintersSuccess = (collection: Collection, minters: string[], chainId: ChainId, txHash: string) => action(SET_COLLECTION_MINTERS_SUCCESS, { collection, minters, ...buildTransactionPayload(chainId, txHash, { collection, minters }) }) export const setCollectionMintersFailure = (collection: Collection, accessList: Access[], error: string) => action(SET_COLLECTION_MINTERS_FAILURE, { collection, accessList, error }) export type SetCollectionMintersRequestAction = ReturnType<typeof setCollectionMintersRequest> export type SetCollectionMintersSuccessAction = ReturnType<typeof setCollectionMintersSuccess> export type SetCollectionMintersFailureAction = ReturnType<typeof setCollectionMintersFailure> // Set collection minters export const SET_COLLECTION_MANAGERS_REQUEST = '[Request] Set collection managers' export const SET_COLLECTION_MANAGERS_SUCCESS = '[Success] Set collection managers' export const SET_COLLECTION_MANAGERS_FAILURE = '[Failure] Set collection managers' export const setCollectionManagersRequest = (collection: Collection, accessList: Access[]) => action(SET_COLLECTION_MANAGERS_REQUEST, { collection, accessList }) export const setCollectionManagersSuccess = (collection: Collection, managers: string[], chainId: ChainId, txHash: string) => action(SET_COLLECTION_MANAGERS_SUCCESS, { collection, managers, ...buildTransactionPayload(chainId, txHash, { collection, managers }) }) export const setCollectionManagersFailure = (collection: Collection, accessList: Access[], error: string) => action(SET_COLLECTION_MANAGERS_FAILURE, { collection, accessList, error }) export type SetCollectionManagersRequestAction = ReturnType<typeof setCollectionManagersRequest> export type SetCollectionManagersSuccessAction = ReturnType<typeof setCollectionManagersSuccess> export type SetCollectionManagersFailureAction = ReturnType<typeof setCollectionManagersFailure> // Approve collection export const APPROVE_COLLECTION_REQUEST = '[Request] Approve collection' export const APPROVE_COLLECTION_SUCCESS = '[Success] Approve collection' export const APPROVE_COLLECTION_FAILURE = '[Failure] Approve collection' export const approveCollectionRequest = (collection: Collection) => action(APPROVE_COLLECTION_REQUEST, { collection }) export const approveCollectionSuccess = (collection: Collection, chainId: ChainId, txHash: string) => action(APPROVE_COLLECTION_SUCCESS, { collection, ...buildTransactionPayload(chainId, txHash, { collection }) }) export const approveCollectionFailure = (collection: Collection, error: string) => action(APPROVE_COLLECTION_FAILURE, { collection, error }) export type ApproveCollectionRequestAction = ReturnType<typeof approveCollectionRequest> export type ApproveCollectionSuccessAction = ReturnType<typeof approveCollectionSuccess> export type ApproveCollectionFailureAction = ReturnType<typeof approveCollectionFailure> // Reject collection export const REJECT_COLLECTION_REQUEST = '[Request] Reject collection' export const REJECT_COLLECTION_SUCCESS = '[Success] Reject collection' export const REJECT_COLLECTION_FAILURE = '[Failure] Reject collection' export const rejectCollectionRequest = (collection: Collection) => action(REJECT_COLLECTION_REQUEST, { collection }) export const rejectCollectionSuccess = (collection: Collection, chainId: ChainId, txHash: string) => action(REJECT_COLLECTION_SUCCESS, { collection, ...buildTransactionPayload(chainId, txHash, { collection }) }) export const rejectCollectionFailure = (collection: Collection, error: string) => action(REJECT_COLLECTION_FAILURE, { collection, error }) export type RejectCollectionRequestAction = ReturnType<typeof rejectCollectionRequest> export type RejectCollectionSuccessAction = ReturnType<typeof rejectCollectionSuccess> export type RejectCollectionFailureAction = ReturnType<typeof rejectCollectionFailure> // Initiate Approval Flow export const INITIATE_APPROVAL_FLOW = 'Initate Approval Flow' export const initiateApprovalFlow = (collection: Collection) => action(INITIATE_APPROVAL_FLOW, { collection }) export type InitiateApprovalFlowAction = ReturnType<typeof initiateApprovalFlow>
the_stack
import React, { useCallback, useDebugValue, useEffect, useMemo, useRef, useReducer } from "react" import globalScope, { MockAbortController, noop } from "./globalScope" import { neverSettle, ActionTypes, init, dispatchMiddleware, reducer as asyncReducer, } from "./reducer" import { AsyncAction, AsyncOptions, AsyncState, AbstractState, PromiseFn, Meta, AsyncInitial, AsyncFulfilled, AsyncPending, AsyncRejected, } from "./types" /** * Due to https://github.com/microsoft/web-build-tools/issues/1050, we need * AbstractState imported in this file, even though it is only used implicitly. * This _uses_ AbstractState so it is not accidentally removed by someone. */ declare type ImportWorkaround<T> = | AbstractState<T> | AsyncInitial<T> | AsyncFulfilled<T> | AsyncPending<T> | AsyncRejected<T> export interface FetchOptions<T> extends AsyncOptions<T> { defer?: boolean json?: boolean } function useAsync<T>(options: AsyncOptions<T>): AsyncState<T> function useAsync<T>(promiseFn: PromiseFn<T>, options?: AsyncOptions<T>): AsyncState<T> function useAsync<T>(arg1: AsyncOptions<T> | PromiseFn<T>, arg2?: AsyncOptions<T>): AsyncState<T> { const options: AsyncOptions<T> = typeof arg1 === "function" ? { ...arg2, promiseFn: arg1, } : arg1 const counter = useRef(0) const isMounted = useRef(true) const lastArgs = useRef<any[] | undefined>(undefined) const lastOptions = useRef<AsyncOptions<T>>(options) const lastPromise = useRef<Promise<T>>(neverSettle) const abortController = useRef<AbortController>(new MockAbortController()) const { devToolsDispatcher } = globalScope.__REACT_ASYNC__ const { reducer, dispatcher = devToolsDispatcher } = options const [state, _dispatch] = useReducer( reducer ? (state: AsyncState<T>, action: AsyncAction<T>) => reducer(state, action, asyncReducer) : asyncReducer, options, init ) const dispatch = useCallback( dispatcher ? action => dispatcher(action, dispatchMiddleware(_dispatch), lastOptions.current) : dispatchMiddleware(_dispatch), [dispatcher] ) const { debugLabel } = options const getMeta: <M extends Meta = Meta>(meta?: M) => M = useCallback( (meta?) => ({ counter: counter.current, promise: lastPromise.current, debugLabel, ...meta, } as any), [debugLabel] ) const setData = useCallback( (data, callback = noop) => { if (isMounted.current) { dispatch({ type: ActionTypes.fulfill, payload: data, meta: getMeta(), }) callback() } return data }, [dispatch, getMeta] ) const setError = useCallback( (error, callback = noop) => { if (isMounted.current) { dispatch({ type: ActionTypes.reject, payload: error, error: true, meta: getMeta(), }) callback() } return error }, [dispatch, getMeta] ) const { onResolve, onReject } = options const handleResolve = useCallback( count => (data: T) => count === counter.current && setData(data, () => onResolve && onResolve(data)), [setData, onResolve] ) const handleReject = useCallback( count => (err: Error) => count === counter.current && setError(err, () => onReject && onReject(err)), [setError, onReject] ) const start = useCallback( promiseFn => { if ("AbortController" in globalScope) { abortController.current.abort() abortController.current = new globalScope.AbortController!() } counter.current++ return (lastPromise.current = new Promise((resolve, reject) => { if (!isMounted.current) return const executor = () => promiseFn().then(resolve, reject) dispatch({ type: ActionTypes.start, payload: executor, meta: getMeta(), }) })) }, [dispatch, getMeta] ) const { promise, promiseFn, initialValue } = options const load = useCallback(() => { const isPreInitialized = initialValue && counter.current === 0 if (promise) { start(() => promise) .then(handleResolve(counter.current)) .catch(handleReject(counter.current)) } else if (promiseFn && !isPreInitialized) { start(() => promiseFn(lastOptions.current, abortController.current)) .then(handleResolve(counter.current)) .catch(handleReject(counter.current)) } }, [start, promise, promiseFn, initialValue, handleResolve, handleReject]) const { deferFn } = options const run = useCallback( (...args) => { if (deferFn) { lastArgs.current = args start(() => deferFn(args, lastOptions.current, abortController.current)) .then(handleResolve(counter.current)) .catch(handleReject(counter.current)) } }, [start, deferFn, handleResolve, handleReject] ) const reload = useCallback(() => { lastArgs.current ? run(...lastArgs.current) : load() }, [run, load]) const { onCancel } = options const cancel = useCallback(() => { onCancel && onCancel() counter.current++ abortController.current.abort() isMounted.current && dispatch({ type: ActionTypes.cancel, meta: getMeta(), }) }, [onCancel, dispatch, getMeta]) /* These effects should only be triggered on changes to specific props */ /* eslint-disable react-hooks/exhaustive-deps */ const { watch, watchFn } = options useEffect(() => { if (watchFn && lastOptions.current && watchFn(options, lastOptions.current)) { lastOptions.current = options load() } }) useEffect(() => { lastOptions.current = options }, [options]) useEffect(() => { if (counter.current) cancel() if (promise || promiseFn) load() }, [promise, promiseFn, watch]) useEffect( () => () => { isMounted.current = false }, [] ) useEffect(() => () => cancel(), []) /* eslint-enable react-hooks/exhaustive-deps */ useDebugValue(state, ({ status }) => `[${counter.current}] ${status}`) if (options.suspense && state.isPending && lastPromise.current !== neverSettle) { // Rely on Suspense to handle the loading state throw lastPromise.current } return useMemo( () => ({ ...state, run, reload, cancel, setData, setError, } as AsyncState<T>), [state, run, reload, cancel, setData, setError] ) } export class FetchError extends Error { constructor(public response: Response) { super(`${response.status} ${response.statusText}`) /* istanbul ignore next */ if (Object.setPrototypeOf) { // Not available in IE 10, but can be polyfilled Object.setPrototypeOf(this, FetchError.prototype) } } } const parseResponse = (accept: undefined | string, json: undefined | boolean) => ( res: Response ) => { if (!res.ok) return Promise.reject(new FetchError(res)) if (typeof json === "boolean") return json ? res.json() : res return accept === "application/json" ? res.json() : res } type OverrideParams = { resource?: RequestInfo } & Partial<RequestInit> interface FetchRun<T> extends Omit<AbstractState<T>, "run"> { run(overrideParams: (params?: OverrideParams) => OverrideParams): void run(overrideParams: OverrideParams): void run(ignoredEvent: React.SyntheticEvent): void run(ignoredEvent: Event): void run(): void } type FetchRunArgs = | [(params?: OverrideParams) => OverrideParams] | [OverrideParams] | [React.SyntheticEvent] | [Event] | [] function isEvent(e: FetchRunArgs[0]): e is Event | React.SyntheticEvent { return typeof e === "object" && "preventDefault" in e } /** * * @param {RequestInfo} resource * @param {RequestInit} init * @param {FetchOptions} options * @returns {AsyncState<T, FetchRun<T>>} */ function useAsyncFetch<T>( resource: RequestInfo, init: RequestInit, { defer, json, ...options }: FetchOptions<T> = {} ): AsyncState<T, FetchRun<T>> { const method = (resource as Request).method || (init && init.method) const headers: Headers & Record<string, any> = (resource as Request).headers || (init && init.headers) || {} const accept: string | undefined = headers["Accept"] || headers["accept"] || (headers.get && headers.get("accept")) const doFetch = (input: RequestInfo, init: RequestInit) => globalScope.fetch(input, init).then(parseResponse(accept, json)) const isDefer = typeof defer === "boolean" ? defer : ["POST", "PUT", "PATCH", "DELETE"].indexOf(method!) !== -1 const fn = isDefer ? "deferFn" : "promiseFn" const identity = JSON.stringify({ resource, init, isDefer, }) const promiseFn = useCallback( (_: AsyncOptions<T>, { signal }: AbortController) => { return doFetch(resource, { signal, ...init }) }, [identity] // eslint-disable-line react-hooks/exhaustive-deps ) const deferFn = useCallback( function([override]: FetchRunArgs, _: AsyncOptions<T>, { signal }: AbortController) { if (!override || isEvent(override)) { return doFetch(resource, { signal, ...init }) } if (typeof override === "function") { const { resource: runResource, ...runInit } = override({ resource, signal, ...init }) return doFetch(runResource || resource, { signal, ...runInit }) } const { resource: runResource, ...runInit } = override return doFetch(runResource || resource, { signal, ...init, ...runInit }) }, [identity] // eslint-disable-line react-hooks/exhaustive-deps ) const state = useAsync({ ...options, [fn]: isDefer ? deferFn : promiseFn, }) useDebugValue(state, ({ counter, status }) => `[${counter}] ${status}`) return state } const unsupported = () => { throw new Error( "useAsync requires React v16.8 or up. Upgrade your React version or use the <Async> component instead." ) } // @ts-ignore export default useEffect ? useAsync : unsupported // @ts-ignore export const useFetch = useEffect ? useAsyncFetch : unsupported
the_stack
jest.unmock('events'); jest.unmock('../../src/JestExt/core'); jest.unmock('../../src/JestExt/helper'); jest.unmock('../../src/appGlobals'); jest.unmock('../test-helper'); jest.mock('../../src/DebugCodeLens', () => ({ DebugCodeLensProvider: class MockCodeLensProvider {}, })); jest.mock('os'); jest.mock('../../src/decorations/test-status', () => ({ TestStatus: jest.fn(), })); const sbUpdateMock = jest.fn(); const statusBar = { bind: () => ({ update: sbUpdateMock, }), }; jest.mock('../../src/StatusBar', () => ({ statusBar })); jest.mock('jest-editor-support'); import * as vscode from 'vscode'; import { JestExt } from '../../src/JestExt/core'; import { createProcessSession } from '../../src/JestExt/process-session'; import { TestStatus } from '../../src/decorations/test-status'; import { updateCurrentDiagnostics, updateDiagnostics } from '../../src/diagnostics'; import { CoverageMapProvider } from '../../src/Coverage'; import * as helper from '../../src/helpers'; import { TestIdentifier, resultsWithLowerCaseWindowsDriveLetters } from '../../src/TestResults'; import * as messaging from '../../src/messaging'; import { PluginResourceSettings } from '../../src/Settings'; import * as extHelper from '../..//src/JestExt/helper'; import { workspaceLogging } from '../../src/logging'; import { ProjectWorkspace } from 'jest-editor-support'; import { mockProjectWorkspace, mockWworkspaceLogging } from '../test-helper'; import { startWizard } from '../../src/setup-wizard'; import { JestTestProvider } from '../../src/test-provider'; /* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "expectItTakesNoAction"] }] */ const mockHelpers = helper as jest.Mocked<any>; const EmptySortedResult = { fail: [], skip: [], success: [], unknown: [], }; const mockGetExtensionResourceSettings = jest.spyOn(extHelper, 'getExtensionResourceSettings'); describe('JestExt', () => { const getConfiguration = vscode.workspace.getConfiguration as jest.Mock<any>; const StateDecorationsMock = TestStatus as jest.Mock; const context: any = { asAbsolutePath: (text) => text } as vscode.ExtensionContext; const workspaceFolder = { name: 'test-folder' } as any; const channelStub = { appendLine: jest.fn(), append: jest.fn(), clear: jest.fn(), show: jest.fn(), dispose: jest.fn(), } as any; const extensionSettings = { debugCodeLens: {}, testExplorer: { enabled: true } } as any; const debugCodeLensProvider = {} as any; const debugConfigurationProvider = { provideDebugConfigurations: jest.fn(), prepareTestRun: jest.fn(), } as any; const mockProcessSession = { start: jest.fn(), stop: jest.fn(), scheduleProcess: jest.fn(), }; console.error = jest.fn(); console.warn = jest.fn(); const newJestExt = (override?: { settings?: Partial<PluginResourceSettings>; coverageCodeLensProvider?: any; }) => { mockGetExtensionResourceSettings.mockReturnValue( override?.settings ? { ...extensionSettings, ...override.settings } : extensionSettings ); const coverageCodeLensProvider: any = override?.coverageCodeLensProvider ?? { coverageChanged: jest.fn(), }; return new JestExt( context, workspaceFolder, debugCodeLensProvider, debugConfigurationProvider, coverageCodeLensProvider ); }; const mockEditor = (fileName: string, languageId = 'typescript'): any => { return { document: { fileName, languageId, uri: fileName }, setDecorations: jest.fn(), }; }; const mockTestProvider: any = { dispose: jest.fn(), }; beforeEach(() => { jest.resetAllMocks(); getConfiguration.mockReturnValue({}); (vscode.window.createOutputChannel as jest.Mocked<any>).mockReturnValue(channelStub); (createProcessSession as jest.Mocked<any>).mockReturnValue(mockProcessSession); (ProjectWorkspace as jest.Mocked<any>).mockImplementation(mockProjectWorkspace); (workspaceLogging as jest.Mocked<any>).mockImplementation(mockWworkspaceLogging); (JestTestProvider as jest.Mocked<any>).mockImplementation(() => mockTestProvider); (vscode.EventEmitter as jest.Mocked<any>) = jest.fn().mockImplementation(() => { return { fire: jest.fn(), event: jest.fn(), dispose: jest.fn() }; }); }); describe('debugTests()', () => { const makeIdentifier = (title: string, ancestors?: string[]): TestIdentifier => ({ title, ancestorTitles: ancestors || [], }); const fileName = 'fileName'; const document: any = { fileName }; let sut: JestExt; let startDebugging, debugConfiguration; const mockShowQuickPick = jest.fn(); let mockConfigurations = []; beforeEach(() => { startDebugging = vscode.debug.startDebugging as unknown as jest.Mock<{}>; (startDebugging as unknown as jest.Mock<{}>).mockImplementation( async (_folder: any, nameOrConfig: any) => { // trigger fallback to default configuration if (typeof nameOrConfig === 'string') { throw null; } } ); debugConfiguration = { type: 'dummyconfig' }; debugConfigurationProvider.provideDebugConfigurations.mockReturnValue([debugConfiguration]); vscode.window.showQuickPick = mockShowQuickPick; mockHelpers.escapeRegExp.mockImplementation((s) => s); mockHelpers.testIdString.mockImplementation((_, s) => s); mockConfigurations = []; vscode.workspace.getConfiguration = jest.fn().mockReturnValue({ get: jest.fn(() => mockConfigurations), }); sut = newJestExt(); }); describe('should run the supplied test', () => { it.each([[document], ['fileName']])('support document paramter: %s', async (doc) => { const testNamePattern = 'testNamePattern'; await sut.debugTests(doc, testNamePattern); expect(vscode.debug.startDebugging).toHaveBeenCalledWith( workspaceFolder, debugConfiguration ); const configuration = startDebugging.mock.calls[startDebugging.mock.calls.length - 1][1]; expect(configuration).toBeDefined(); expect(configuration.type).toBe('dummyconfig'); expect(sut.debugConfigurationProvider.prepareTestRun).toBeCalledWith( fileName, testNamePattern ); }); }); it('can handle testIdentifier argument', async () => { const tId = makeIdentifier('test-1', ['d-1', 'd-1-1']); const fullName = 'd-1 d-1-1 test-1'; mockHelpers.testIdString.mockReturnValue(fullName); await sut.debugTests(document, tId); expect(vscode.debug.startDebugging).toHaveBeenCalledWith(workspaceFolder, debugConfiguration); const configuration = startDebugging.mock.calls[startDebugging.mock.calls.length - 1][1]; expect(configuration).toBeDefined(); expect(configuration.type).toBe('dummyconfig'); // test identifier is cleaned up before debug expect(mockHelpers.testIdString).toBeCalledWith('full-name', tId); expect(sut.debugConfigurationProvider.prepareTestRun).toBeCalledWith(fileName, fullName); }); it.each` desc | testIds | testIdStringCount | startDebug ${'0 id'} | ${[]} | ${0} | ${false} ${'1 string id '} | ${['test-1']} | ${0} | ${true} ${'1 testIdentifier id '} | ${[makeIdentifier('test-1', ['d-1'])]} | ${1} | ${true} `('no selection needed: $desc', async ({ testIds, testIdStringCount, startDebug }) => { await sut.debugTests(document, ...testIds); expect(mockShowQuickPick).not.toBeCalled(); expect(mockHelpers.testIdString).toBeCalledTimes(testIdStringCount); if (testIdStringCount >= 1) { expect(mockHelpers.testIdString).toHaveBeenLastCalledWith('full-name', testIds[0]); expect(mockHelpers.escapeRegExp).toHaveBeenCalled(); } if (startDebug) { expect(vscode.debug.startDebugging).toHaveBeenCalledWith( workspaceFolder, debugConfiguration ); const configuration = startDebugging.mock.calls[startDebugging.mock.calls.length - 1][1]; expect(configuration).toBeDefined(); expect(configuration.type).toBe('dummyconfig'); expect(sut.debugConfigurationProvider.prepareTestRun).toHaveBeenCalled(); } else { expect(sut.debugConfigurationProvider.prepareTestRun).not.toHaveBeenCalled(); expect(vscode.debug.startDebugging).not.toHaveBeenCalled(); } }); describe('paramerterized test', () => { describe.each` desc | tId1 | tId2 | tId3 | selectIdx ${'testIdentifiers'} | ${makeIdentifier('test-1', ['d-1'])} | ${makeIdentifier('test-2', ['d-1'])} | ${makeIdentifier('test-3', ['d-1'])} | ${0} ${'string ids'} | ${'d-1 test-1'} | ${'d-1 test-2'} | ${'d-1 test-3'} | ${2} ${'mixed ids'} | ${'d-1 test-1'} | ${makeIdentifier('test-2', ['d-1'])} | ${'d-1 test-3'} | ${1} `('with $desc', ({ tId1, tId2, tId3, selectIdx }) => { let identifierIdCount = 0; beforeEach(() => { mockShowQuickPick.mockImplementation((items) => Promise.resolve(items[selectIdx])); identifierIdCount = [tId1, tId2, tId3].filter((id) => typeof id !== 'string').length; }); it('can run selected test', async () => { // user choose the 2nd test: tId2 await sut.debugTests(document, tId1, tId2, tId3); // user has made selection to choose from 3 candidates expect(mockShowQuickPick).toHaveBeenCalledTimes(1); const [items] = mockShowQuickPick.mock.calls[0]; expect(items).toHaveLength(3); const hasIds = () => { // id string is called 4 times: 3 to construt the quickPickIems, the last one is for jest test fullName expect(mockHelpers.testIdString).toBeCalledTimes(identifierIdCount + 1); const calls = mockHelpers.testIdString.mock.calls; expect( calls.slice(0, identifierIdCount).every((c) => c[0] === 'display-reverse') ).toBeTruthy(); expect(calls[calls.length - 1][0]).toEqual('full-name'); }; const hasNoId = () => { expect(mockHelpers.testIdString).toBeCalledTimes(0); }; if (identifierIdCount) { hasIds(); } else { hasNoId(); } const selected = [tId1, tId2, tId3][selectIdx]; expect(mockHelpers.escapeRegExp).toBeCalledWith(selected); // verify the actual test to be run is the one we selected: tId2 expect(vscode.debug.startDebugging).toHaveBeenCalledWith( workspaceFolder, debugConfiguration ); const configuration = startDebugging.mock.calls[startDebugging.mock.calls.length - 1][1]; expect(configuration).toBeDefined(); expect(configuration.type).toBe('dummyconfig'); expect(sut.debugConfigurationProvider.prepareTestRun).toBeCalledWith(fileName, selected); }); it('if user did not choose any test, no debug will be run', async () => { selectIdx = -1; await sut.debugTests(document, tId1, tId2, tId3); expect(mockShowQuickPick).toHaveBeenCalledTimes(1); expect(vscode.debug.startDebugging).not.toHaveBeenCalled(); }); it('if pass zero testId, nothing will be run', async () => { await sut.debugTests(document); expect(mockShowQuickPick).not.toHaveBeenCalled(); expect(mockHelpers.testIdString).not.toBeCalled(); expect(vscode.debug.startDebugging).not.toHaveBeenCalled(); }); }); }); it.each` configNames | shouldShowWarning | debugMode | v2 ${undefined} | ${true} | ${true} | ${false} ${[]} | ${true} | ${true} | ${false} ${['a', 'b']} | ${true} | ${false} | ${false} ${['a', 'vscode-jest-tests.v2', 'b']} | ${false} | ${false} | ${true} ${['a', 'vscode-jest-tests', 'b']} | ${false} | ${false} | ${false} `( 'provides setup wizard in warning message if no "vscode-jest-tests" in launch.json: $configNames', async ({ configNames, shouldShowWarning, debugMode, v2 }) => { expect.hasAssertions(); const testNamePattern = 'testNamePattern'; mockConfigurations = configNames ? configNames.map((name) => ({ name })) : undefined; // mockProjectWorkspace.debug = debugMode; sut = newJestExt({ settings: { debugMode } }); await sut.debugTests(document, testNamePattern); expect(startDebugging).toBeCalledTimes(1); if (shouldShowWarning) { // debug with generated config expect(vscode.debug.startDebugging).toHaveBeenLastCalledWith( workspaceFolder, debugConfiguration ); } else { // debug with existing config expect(vscode.debug.startDebugging).toHaveBeenLastCalledWith(workspaceFolder, { name: v2 ? 'vscode-jest-tests.v2' : 'vscode-jest-tests', }); } expect(sut.debugConfigurationProvider.prepareTestRun).toBeCalledWith( fileName, testNamePattern ); if (shouldShowWarning) { expect(messaging.systemWarningMessage).toHaveBeenCalled(); //verify the message button does invoke the setup wizard command const button = (messaging.systemWarningMessage as jest.Mocked<any>).mock.calls[0][1]; expect(button.action).not.toBeUndefined(); vscode.commands.executeCommand = jest.fn(); button.action(); expect(startWizard).toBeCalledWith(sut.debugConfigurationProvider, { workspace: workspaceFolder, taskId: 'debugConfig', verbose: debugMode, }); } else { expect(messaging.systemWarningMessage).not.toHaveBeenCalled(); } } ); }); describe('onDidCloseTextDocument()', () => { const document = {} as any; let sut; beforeEach(() => { sut = newJestExt(); sut.removeCachedTestResults = jest.fn(); sut.removeCachedDecorationTypes = jest.fn(); }); it('should remove the cached test results', () => { sut.onDidCloseTextDocument(document); expect(sut.removeCachedTestResults).toBeCalledWith(document); }); }); describe('removeCachedTestResults()', () => { let sut; beforeEach(() => { sut = newJestExt(); sut.testResultProvider.removeCachedResults = jest.fn(); }); it('should do nothing when the document is falsy', () => { sut.removeCachedTestResults(null); expect(sut.testResultProvider.removeCachedResults).not.toBeCalled(); }); it('should do nothing when the document is untitled', () => { const document: any = { isUntitled: true } as any; sut.removeCachedTestResults(document); expect(sut.testResultProvider.removeCachedResults).not.toBeCalled(); }); it('should reset the test result cache for the document', () => { const expected = 'file.js'; sut.removeCachedTestResults({ fileName: expected } as any); expect(sut.testResultProvider.removeCachedResults).toBeCalledWith(expected); }); it('can invalidate test results', () => { const expected = 'file.js'; sut.removeCachedTestResults({ fileName: expected } as any, true); expect(sut.testResultProvider.removeCachedResults).not.toBeCalled(); expect(sut.testResultProvider.invalidateTestResults).toBeCalledWith(expected); }); }); describe('onDidChangeActiveTextEditor()', () => { const editor: any = {}; let sut; beforeEach(() => { sut = newJestExt(); sut.triggerUpdateActiveEditor = jest.fn(); (sut.triggerUpdateActiveEditor as jest.Mock<{}>).mockReset(); }); it('should update the annotations when the editor has a document', () => { editor.document = {}; sut.onDidChangeActiveTextEditor(editor); expect(sut.triggerUpdateActiveEditor).toBeCalledWith(editor); }); }); describe('onDidChangeTextDocument()', () => { let sut; let event; beforeEach(() => { sut = newJestExt(); event = { document: { isDirty: false, uri: { scheme: 'file' }, }, contentChanges: [], }; }); function expectItTakesNoAction(event) { sut.removeCachedTestResults = jest.fn(); sut.triggerUpdateActiveEditor = jest.fn(); sut.onDidChangeTextDocument(event); expect(sut.removeCachedTestResults).not.toBeCalledWith(event.document); expect(sut.triggerUpdateActiveEditor).not.toBeCalled(); } it('should do nothing if the document has unsaved changes', () => { const event: any = { document: { isDirty: true, uri: { scheme: 'file' }, }, contentChanges: [], }; expectItTakesNoAction(event); }); it('should do nothing if the document URI scheme is "git"', () => { const event: any = { document: { isDirty: false, uri: { scheme: 'git', }, }, contentChanges: [], }; expectItTakesNoAction(event); }); it('should do nothing if the document is clean but there are changes', () => { const event = { document: { isDirty: false, uri: { scheme: 'file' }, }, contentChanges: { length: 1 }, }; expectItTakesNoAction(event); }); it('should trigger updateActiveEditor', () => { const editor: any = { document: event.document }; sut.triggerUpdateActiveEditor = jest.fn(); vscode.window.visibleTextEditors = [editor]; sut.onDidChangeTextDocument(event); expect(sut.triggerUpdateActiveEditor).toBeCalledWith(editor); }); it('should update statusBar for stats', () => { sut.onDidChangeTextDocument(event); expect(sut.testResultProvider.getTestSuiteStats).toBeCalled(); expect(sbUpdateMock).toBeCalled(); }); }); describe('onWillSaveTextDocument', () => { it.each([[true], [false]])( 'ony invalidate test status if document is dirty: isDirty=%d', (isDirty) => { vscode.window.visibleTextEditors = []; const sut: any = newJestExt(); sut.testResultProvider.invalidateTestResults = jest.fn(); const event = { document: { isDirty, uri: { scheme: 'file' }, }, }; sut.onWillSaveTextDocument(event); if (isDirty) { expect(sut.testResultProvider.invalidateTestResults).toBeCalled(); } else { expect(sut.testResultProvider.invalidateTestResults).not.toBeCalled(); } } ); }); describe('onDidSaveTextDocument', () => { describe('should handle onSave run', () => { it.each` runConfig | languageId | isTestFile | shouldSchedule | isDirty ${'off'} | ${'javascript'} | ${'yes'} | ${false} | ${true} ${{ watch: true }} | ${'javascript'} | ${'yes'} | ${false} | ${false} ${{ watch: false }} | ${'javascript'} | ${'yes'} | ${false} | ${true} ${{ watch: false, onSave: 'test-src-file' }} | ${'javascript'} | ${'no'} | ${true} | ${false} ${{ watch: false, onSave: 'test-src-file' }} | ${'javascript'} | ${'unknown'} | ${true} | ${false} ${{ watch: false, onSave: 'test-src-file' }} | ${'javascript'} | ${'yes'} | ${true} | ${false} ${{ watch: false, onSave: 'test-src-file' }} | ${'json'} | ${'no'} | ${false} | ${false} ${{ watch: false, onSave: 'test-file' }} | ${'javascript'} | ${'no'} | ${false} | ${true} ${{ watch: false, onSave: 'test-file' }} | ${'javascript'} | ${'unknown'} | ${true} | ${false} ${{ watch: false, onSave: 'test-file' }} | ${'javascript'} | ${'yes'} | ${true} | ${false} ${{ watch: false, onSave: 'test-file' }} | ${'javascript'} | ${'unknown'} | ${true} | ${false} ${{ watch: false, onSave: 'test-file' }} | ${'json'} | ${'unknown'} | ${false} | ${false} `( 'with autoRun: $runConfig $languageId $isTestFile => $shouldSchedule, $isDirty', ({ runConfig: autoRun, languageId, isTestFile, shouldSchedule, isDirty }) => { const sut: any = newJestExt({ settings: { autoRun } }); const fileName = '/a/file;'; const document: any = { uri: { scheme: 'file' }, languageId: languageId, fileName, }; vscode.window.visibleTextEditors = []; (sut.testResultProvider.isTestFile as jest.Mocked<any>).mockReturnValueOnce(isTestFile); mockProcessSession.scheduleProcess.mockClear(); sut.onDidSaveTextDocument(document); if (shouldSchedule) { expect(mockProcessSession.scheduleProcess).toBeCalledWith( expect.objectContaining({ type: 'by-file', testFileName: fileName, notTestFile: isTestFile !== 'yes', }) ); } else { expect(mockProcessSession.scheduleProcess).not.toBeCalled(); } expect(sbUpdateMock).toBeCalledWith(expect.objectContaining({ stats: { isDirty } })); } ); }); }); describe('toggleCoverageOverlay()', () => { it('should toggle the coverage overlay visibility', () => { const sut = newJestExt(); sut.triggerUpdateSettings = jest.fn(); sut.toggleCoverageOverlay(); expect(sut.coverageOverlay.toggleVisibility).toBeCalled(); expect(sut.triggerUpdateSettings).toBeCalled(); }); it('overrides showCoverageOnLoad settings', async () => { const settings = { showCoverageOnLoad: true } as any; const sut = newJestExt({ settings }); const { runnerWorkspace } = (createProcessSession as jest.Mocked<any>).mock.calls[0][0]; expect(runnerWorkspace.collectCoverage).toBe(true); sut.coverageOverlay.enabled = false; await sut.toggleCoverageOverlay(); const { runnerWorkspace: runnerWorkspace2 } = (createProcessSession as jest.Mocked<any>).mock .calls[1][0]; expect(runnerWorkspace2.collectCoverage).toBe(false); }); }); describe('triggerUpdateActiveEditor()', () => { it('should update the coverage overlay in visible editors', () => { const editor: any = {}; const sut = newJestExt(); sut.triggerUpdateActiveEditor(editor); expect(sut.coverageOverlay.updateVisibleEditors).toBeCalled(); }); it('should update both decorators and diagnostics for valid editor', () => { const sut = newJestExt(); sut.updateDecorators = jest.fn(); const editor = mockEditor('file://a/b/c.ts'); (sut.testResultProvider.getSortedResults as unknown as jest.Mock<{}>).mockReturnValueOnce({ success: [], fail: [], skip: [], unknown: [], }); sut.triggerUpdateActiveEditor(editor); expect(sut.updateDecorators).toBeCalled(); expect(updateCurrentDiagnostics).toBeCalled(); }); it.each` autoRun | isInteractive ${'off'} | ${true} ${{ watch: true }} | ${false} ${{ watch: false }} | ${true} ${{ onStartup: ['all-tests'] }} | ${true} ${{ onSave: 'test-file' }} | ${true} ${{ onSave: 'test-src-file' }} | ${true} ${{ onSave: 'test-src-file', onStartup: ['all-tests'] }} | ${true} `('should update vscode editor context', ({ autoRun, isInteractive }) => { const sut = newJestExt({ settings: { autoRun } }); const editor = mockEditor('a'); sut.triggerUpdateActiveEditor(editor); expect(vscode.commands.executeCommand).toBeCalledWith( 'setContext', 'jest:run.interactive', isInteractive ); }); it('when failed to get test result, it should report error and clear the decorators and diagnostics', () => { const sut = newJestExt(); sut.debugCodeLensProvider.didChange = jest.fn(); const editor = mockEditor('a'); (sut.testResultProvider.getSortedResults as jest.Mocked<any>).mockImplementation(() => { throw new Error('force error'); }); const updateDecoratorsSpy = jest.spyOn(sut, 'updateDecorators'); sut.triggerUpdateActiveEditor(editor); expect(channelStub.appendLine).toBeCalledWith(expect.stringContaining('force error')); expect(updateDecoratorsSpy).toBeCalledWith(EmptySortedResult, editor); expect(updateCurrentDiagnostics).toBeCalledWith(EmptySortedResult.fail, undefined, editor); }); describe('can skip test-file related updates', () => { let sut; let updateDecoratorsSpy; beforeEach(() => { sut = newJestExt(); (sut.testResultProvider.getSortedResults as unknown as jest.Mock<{}>).mockReturnValueOnce({ success: [], fail: [], skip: [], unknown: [], }); updateDecoratorsSpy = jest.spyOn(sut, 'updateDecorators'); sut.debugCodeLensProvider.didChange = jest.fn(); }); it.each` languageId | shouldSkip ${'json'} | ${true} ${''} | ${true} ${'markdown'} | ${true} ${'javascript'} | ${false} ${'javascriptreact'} | ${false} ${'typescript'} | ${false} ${'typescriptreact'} | ${false} ${'vue'} | ${false} `('if languageId=languageId => skip? $shouldSkip', ({ languageId, shouldSkip }) => { const editor = mockEditor('file', languageId); sut.triggerUpdateActiveEditor(editor); if (shouldSkip) { expect(updateCurrentDiagnostics).not.toBeCalled(); expect(updateDecoratorsSpy).not.toBeCalled(); } else { expect(updateCurrentDiagnostics).toBeCalled(); expect(updateDecoratorsSpy).toBeCalled(); } }); it('if editor has no document', () => { const editor = {}; sut.triggerUpdateActiveEditor(editor); expect(updateCurrentDiagnostics).not.toBeCalled(); expect(updateDecoratorsSpy).not.toBeCalled(); }); it.each` isTestFile | shouldUpdate ${'yes'} | ${true} ${'no'} | ${false} ${'unknown'} | ${true} `( 'isTestFile: $isTestFile => shouldUpdate? $shouldUpdate', async ({ isTestFile, shouldUpdate }) => { // update testFiles await sut.startSession(); const { type, onResult } = mockProcessSession.scheduleProcess.mock.calls[0][0]; expect(type).toEqual('list-test-files'); expect(onResult).not.toBeUndefined(); (sut.testResultProvider.isTestFile as jest.Mocked<any>).mockReturnValueOnce(isTestFile); const editor = mockEditor('x'); sut.triggerUpdateActiveEditor(editor); if (shouldUpdate) { expect(updateCurrentDiagnostics).toBeCalled(); expect(updateDecoratorsSpy).toBeCalled(); } else { expect(updateCurrentDiagnostics).not.toBeCalled(); expect(updateDecoratorsSpy).not.toBeCalled(); } } ); }); }); describe('updateDecorators', () => { let sut: JestExt; const mockEditor: any = { document: { uri: { fsPath: `file://a/b/c.js` } } }; const emptyTestResults = { success: [], fail: [], skip: [], unknown: [] }; const settings: any = { debugCodeLens: {}, enableInlineErrorMessages: false, }; const tr1 = { start: { line: 1, column: 0 }, }; const tr2 = { start: { line: 100, column: 0 }, }; beforeEach(() => { StateDecorationsMock.mockImplementation(() => ({ passing: { key: 'pass' } as vscode.TextEditorDecorationType, failing: { key: 'fail' } as vscode.TextEditorDecorationType, skip: { key: 'skip' } as vscode.TextEditorDecorationType, unknown: { key: 'unknown' } as vscode.TextEditorDecorationType, })); mockEditor.setDecorations = jest.fn(); }); describe('when "showClassicStatus" is on', () => { beforeEach(() => { sut = newJestExt({ settings: { ...settings, testExplorer: { enabled: true, showClassicStatus: true } }, }); sut.debugCodeLensProvider.didChange = jest.fn(); }); it('will reset decorator if testResults is empty', () => { sut.updateDecorators(emptyTestResults, mockEditor); expect(mockEditor.setDecorations).toHaveBeenCalledTimes(4); for (const args of mockEditor.setDecorations.mock.calls) { expect(args[1].length).toBe(0); } }); it('will generate dot dectorations for test results', () => { const testResults2: any = { success: [tr1], fail: [tr2], skip: [], unknown: [] }; sut.updateDecorators(testResults2, mockEditor); expect(mockEditor.setDecorations).toHaveBeenCalledTimes(4); for (const args of mockEditor.setDecorations.mock.calls) { let expectedLength = -1; switch (args[0].key) { case 'fail': case 'pass': expectedLength = 1; break; case 'skip': case 'unknown': expectedLength = 0; break; } expect(args[1].length).toBe(expectedLength); } }); }); describe('when showDecorations for "status.classic" is off', () => { it.each([[{ enabled: true }], [{ enabled: true, showClassicStatus: false }]])( 'no dot decorators will be generatred for testExplore config: %s', (testExplorerConfig) => { sut = newJestExt({ settings: { ...settings, testExplorer: testExplorerConfig }, }); sut.debugCodeLensProvider.didChange = jest.fn(); const testResults2: any = { success: [tr1], fail: [tr2], skip: [], unknown: [] }; sut.updateDecorators(testResults2, mockEditor); expect(mockEditor.setDecorations).toHaveBeenCalledTimes(0); } ); }); }); describe('session', () => { const createJestExt = () => { const jestExt: any = newJestExt(); return jestExt; }; beforeEach(() => {}); describe('startSession', () => { it('starts a new session and file event', async () => { const sut = createJestExt(); await sut.startSession(); expect(mockProcessSession.start).toHaveBeenCalled(); expect(JestTestProvider).toHaveBeenCalled(); expect(sut.events.onTestSessionStarted.fire).toHaveBeenCalledWith( expect.objectContaining({ session: mockProcessSession }) ); }); it('if failed to start session, show error', async () => { mockProcessSession.start.mockReturnValueOnce(Promise.reject('forced error')); const sut = createJestExt(); await sut.startSession(); expect(messaging.systemErrorMessage).toBeCalled(); }); it('dispose existing jestProvider before creating new one', async () => { expect.hasAssertions(); const sut = createJestExt(); await sut.startSession(); expect(JestTestProvider).toHaveBeenCalledTimes(1); await sut.startSession(); expect(mockTestProvider.dispose).toBeCalledTimes(1); expect(JestTestProvider).toHaveBeenCalledTimes(2); }); describe('will update test file list', () => { it.each` fileNames | error | expectedTestFiles ${undefined} | ${'some error'} | ${undefined} ${undefined} | ${new Error('some error')} | ${undefined} ${[]} | ${undefined} | ${[]} ${['a', 'b']} | ${undefined} | ${['a', 'b']} `( 'can schedule the request and process the result ($fileNames, $error)', async ({ fileNames, error, expectedTestFiles }) => { expect.hasAssertions(); const sut = createJestExt(); const stats = { success: 1000, isDirty: false }; sut.testResultProvider.getTestSuiteStats = jest.fn().mockReturnValueOnce(stats); await sut.startSession(); expect(mockProcessSession.scheduleProcess).toBeCalledTimes(1); const { type, onResult } = mockProcessSession.scheduleProcess.mock.calls[0][0]; expect(type).toEqual('list-test-files'); expect(onResult).not.toBeUndefined(); onResult(fileNames, error); expect(sut.testResultProvider.updateTestFileList).toBeCalledWith(expectedTestFiles); // stats will be updated in status baar accordingly expect(sut.testResultProvider.getTestSuiteStats).toBeCalled(); expect(sbUpdateMock).toBeCalledWith({ stats }); } ); }); }); describe('stopSession', () => { it('will fire event', async () => { const sut = createJestExt(); await sut.stopSession(); expect(mockProcessSession.stop).toHaveBeenCalled(); expect(sut.events.onTestSessionStopped.fire).toHaveBeenCalled(); }); it('dispose existing testProvider', async () => { const sut = createJestExt(); await sut.startSession(); expect(JestTestProvider).toHaveBeenCalledTimes(1); await sut.stopSession(); expect(mockTestProvider.dispose).toBeCalledTimes(1); expect(JestTestProvider).toHaveBeenCalledTimes(1); }); it('updatae statusBar status', async () => { const sut = createJestExt(); await sut.stopSession(); expect(sbUpdateMock).toHaveBeenCalledWith({ state: 'stopped' }); }); it('if failed to stop session, show error', async () => { mockProcessSession.stop.mockReturnValueOnce(Promise.reject('forced error')); const sut = createJestExt(); await sut.stopSession(); expect(messaging.systemErrorMessage).toBeCalled(); }); }); }); describe('_updateCoverageMap', () => { it('the overlay and codeLens will be updated when map updated async', async () => { expect.hasAssertions(); (CoverageMapProvider as jest.Mock<any>).mockImplementation(() => ({ update: () => Promise.resolve(), })); const coverageCodeLensProvider: any = { coverageChanged: jest.fn() }; const sut = newJestExt({ coverageCodeLensProvider }); await sut._updateCoverageMap({}); expect(coverageCodeLensProvider.coverageChanged).toBeCalled(); expect(sut.coverageOverlay.updateVisibleEditors).toBeCalled(); }); }); describe('runAllTests', () => { describe.each` scheduleProcess ${{}} ${undefined} `('scheduleProcess returns $scheduleProcess', ({ scheduleProcess }) => { beforeEach(() => { mockProcessSession.scheduleProcess.mockReturnValueOnce(scheduleProcess); }); it('can run all test for the workspace', () => { const sut = newJestExt(); const dirtyFiles: any = sut['dirtyFiles']; dirtyFiles.clear = jest.fn(); sut.runAllTests(); expect(mockProcessSession.scheduleProcess).toBeCalledWith({ type: 'all-tests' }); if (scheduleProcess) { expect(dirtyFiles.clear).toBeCalled(); } else { expect(dirtyFiles.clear).not.toBeCalled(); } }); it('can run all test for the given editor', () => { const sut = newJestExt(); const dirtyFiles: any = sut['dirtyFiles']; dirtyFiles.delete = jest.fn(); const editor: any = { document: { fileName: 'whatever' } }; sut.runAllTests(editor); expect(mockProcessSession.scheduleProcess).toBeCalledWith({ type: 'by-file', testFileName: editor.document.fileName, notTestFile: true, }); if (scheduleProcess) { expect(dirtyFiles.delete).toBeCalledWith(editor.document.fileName); } else { expect(dirtyFiles.delete).not.toBeCalled(); } }); }); it.each` isTestFile | notTestFile ${'yes'} | ${false} ${'no'} | ${true} ${'unknown'} | ${true} `( 'treat unknown as notTestFile: isTestFile=$isTestFile => notTestFile=$notTestFile', ({ isTestFile, notTestFile }) => { const sut = newJestExt(); const editor: any = { document: { fileName: 'whatever' } }; (sut.testResultProvider.isTestFile as jest.Mocked<any>).mockReturnValueOnce(isTestFile); sut.runAllTests(editor); expect(mockProcessSession.scheduleProcess).toBeCalledWith({ type: 'by-file', testFileName: editor.document.fileName, notTestFile: notTestFile, }); } ); }); describe('refresh test file list upon file system change', () => { const getProcessType = () => { const { type } = mockProcessSession.scheduleProcess.mock.calls[0][0]; return type; }; let jestExt: any; beforeEach(() => { jestExt = newJestExt(); }); it('when new file is created', () => { jestExt.onDidCreateFiles({}); expect(mockProcessSession.scheduleProcess).toHaveBeenCalledTimes(1); expect(getProcessType()).toEqual('list-test-files'); }); it('when file is renamed', () => { jestExt.onDidRenameFiles({}); expect(mockProcessSession.scheduleProcess).toHaveBeenCalledTimes(1); expect(getProcessType()).toEqual('list-test-files'); }); it('when file is deleted', () => { jestExt.onDidDeleteFiles({}); expect(mockProcessSession.scheduleProcess).toHaveBeenCalledTimes(1); expect(getProcessType()).toEqual('list-test-files'); }); }); describe('triggerUpdateSettings', () => { it('should create a new ProcessSession', async () => { const jestExt = newJestExt(); expect(createProcessSession).toBeCalledTimes(1); const settings: any = { debugMode: true, }; await jestExt.triggerUpdateSettings(settings); expect(createProcessSession).toBeCalledTimes(2); expect(createProcessSession).toHaveBeenLastCalledWith( expect.objectContaining({ settings: { debugMode: true } }) ); }); }); describe('can handle test run results', () => { let sut; let updateWithData; const mockCoverageMapProvider = { update: jest.fn() }; beforeEach(() => { (CoverageMapProvider as jest.Mock<any>).mockReturnValueOnce(mockCoverageMapProvider); mockCoverageMapProvider.update.mockImplementation(() => Promise.resolve()); sut = newJestExt(); const { updateWithData: f } = (createProcessSession as jest.Mocked<any>).mock.calls[0][0]; updateWithData = f; (resultsWithLowerCaseWindowsDriveLetters as jest.Mocked<any>).mockReturnValue({ coverageMap: {}, }); }); it('will invoke internal components to process test results', () => { updateWithData({}, 'test-all-12'); expect(mockCoverageMapProvider.update).toBeCalled(); expect(sut.testResultProvider.updateTestResults).toBeCalledWith( expect.anything(), 'test-all-12' ); expect(updateDiagnostics).toBeCalled(); }); it('will calculate stats and update statusBar', () => { updateWithData({}); expect(sut.testResultProvider.getTestSuiteStats).toBeCalled(); expect(sbUpdateMock).toBeCalled(); }); it('will update visible editors for the current workspace', () => { (vscode.window.visibleTextEditors as any) = [ mockEditor('a'), mockEditor('b'), mockEditor('c'), ]; (vscode.workspace.getWorkspaceFolder as jest.Mocked<any>).mockImplementation((uri) => uri !== 'b' ? workspaceFolder : undefined ); const triggerUpdateActiveEditorSpy = jest.spyOn(sut as any, 'triggerUpdateActiveEditor'); updateWithData(); expect(triggerUpdateActiveEditorSpy).toBeCalledTimes(2); }); }); describe('deactivate', () => { it('will stop session and output channel', () => { const sut = newJestExt(); sut.deactivate(); expect(mockProcessSession.stop).toBeCalledTimes(1); expect(channelStub.dispose).toBeCalledTimes(1); }); it('will dispose test provider if initialized', () => { const sut = newJestExt(); sut.deactivate(); expect(mockTestProvider.dispose).not.toBeCalledTimes(1); sut.startSession(); sut.deactivate(); expect(mockTestProvider.dispose).toBeCalledTimes(1); }); it('will dispose all events', () => { const sut = newJestExt(); sut.deactivate(); expect(sut.events.onRunEvent.dispose).toHaveBeenCalled(); expect(sut.events.onTestSessionStarted.dispose).toHaveBeenCalled(); expect(sut.events.onTestSessionStopped.dispose).toHaveBeenCalled(); }); }); describe('activate', () => { it('will invoke onDidChangeActiveTextEditor for activeTextEditor', () => { const sut = newJestExt(); const spy = jest.spyOn(sut, 'onDidChangeActiveTextEditor').mockImplementation(() => {}); vscode.window.activeTextEditor = undefined; sut.activate(); expect(spy).not.toHaveBeenCalled(); (vscode.window.activeTextEditor as any) = { document: { uri: 'whatever' }, }; (vscode.workspace.getWorkspaceFolder as jest.Mocked<any>).mockReturnValue(workspaceFolder); sut.activate(); expect(spy).toHaveBeenCalled(); }); }); describe('runEvents', () => { let sut, onRunEvent, process; beforeEach(() => { sut = newJestExt(); onRunEvent = (sut.events.onRunEvent.event as jest.Mocked<any>).mock.calls[0][0]; process = { id: 'a process id' }; }); describe('can process run events', () => { it('register onRunEvent listener', () => { expect(sut.events.onRunEvent.event).toBeCalledTimes(1); }); it('scheduled event: output to channel', () => { onRunEvent({ type: 'scheduled', process }); expect(sut.channel.appendLine).toBeCalledWith(expect.stringContaining(process.id)); }); it('data event: relay clean-text to channel', () => { onRunEvent({ type: 'data', text: 'plain text', raw: 'raw text', newLine: true, isError: true, process, }); expect(sut.channel.appendLine).toBeCalledWith(expect.stringContaining('plain text')); expect(sut.channel.show).toBeCalled(); sut.channel.show.mockClear(); onRunEvent({ type: 'data', text: 'plain text 2', raw: 'raw text', process }); expect(sut.channel.append).toBeCalledWith(expect.stringContaining('plain text 2')); expect(sut.channel.show).not.toBeCalled(); }); it('start event: notify status bar and clear channel', () => { onRunEvent({ type: 'start', process }); expect(sbUpdateMock).toBeCalledWith({ state: 'running' }); expect(sut.channel.clear).toBeCalled(); }); it('end event: notify status bar', () => { onRunEvent({ type: 'end', process }); expect(sbUpdateMock).toBeCalledWith({ state: 'done' }); }); describe('exit event: notify status bar', () => { it('if no error: status bar done', () => { onRunEvent({ type: 'exit', process }); expect(sbUpdateMock).toBeCalledWith({ state: 'done' }); }); it('if error: status bar stopped and show error', () => { onRunEvent({ type: 'exit', error: 'something is wrong', process }); expect(sbUpdateMock).toBeCalledWith({ state: 'stopped' }); expect(messaging.systemErrorMessage).toHaveBeenCalled(); }); }); }); it('events are disposed when extensioin deactivated', () => { sut.deactivate(); expect(sut.events.onRunEvent.dispose).toBeCalled(); }); }); });
the_stack
import {makeDataBoundsBoundingBoxAnnotationSet} from 'neuroglancer/annotation'; import {ChunkManager, WithParameters} from 'neuroglancer/chunk_manager/frontend'; import {CoordinateSpace, makeCoordinateSpace, makeIdentityTransform, makeIdentityTransformedBoundingBox} from 'neuroglancer/coordinate_transform'; import {WithCredentialsProvider} from 'neuroglancer/credentials_provider/chunk_source_frontend'; import {CompleteUrlOptions, DataSource, DataSourceProvider, GetDataSourceOptions} from 'neuroglancer/datasource'; import {VolumeChunkSourceParameters, ZarrCompressor, ZarrEncoding, ZarrSeparator} from 'neuroglancer/datasource/zarr/base'; import {SliceViewSingleResolutionSource} from 'neuroglancer/sliceview/frontend'; import {DataType, makeDefaultVolumeChunkSpecifications, VolumeSourceOptions, VolumeType} from 'neuroglancer/sliceview/volume/base'; import {MultiscaleVolumeChunkSource as GenericMultiscaleVolumeChunkSource, VolumeChunkSource} from 'neuroglancer/sliceview/volume/frontend'; import {transposeNestedArrays} from 'neuroglancer/util/array'; import {applyCompletionOffset, completeQueryStringParametersFromTable} from 'neuroglancer/util/completion'; import {Borrowed} from 'neuroglancer/util/disposable'; import {completeHttpPath} from 'neuroglancer/util/http_path_completion'; import {isNotFoundError, responseJson} from 'neuroglancer/util/http_request'; import {parseArray, parseFixedLengthArray, parseQueryStringParameters, verifyObject, verifyObjectProperty, verifyOptionalObjectProperty, verifyString} from 'neuroglancer/util/json'; import {createIdentity} from 'neuroglancer/util/matrix'; import {parseNumpyDtype} from 'neuroglancer/util/numpy_dtype'; import {getObjectId} from 'neuroglancer/util/object_id'; import {cancellableFetchSpecialOk, parseSpecialUrl, SpecialProtocolCredentials, SpecialProtocolCredentialsProvider} from 'neuroglancer/util/special_protocol_request'; class ZarrVolumeChunkSource extends (WithParameters(WithCredentialsProvider<SpecialProtocolCredentials>()(VolumeChunkSource), VolumeChunkSourceParameters)) {} interface ZarrMetadata { encoding: ZarrEncoding; order: 'C'|'F'; dataType: DataType; rank: number; shape: number[]; chunks: number[]; dimensionSeparator: ZarrSeparator|undefined; } function parseDimensionSeparator(obj: unknown): ZarrSeparator|undefined { return verifyOptionalObjectProperty(obj, 'dimension_separator', value => { if (value !== '.' && value !== '/') { throw new Error(`Expected "." or "/", but received: ${JSON.stringify(value)}`); } return value; }); } function parseZarrMetadata(obj: unknown): ZarrMetadata { try { verifyObject(obj); verifyObjectProperty(obj, 'zarr_format', zarrFormat => { if (zarrFormat !== 2) { throw new Error(`Expected 2 but received: ${JSON.stringify(zarrFormat)}`); } }); const shape = verifyObjectProperty( obj, 'shape', shape => parseArray(shape, x => { if (typeof x !== 'number' || !Number.isInteger(x) || x < 0) { throw new Error(`Expected non-negative integer, but received: ${JSON.stringify(x)}`); } return x; })); const chunks = verifyObjectProperty( obj, 'chunks', chunks => parseFixedLengthArray(new Array<number>(shape.length), chunks, x => { if (typeof x !== 'number' || !Number.isInteger(x) || x <= 0) { throw new Error(`Expected positive integer, but received: ${JSON.stringify(x)}`); } return x; })); const order = verifyObjectProperty(obj, 'order', order => { if (order !== 'C' && order !== 'F') { throw new Error(`Expected "C" or "F", but received: ${JSON.stringify(order)}`); } return order; }); const dimensionSeparator = parseDimensionSeparator(obj); const numpyDtype = verifyObjectProperty(obj, 'dtype', dtype => parseNumpyDtype(verifyString(dtype))); const compressor = verifyObjectProperty(obj, 'compressor', compressor => { if (compressor === null) return ZarrCompressor.RAW; verifyObject(compressor); const id = verifyObjectProperty(compressor, 'id', verifyString); switch (id) { case 'blosc': return ZarrCompressor.BLOSC; case 'gzip': return ZarrCompressor.GZIP; case 'zlib': return ZarrCompressor.GZIP; default: throw new Error(`Unsupported compressor: ${JSON.stringify(id)}`); } }); return { rank: shape.length, shape, chunks, order, dataType: numpyDtype.dataType, encoding: {compressor, endianness: numpyDtype.endianness}, dimensionSeparator, }; } catch (e) { throw new Error(`Error parsing zarr metadata: ${e.message}`); } } export class MultiscaleVolumeChunkSource extends GenericMultiscaleVolumeChunkSource { dataType: DataType; volumeType: VolumeType; modelSpace: CoordinateSpace; get rank() { return this.metadata.rank; } constructor( chunkManager: Borrowed<ChunkManager>, public credentialsProvider: SpecialProtocolCredentialsProvider, public url: string, public separator: ZarrSeparator, public metadata: ZarrMetadata, public attrs: unknown) { super(chunkManager); this.dataType = metadata.dataType; this.volumeType = VolumeType.IMAGE; let names = verifyOptionalObjectProperty( attrs, '_ARRAY_DIMENSIONS', names => parseFixedLengthArray(new Array<string>(metadata.rank), names, verifyString)); if (names === undefined) { names = Array.from(metadata.shape, (_, i) => `d${i}`); } this.modelSpace = makeCoordinateSpace({ names, scales: Float64Array.from(metadata.shape, () => 1), units: Array.from(metadata.shape, () => ''), boundingBoxes: [makeIdentityTransformedBoundingBox({ lowerBounds: new Float64Array(metadata.rank), upperBounds: Float64Array.from(metadata.shape), })], }); } getSources(volumeSourceOptions: VolumeSourceOptions) { const {metadata} = this; const {rank, chunks, shape} = metadata; let permutedChunkShape: Uint32Array; let permutedDataShape: Float32Array; let transform: Float32Array; if (metadata.order === 'F') { permutedChunkShape = Uint32Array.from(chunks); permutedDataShape = Float32Array.from(shape); transform = createIdentity(Float32Array, rank + 1); } else { permutedChunkShape = new Uint32Array(rank); permutedDataShape = new Float32Array(rank); transform = new Float32Array((rank + 1) ** 2); transform[(rank + 1) ** 2 - 1] = 1; for (let i = 0; i < rank; ++i) { permutedChunkShape[i] = chunks[rank - 1 - i]; permutedDataShape[i] = shape[rank - 1 - i]; transform[i + (rank - 1 - i) * (rank + 1)] = 1; } } return transposeNestedArrays( [makeDefaultVolumeChunkSpecifications({ rank, chunkToMultiscaleTransform: transform, dataType: metadata.dataType, upperVoxelBound: permutedDataShape, volumeType: this.volumeType, chunkDataSizes: [permutedChunkShape], volumeSourceOptions, }).map((spec): SliceViewSingleResolutionSource<VolumeChunkSource> => ({ chunkSource: this.chunkManager.getChunkSource(ZarrVolumeChunkSource, { credentialsProvider: this.credentialsProvider, spec, parameters: { url: this.url, encoding: metadata.encoding, separator: this.separator, } }), chunkToMultiscaleTransform: transform, }))]); } } function getAttributes( chunkManager: ChunkManager, credentialsProvider: SpecialProtocolCredentialsProvider, url: string): Promise<any> { return chunkManager.memoize.getUncounted( {type: 'zarr:.zattrs json', url, credentialsProvider: getObjectId(credentialsProvider)}, async () => { try { const json = await cancellableFetchSpecialOk( credentialsProvider, url + '/.zattrs', {}, responseJson); verifyObject(json); return json; } catch (e) { if (isNotFoundError(e)) return {}; throw e; } }); } function getMetadata( chunkManager: ChunkManager, credentialsProvider: SpecialProtocolCredentialsProvider, url: string): Promise<any> { return chunkManager.memoize.getUncounted( {type: 'zarr:.zarray json', url, credentialsProvider: getObjectId(credentialsProvider)}, async () => { const json = await cancellableFetchSpecialOk( credentialsProvider, url + '/.zarray', {}, responseJson); return parseZarrMetadata(json); }); } const supportedQueryParameters = [ { key: {value: 'dimension_separator', description: 'Dimension separator in chunk keys'}, values: [ {value: '.', description: '(default)'}, {value: '/', description: ''}, ] }, ]; export class ZarrDataSource extends DataSourceProvider { get description() { return 'Zarr data source'; } get(options: GetDataSourceOptions): Promise<DataSource> { // Pattern is infallible. let [, providerUrl, query] = options.providerUrl.match(/([^?]*)(?:\?(.*))?$/)!; const parameters = parseQueryStringParameters(query || ''); verifyObject(parameters); const dimensionSeparator = parseDimensionSeparator(parameters); if (providerUrl.endsWith('/')) { providerUrl = providerUrl.substring(0, providerUrl.length - 1); } return options.chunkManager.memoize.getUncounted( {'type': 'zarr:MultiscaleVolumeChunkSource', providerUrl, dimensionSeparator}, async () => { const {url, credentialsProvider} = parseSpecialUrl(providerUrl, options.credentialsManager); const [metadata, attrs] = await Promise.all([ getMetadata(options.chunkManager, credentialsProvider, url), getAttributes(options.chunkManager, credentialsProvider, url) ]); if (metadata.dimensionSeparator !== undefined && dimensionSeparator !== undefined && metadata.dimensionSeparator !== dimensionSeparator) { throw new Error( `Explicitly specified dimension separator ` + `${JSON.stringify(dimensionSeparator)} does not match value ` + `in .zarray ${JSON.stringify(metadata.dimensionSeparator)}`); } const volume = new MultiscaleVolumeChunkSource( options.chunkManager, credentialsProvider, url, dimensionSeparator || metadata.dimensionSeparator || '.', metadata, attrs); return { modelTransform: makeIdentityTransform(volume.modelSpace), subsources: [ { id: 'default', default: true, url: undefined, subsource: {volume}, }, { id: 'bounds', default: true, url: undefined, subsource: { staticAnnotations: makeDataBoundsBoundingBoxAnnotationSet(volume.modelSpace.bounds) }, }, ], }; }) } async completeUrl(options: CompleteUrlOptions) { // Pattern is infallible. let [, , query] = options.providerUrl.match(/([^?]*)(?:\?(.*))?$/)!; if (query !== undefined) { return applyCompletionOffset( options.providerUrl.length - query.length, await completeQueryStringParametersFromTable(query, supportedQueryParameters)); } return await completeHttpPath( options.credentialsManager, options.providerUrl, options.cancellationToken); } }
the_stack
import * as React from 'react'; import { mount as _mount } from 'enzyme'; import { Async, FieldFeedback, FieldFeedbacksProps, FormWithConstraints, FormWithConstraintsProps } from '.'; import * as assert from './assert'; import { FieldFeedbacksEnzymeFix as FieldFeedbacks } from './FieldFeedbacksEnzymeFix'; import { dBlock, error, formatHTML, info, key, keys, warning, whenValid } from './formatHTML'; import { validValidityState } from './InputElementMock'; import { SignUp } from './SignUp'; import { wait } from './wait'; function mount(node: React.ReactElement<FormWithConstraintsProps>) { return _mount<FormWithConstraintsProps, Record<string, unknown>>(node); } test('constructor()', () => { const form = new FormWithConstraints({}); expect(form.fieldsStore.fields).toEqual([]); }); test('computeFieldFeedbacksKey()', () => { const form = new FormWithConstraints({}); expect(form.computeFieldFeedbacksKey()).toEqual('0'); expect(form.computeFieldFeedbacksKey()).toEqual('1'); expect(form.computeFieldFeedbacksKey()).toEqual('2'); }); interface FormProps { inputStop: FieldFeedbacksProps['stop']; } describe('FormWithBeforeAsync', () => { class FormWithBeforeAsync extends React.Component<FormProps> { formWithConstraints: FormWithConstraints | null = null; input: HTMLInputElement | null = null; render() { const { inputStop } = this.props; return ( <FormWithConstraints ref={formWithConstraints => (this.formWithConstraints = formWithConstraints)} > <input name="input" ref={input => (this.input = input)} /> <FieldFeedbacks for="input" stop={inputStop}> <FieldFeedback when={() => true}>Error before Async</FieldFeedback> <FieldFeedback when={() => true} warning> Warning before Async </FieldFeedback> <FieldFeedback when={() => true} info> Info before Async </FieldFeedback> <Async promise={() => wait(10)} then={() => <FieldFeedback>Async error</FieldFeedback>} /> </FieldFeedbacks> </FormWithConstraints> ); } } test('stop="first"', async () => { const wrapper = mount(<FormWithBeforeAsync inputStop="first" />); const form = wrapper.instance() as FormWithBeforeAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error before Async</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-error"', async () => { const wrapper = mount(<FormWithBeforeAsync inputStop="first-error" />); const form = wrapper.instance() as FormWithBeforeAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error before Async</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-warning"', async () => { const wrapper = mount(<FormWithBeforeAsync inputStop="first-warning" />); const form = wrapper.instance() as FormWithBeforeAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error before Async</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning before Async</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-info"', async () => { const wrapper = mount(<FormWithBeforeAsync inputStop="first-info" />); const form = wrapper.instance() as FormWithBeforeAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error before Async</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning before Async</span> <span ${key}="0.2" ${info} ${dBlock}>Info before Async</span> </span> </form>`); wrapper.unmount(); }); test('stop="no"', async () => { const wrapper = mount(<FormWithBeforeAsync inputStop="no" />); const form = wrapper.instance() as FormWithBeforeAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error before Async</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning before Async</span> <span ${key}="0.2" ${info} ${dBlock}>Info before Async</span> <span ${key}="0.3" ${error} ${dBlock}>Async error</span> </span> </form>`); wrapper.unmount(); }); }); describe('FormWithAfterAsync', () => { class FormWithAfterAsync extends React.Component<FormProps> { formWithConstraints: FormWithConstraints | null = null; input: HTMLInputElement | null = null; render() { const { inputStop } = this.props; return ( <FormWithConstraints ref={formWithConstraints => (this.formWithConstraints = formWithConstraints)} > <input name="input" ref={input => (this.input = input)} /> <FieldFeedbacks for="input" stop={inputStop}> <Async promise={() => wait(10)} then={() => <FieldFeedback>Async error</FieldFeedback>} /> <FieldFeedback when={() => true}>Error after Async</FieldFeedback> <FieldFeedback when={() => true} warning> Warning after Async </FieldFeedback> <FieldFeedback when={() => true} info> Info after Async </FieldFeedback> </FieldFeedbacks> </FormWithConstraints> ); } } test('stop="first"', async () => { const wrapper = mount(<FormWithAfterAsync inputStop="first" />); const form = wrapper.instance() as FormWithAfterAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Async error</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-error"', async () => { const wrapper = mount(<FormWithAfterAsync inputStop="first-error" />); const form = wrapper.instance() as FormWithAfterAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Async error</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-warning"', async () => { const wrapper = mount(<FormWithAfterAsync inputStop="first-warning" />); const form = wrapper.instance() as FormWithAfterAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Async error</span> <span ${key}="0.0" ${error} ${dBlock}>Error after Async</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning after Async</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-info"', async () => { const wrapper = mount(<FormWithAfterAsync inputStop="first-info" />); const form = wrapper.instance() as FormWithAfterAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Async error</span> <span ${key}="0.0" ${error} ${dBlock}>Error after Async</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning after Async</span> <span ${key}="0.2" ${info} ${dBlock}>Info after Async</span> </span> </form>`); wrapper.unmount(); }); test('stop="no"', async () => { const wrapper = mount(<FormWithAfterAsync inputStop="no" />); const form = wrapper.instance() as FormWithAfterAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Async error</span> <span ${key}="0.0" ${error} ${dBlock}>Error after Async</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning after Async</span> <span ${key}="0.2" ${info} ${dBlock}>Info after Async</span> </span> </form>`); wrapper.unmount(); }); }); describe('FormWithMultipleNestedFieldFeedbacks - test FieldFeedbacks.validate() has*(fieldFeedbacksParent.key)', () => { class FormWithMultipleNestedFieldFeedbacks extends React.Component<FormProps> { formWithConstraints: FormWithConstraints | null = null; input: HTMLInputElement | null = null; render() { const { inputStop } = this.props; return ( <FormWithConstraints ref={formWithConstraints => (this.formWithConstraints = formWithConstraints)} > <input name="input" ref={input => (this.input = input)} /> <FieldFeedbacks for="input" stop={inputStop}> <FieldFeedbacks stop="no"> <FieldFeedback when={() => true}>Error 1</FieldFeedback> <FieldFeedback when={() => true} warning> Warning 1 </FieldFeedback> <FieldFeedback when={() => true} info> Info 1 </FieldFeedback> </FieldFeedbacks> </FieldFeedbacks> <FieldFeedbacks for="input" stop={inputStop}> <FieldFeedbacks stop="no"> <FieldFeedback when={() => true}>Error 2</FieldFeedback> <FieldFeedback when={() => true} warning> Warning 2 </FieldFeedback> <FieldFeedback when={() => true} info> Info 2 </FieldFeedback> </FieldFeedbacks> </FieldFeedbacks> </FormWithConstraints> ); } } test('stop="first"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedbacks inputStop="first" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedbacks; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${keys}="0.0"> <span ${key}="0.0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.0.2" ${info} ${dBlock}>Info 1</span> </span> </span> <span ${keys}="1"> <span ${keys}="1.0"> <span ${key}="1.0.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.0.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.0.2" ${info} ${dBlock}>Info 2</span> </span> </span> </form>`); wrapper.unmount(); }); test('stop="first-error"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedbacks inputStop="first-error" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedbacks; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${keys}="0.0"> <span ${key}="0.0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.0.2" ${info} ${dBlock}>Info 1</span> </span> </span> <span ${keys}="1"> <span ${keys}="1.0"> <span ${key}="1.0.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.0.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.0.2" ${info} ${dBlock}>Info 2</span> </span> </span> </form>`); wrapper.unmount(); }); test('stop="first-warning"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedbacks inputStop="first-warning" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedbacks; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${keys}="0.0"> <span ${key}="0.0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.0.2" ${info} ${dBlock}>Info 1</span> </span> </span> <span ${keys}="1"> <span ${keys}="1.0"> <span ${key}="1.0.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.0.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.0.2" ${info} ${dBlock}>Info 2</span> </span> </span> </form>`); wrapper.unmount(); }); test('stop="first-info"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedbacks inputStop="first-info" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedbacks; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${keys}="0.0"> <span ${key}="0.0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.0.2" ${info} ${dBlock}>Info 1</span> </span> </span> <span ${keys}="1"> <span ${keys}="1.0"> <span ${key}="1.0.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.0.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.0.2" ${info} ${dBlock}>Info 2</span> </span> </span> </form>`); wrapper.unmount(); }); test('stop="no"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedbacks inputStop="no" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedbacks; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${keys}="0.0"> <span ${key}="0.0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.0.2" ${info} ${dBlock}>Info 1</span> </span> </span> <span ${keys}="1"> <span ${keys}="1.0"> <span ${key}="1.0.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.0.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.0.2" ${info} ${dBlock}>Info 2</span> </span> </span> </form>`); wrapper.unmount(); }); }); describe('FormWithMultipleNestedAsync - test Async.validate() has*(fieldFeedbacks.key)', () => { class FormWithMultipleNestedAsync extends React.Component<FormProps> { formWithConstraints: FormWithConstraints | null = null; input: HTMLInputElement | null = null; render() { const { inputStop } = this.props; return ( <FormWithConstraints ref={formWithConstraints => (this.formWithConstraints = formWithConstraints)} > <input name="input" ref={input => (this.input = input)} /> <FieldFeedbacks for="input" stop={inputStop}> <Async promise={() => wait(10)} then={() => <FieldFeedback>Async1 error</FieldFeedback>} /> <Async promise={() => wait(10)} then={() => <FieldFeedback warning>Async1 warning</FieldFeedback>} /> <Async promise={() => wait(10)} then={() => <FieldFeedback info>Async1 info</FieldFeedback>} /> </FieldFeedbacks> <FieldFeedbacks for="input" stop={inputStop}> <Async promise={() => wait(10)} then={() => <FieldFeedback>Async2 error</FieldFeedback>} /> <Async promise={() => wait(10)} then={() => <FieldFeedback warning>Async2 warning</FieldFeedback>} /> <Async promise={() => wait(10)} then={() => <FieldFeedback info>Async2 info</FieldFeedback>} /> </FieldFeedbacks> </FormWithConstraints> ); } } test('stop="first"', async () => { const wrapper = mount(<FormWithMultipleNestedAsync inputStop="first" />); const form = wrapper.instance() as FormWithMultipleNestedAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Async1 error</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Async2 error</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-error"', async () => { const wrapper = mount(<FormWithMultipleNestedAsync inputStop="first-error" />); const form = wrapper.instance() as FormWithMultipleNestedAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Async1 error</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Async2 error</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-warning"', async () => { const wrapper = mount(<FormWithMultipleNestedAsync inputStop="first-warning" />); const form = wrapper.instance() as FormWithMultipleNestedAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Async1 error</span> <span ${key}="0.1" ${warning} ${dBlock}>Async1 warning</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Async2 error</span> <span ${key}="1.1" ${warning} ${dBlock}>Async2 warning</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-info"', async () => { const wrapper = mount(<FormWithMultipleNestedAsync inputStop="first-info" />); const form = wrapper.instance() as FormWithMultipleNestedAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Async1 error</span> <span ${key}="0.1" ${warning} ${dBlock}>Async1 warning</span> <span ${key}="0.2" ${info} ${dBlock}>Async1 info</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Async2 error</span> <span ${key}="1.1" ${warning} ${dBlock}>Async2 warning</span> <span ${key}="1.2" ${info} ${dBlock}>Async2 info</span> </span> </form>`); wrapper.unmount(); }); test('stop="no"', async () => { const wrapper = mount(<FormWithMultipleNestedAsync inputStop="no" />); const form = wrapper.instance() as FormWithMultipleNestedAsync; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Async1 error</span> <span ${key}="0.1" ${warning} ${dBlock}>Async1 warning</span> <span ${key}="0.2" ${info} ${dBlock}>Async1 info</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Async2 error</span> <span ${key}="1.1" ${warning} ${dBlock}>Async2 warning</span> <span ${key}="1.2" ${info} ${dBlock}>Async2 info</span> </span> </form>`); wrapper.unmount(); }); }); describe('FormWithMultipleNestedFieldFeedback - test FieldFeedback.validate() has*(fieldFeedbacks.key)', () => { class FormWithMultipleNestedFieldFeedback extends React.Component<FormProps> { formWithConstraints: FormWithConstraints | null = null; input: HTMLInputElement | null = null; render() { const { inputStop } = this.props; return ( <FormWithConstraints ref={formWithConstraints => (this.formWithConstraints = formWithConstraints)} > <input name="input" ref={input => (this.input = input)} /> <FieldFeedbacks for="input" stop={inputStop}> <FieldFeedback when={() => true}>Error 1</FieldFeedback> <FieldFeedback when={() => true} warning> Warning 1 </FieldFeedback> <FieldFeedback when={() => true} info> Info 1 </FieldFeedback> </FieldFeedbacks> <FieldFeedbacks for="input" stop={inputStop}> <FieldFeedback when={() => true}>Error 2</FieldFeedback> <FieldFeedback when={() => true} warning> Warning 2 </FieldFeedback> <FieldFeedback when={() => true} info> Info 2 </FieldFeedback> </FieldFeedbacks> </FormWithConstraints> ); } } test('stop="first"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedback inputStop="first" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedback; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error 1</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Error 2</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-error"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedback inputStop="first-error" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedback; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error 1</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Error 2</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-warning"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedback inputStop="first-warning" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedback; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning 1</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.1" ${warning} ${dBlock}>Warning 2</span> </span> </form>`); wrapper.unmount(); }); test('stop="first-info"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedback inputStop="first-info" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedback; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.2" ${info} ${dBlock}>Info 1</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.2" ${info} ${dBlock}>Info 2</span> </span> </form>`); wrapper.unmount(); }); test('stop="no"', async () => { const wrapper = mount(<FormWithMultipleNestedFieldFeedback inputStop="no" />); const form = wrapper.instance() as FormWithMultipleNestedFieldFeedback; await form.formWithConstraints!.validateFields(form.input!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="input"> <span ${keys}="0"> <span ${key}="0.0" ${error} ${dBlock}>Error 1</span> <span ${key}="0.1" ${warning} ${dBlock}>Warning 1</span> <span ${key}="0.2" ${info} ${dBlock}>Info 1</span> </span> <span ${keys}="1"> <span ${key}="1.0" ${error} ${dBlock}>Error 2</span> <span ${key}="1.1" ${warning} ${dBlock}>Warning 2</span> <span ${key}="1.2" ${info} ${dBlock}>Info 2</span> </span> </form>`); wrapper.unmount(); }); }); describe('validate', () => { describe('validateFields()', () => { test('inputs', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields(signUp.username!, signUp.passwordConfirm!); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Username 'john' already taken, choose another</span> </span> <input type="password" name="password"> <span ${keys}="1"></span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); wrapper.unmount(); }); test('field names', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields('username', 'passwordConfirm'); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); wrapper.unmount(); }); test('inputs + field names', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields(signUp.username!, 'passwordConfirm'); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); wrapper.unmount(); }); test('without arguments', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '123456', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); wrapper.unmount(); }); test('change inputs', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = ''; signUp.password!.value = ''; signUp.passwordConfirm!.value = ''; let fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: true }, { key: '0.1', type: 'error', show: undefined }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: true }, { key: '1.1', type: 'error', show: undefined }, { key: '1.2', type: 'warning', show: undefined }, { key: '1.3', type: 'warning', show: undefined }, { key: '1.4', type: 'warning', show: undefined }, { key: '1.5', type: 'warning', show: undefined }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: false }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: '', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '', validity: validValidityState, validationMessage: '' } ] ]); emitValidateFieldEventSpy.mockClear(); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '123456', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Username 'john' already taken, choose another</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); wrapper.unmount(); }); test('change inputs rapidly', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = ''; signUp.password!.value = ''; signUp.passwordConfirm!.value = ''; signUp.form!.validateFields(); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; signUp.form!.validateFields(); signUp.username!.value = 'jimmy'; signUp.password!.value = '12345'; signUp.passwordConfirm!.value = '12345'; const assertSpy = jest.spyOn(assert, 'assert').mockImplementation(); expect(assert.assert).toHaveBeenCalledTimes(0); const fields = await signUp.form!.validateFields(); expect(assert.assert).toHaveBeenCalledTimes(56); expect(assert.assert).toHaveBeenCalledWith( false, `FieldsStore does not match emitValidateFieldEvent() result, did the user changed the input rapidly?` ); assertSpy.mockRestore(); // eslint-disable-next-line no-constant-condition if (false /* Disable code because it randomly fails */) { // eslint-disable-next-line jest/no-conditional-expect expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'info', show: true }, { key: '0.4', type: 'error', show: true }, { key: '0.5', type: 'info', show: undefined }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: false }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); } expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(9); // eslint-disable-next-line no-constant-condition if (false /* Disable code because it randomly fails */) { // eslint-disable-next-line jest/no-conditional-expect expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: '', validity: validValidityState, validationMessage: '' } ], [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'username', type: 'text', value: 'jimmy', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ], // Instead of '123456'? [ { name: 'password', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ], // Instead of ''? [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); } wrapper.unmount(); }); }); describe('validateFieldsWithoutFeedback()', () => { // eslint-disable-next-line jest/expect-expect test('inputs', async () => { // }); // eslint-disable-next-line jest/expect-expect test('field names', async () => { // }); test('inputs + field names', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields1 = await signUp.form!.validateFieldsWithoutFeedback( signUp.username!, 'passwordConfirm' ); expect(fields1).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); // Fields are already dirty so calling validateFieldsWithoutFeedback() again won't do anything emitValidateFieldEventSpy.mockClear(); signUp.username!.value = 'jimmy'; signUp.password!.value = '12345'; signUp.passwordConfirm!.value = '12345'; const fields2 = await signUp.form!.validateFieldsWithoutFeedback( signUp.username!, 'passwordConfirm' ); expect(fields2).toEqual(fields1); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(0); expect(emitValidateFieldEventSpy.mock.calls).toEqual([]); wrapper.unmount(); }); test('without arguments', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields1 = await signUp.form!.validateFieldsWithoutFeedback(); expect(fields1).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'john', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '123456', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); // Fields are already dirty so calling validateFieldsWithoutFeedback() again won't do anything emitValidateFieldEventSpy.mockClear(); signUp.username!.value = 'jimmy'; signUp.password!.value = '12345'; signUp.passwordConfirm!.value = '12345'; const fields2 = await signUp.form!.validateFieldsWithoutFeedback(); expect(fields2).toEqual(fields1); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(0); expect(emitValidateFieldEventSpy.mock.calls).toEqual([]); wrapper.unmount(); }); test('Could not find field', async () => { const wrapper = mount( <FormWithConstraints> <input name="username" /> </FormWithConstraints> ); const form = wrapper.instance() as FormWithConstraints; expect(await form.validateFieldsWithoutFeedback()).toEqual([]); // Ignore input without FieldFeedbacks expect(await form.validateFieldsWithoutFeedback('username')).toEqual([]); // Ignore input without FieldFeedbacks await expect(form.validateFieldsWithoutFeedback('unknown')).rejects.toThrow( `Could not find field '[name="unknown"]' inside the form` ); wrapper.unmount(); }); }); test('validateForm()', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const validateFieldsWithoutFeedbackSpy = jest.spyOn( signUp.form!, 'validateFieldsWithoutFeedback' ); await signUp.form!.validateForm(); expect(validateFieldsWithoutFeedbackSpy).toHaveBeenCalledTimes(1); expect(validateFieldsWithoutFeedbackSpy.mock.calls).toEqual([[]]); wrapper.unmount(); }); describe('normalizeInputs', () => { test('Multiple elements matching', async () => { const wrapper = mount( <FormWithConstraints> <input name="username" /> <FieldFeedbacks for="username" /> <input type="password" name="password" /> <input type="password" name="password" /> <input type="password" name="password" /> <FieldFeedbacks for="password" /> </FormWithConstraints> ); const form = wrapper.instance() as FormWithConstraints; // [async/await toThrow is not working](https://github.com/facebook/jest/issues/1700) expect(await form.validateFields('username')).toEqual([ { name: 'username', element: expect.any(HTMLInputElement), validations: [] } ]); await expect(form.validateFields()).rejects.toThrow( `Multiple elements matching '[name="password"]' inside the form` ); await expect(form.validateFields('password')).rejects.toThrow( `Multiple elements matching '[name="password"]' inside the form` ); wrapper.unmount(); }); test('Could not find field', async () => { const wrapper = mount( <FormWithConstraints> <input name="username" /> </FormWithConstraints> ); const form = wrapper.instance() as FormWithConstraints; expect(await form.validateFields()).toEqual([]); // Ignore input without FieldFeedbacks expect(await form.validateFields('username')).toEqual([]); // Ignore input without FieldFeedbacks await expect(form.validateFields('unknown')).rejects.toThrow( `Could not find field '[name="unknown"]' inside the form` ); wrapper.unmount(); }); test('Could not find field - child with props undefined', async () => { const wrapper = mount(<FormWithConstraints>ChildWithPropsUndefined</FormWithConstraints>); const form = wrapper.instance() as FormWithConstraints; expect(await form.validateFields()).toEqual([]); await expect(form.validateFields('unknown')).rejects.toThrow( `Could not find field '[name="unknown"]' inside the form` ); wrapper.unmount(); }); test('Ignore elements without type', async () => { const wrapper = mount( <FormWithConstraints> <iframe src="https://www.google.com/recaptcha..." name="a-49ekipqfmwsv" /> </FormWithConstraints> ); const form = wrapper.instance() as FormWithConstraints; expect(await form.validateFields()).toEqual([]); await expect(form.validateFields('a-49ekipqfmwsv')).rejects.toThrow( `'[name="a-49ekipqfmwsv"]' should match an <input>, <select> or <textarea>` ); wrapper.unmount(); }); }); }); describe('Async', () => { test('then', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'jimmy'; signUp.password!.value = '12345'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'info', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: false }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'jimmy', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${info} ${dBlock}>Username 'jimmy' available</span> <span ${key}="0.2" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.1" ${whenValid} ${dBlock}>Looks good!</span> </span> </form>`); wrapper.unmount(); }); test('catch', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.username!.value = 'error'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: signUp.password, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [ { name: 'username', type: 'text', value: 'error', validity: validValidityState, validationMessage: '' } ], [ { name: 'password', type: 'password', value: '123456', validity: validValidityState, validationMessage: '' } ], [ { name: 'passwordConfirm', type: 'password', value: '12345', validity: validValidityState, validationMessage: '' } ] ]); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Something wrong with username 'error'</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); wrapper.unmount(); }); }); test('isValid()', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; let fields = await signUp.form!.validateFields( signUp.username!, signUp.password!, signUp.passwordConfirm! ); expect(fields.every(field => field.isValid())).toEqual(false); expect(signUp.form!.isValid()).toEqual(false); signUp.username!.value = 'jimmy'; signUp.password!.value = '12345'; signUp.passwordConfirm!.value = '12345'; fields = await signUp.form!.validateFields( signUp.username!, signUp.password!, signUp.passwordConfirm! ); expect(fields.every(field => field.isValid())).toEqual(true); expect(signUp.form!.isValid()).toEqual(true); wrapper.unmount(); }); test('hasFeedbacks()', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; expect(signUp.form!.hasFeedbacks()).toEqual(false); signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; const fields = await signUp.form!.validateFields( signUp.username!, signUp.password!, signUp.passwordConfirm! ); expect(fields.every(field => field.hasFeedbacks())).toEqual(true); expect(signUp.form!.hasFeedbacks()).toEqual(true); signUp.form!.resetFields(); expect(signUp.form!.hasFeedbacks()).toEqual(false); wrapper.unmount(); }); describe('resetFields()', () => { test('inputs', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Username 'john' already taken, choose another</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); signUp.form!.resetFields(signUp.username!, signUp.passwordConfirm!); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"></span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"></span> </form>`); wrapper.unmount(); }); test('field names', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Username 'john' already taken, choose another</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); signUp.form!.resetFields('username', 'passwordConfirm'); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"></span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"></span> </form>`); wrapper.unmount(); }); test('inputs + field names', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Username 'john' already taken, choose another</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); signUp.form!.resetFields(signUp.username!, 'passwordConfirm'); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"></span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"></span> </form>`); wrapper.unmount(); }); test('without arguments', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"> <span ${key}="0.3" ${error} ${dBlock}>Username 'john' already taken, choose another</span> </span> <input type="password" name="password"> <span ${keys}="1"> <span ${key}="1.3" ${warning} ${dBlock}>Should contain small letters</span> <span ${key}="1.4" ${warning} ${dBlock}>Should contain capital letters</span> <span ${key}="1.5" ${warning} ${dBlock}>Should contain special characters</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </span> <input type="password" name="passwordConfirm"> <span ${keys}="2"> <span ${key}="2.0" ${error} ${dBlock}>Not the same password</span> </span> </form>`); signUp.form!.resetFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <span ${keys}="0"></span> <input type="password" name="password"> <span ${keys}="1"></span> <input type="password" name="passwordConfirm"> <span ${keys}="2"></span> </form>`); wrapper.unmount(); }); test('Could not find field', async () => { const wrapper = mount( <FormWithConstraints> <input name="username" /> </FormWithConstraints> ); const form = wrapper.instance() as FormWithConstraints; expect(form.resetFields()).toEqual([]); // Ignore input without FieldFeedbacks expect(form.resetFields('username')).toEqual([]); // Ignore input without FieldFeedbacks expect(() => form.resetFields('unknown')).toThrow( new Error(`Could not find field '[name="unknown"]' inside the form`) ); wrapper.unmount(); }); }); test('reset()', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; const resetFieldsSpy = jest.spyOn(signUp.form!, 'resetFields'); signUp.form!.reset(); expect(resetFieldsSpy).toHaveBeenCalledTimes(1); expect(resetFieldsSpy.mock.calls).toEqual([[]]); wrapper.unmount(); });
the_stack
export { UiComponents } from "./components-react/UiComponents"; export * from "./components-react/breadcrumb/Breadcrumb"; export * from "./components-react/breadcrumb/BreadcrumbPath"; export * from "./components-react/breadcrumb/BreadcrumbTreeUtils"; export * from "./components-react/breadcrumb/BreadcrumbDetails"; export * from "./components-react/common/Links"; export * from "./components-react/common/PageOptions"; export * from "./components-react/common/selection/SelectionModes"; export * from "./components-react/common/HighlightingComponentProps"; export * from "./components-react/common/HighlightedText"; export * from "./components-react/common/IImageLoader"; export * from "./components-react/common/selection/SelectionHandler"; export * from "./components-react/common/showhide/ShowHideDialog"; export * from "./components-react/common/showhide/ShowHideItem"; export * from "./components-react/common/showhide/ShowHideMenu"; export * from "./components-react/common/UseAsyncValue"; export * from "./components-react/common/UseDebouncedAsyncValue"; export * from "./components-react/common/DateUtils"; export * from "./components-react/converters/TypeConverter"; export * from "./components-react/converters/TypeConverterManager"; export * from "./components-react/converters/BooleanTypeConverter"; export * from "./components-react/converters/DateTimeTypeConverter"; export * from "./components-react/converters/EnumTypeConverter"; export * from "./components-react/converters/HexadecimalTypeConverter"; export * from "./components-react/converters/NavigationPropertyTypeConverter"; export * from "./components-react/converters/NumericTypeConverter"; export * from "./components-react/converters/PointTypeConverter"; export * from "./components-react/converters/StringTypeConverter"; export * from "./components-react/converters/CompositeTypeConverter"; export * from "./components-react/converters/valuetypes/ConvertedTypes"; export * from "./components-react/datepicker/DateField"; export * from "./components-react/datepicker/DatePicker"; export * from "./components-react/datepicker/DatePickerPopupButton"; export * from "./components-react/datepicker/IntlFormatter"; export * from "./components-react/datepicker/TimeField"; export * from "./components-react/editors/BooleanEditor"; export * from "./components-react/editors/CustomNumberEditor"; export * from "./components-react/editors/DateTimeEditor"; export * from "./components-react/editors/EditorContainer"; export * from "./components-react/editors/EnumButtonGroupEditor"; export * from "./components-react/editors/EnumEditor"; export * from "./components-react/editors/IconEditor"; export * from "./components-react/editors/ImageCheckBoxEditor"; export * from "./components-react/editors/NumericInputEditor"; export * from "./components-react/editors/PropertyEditorManager"; export * from "./components-react/editors/SliderEditor"; export * from "./components-react/editors/TextEditor"; export * from "./components-react/editors/TextareaEditor"; export * from "./components-react/editors/ThemedEnumEditor"; export * from "./components-react/editors/ToggleEditor"; export * from "./components-react/favorite/FavoritePropertiesRenderer"; export * from "./components-react/favorite/FavoritePropertyList"; export * from "./components-react/filtering/FilteringInput"; export * from "./components-react/filtering/ResultSelector"; export * from "./components-react/iconpicker/IconPickerButton"; export * from "./components-react/inputs/ParsedInput"; export * from "./components-react/properties/LinkHandler"; export * from "./components-react/properties/ValueRendererManager"; export * from "./components-react/properties/renderers/NonPrimitivePropertyRenderer"; export * from "./components-react/properties/renderers/PrimitivePropertyRenderer"; export * from "./components-react/properties/renderers/PropertyRenderer"; export * from "./components-react/properties/renderers/PropertyView"; export * from "./components-react/properties/renderers/ActionButtonList"; export * from "./components-react/properties/renderers/ActionButtonRenderer"; export * from "./components-react/properties/renderers/value/MergedPropertyValueRenderer"; export * from "./components-react/properties/renderers/value/MultilineTextPropertyValueRenderer"; export * from "./components-react/properties/renderers/value/UrlPropertyValueRenderer"; export * from "./components-react/properties/renderers/value/WithContextStyle"; export * from "./components-react/properties/renderers/label/NonPrimitivePropertyLabelRenderer"; export * from "./components-react/properties/renderers/label/PrimitivePropertyLabelRenderer"; export * from "./components-react/properties/renderers/label/PropertyLabelRenderer"; export * from "./components-react/properties/renderers/value/PrimitivePropertyValueRenderer"; export * from "./components-react/properties/renderers/value/ArrayPropertyValueRenderer"; export * from "./components-react/properties/renderers/value/StructPropertyValueRenderer"; export * from "./components-react/properties/renderers/value/DoublePropertyValueRenderer"; export * from "./components-react/properties/renderers/value/NavigationPropertyValueRenderer"; export * from "./components-react/properties/renderers/value/table/ArrayValueRenderer"; export * from "./components-react/properties/renderers/value/table/StructValueRenderer"; export * from "./components-react/properties/renderers/value/table/NonPrimitiveValueRenderer"; export * from "./components-react/properties/ItemStyle"; export * from "./components-react/propertygrid/PropertyCategoryRendererManager"; export * from "./components-react/propertygrid/PropertyDataProvider"; export * from "./components-react/propertygrid/SimplePropertyDataProvider"; export * from "./components-react/propertygrid/component/PropertyGrid"; export * from "./components-react/propertygrid/component/VirtualizedPropertyGrid"; export * from "./components-react/propertygrid/component/VirtualizedPropertyGridWithDataProvider"; export * from "./components-react/propertygrid/component/PropertyCategoryBlock"; export * from "./components-react/propertygrid/component/PropertyGridEventsRelatedPropsSupplier"; export * from "./components-react/propertygrid/component/PropertyGridCommons"; export * from "./components-react/propertygrid/component/PropertyList"; export * from "./components-react/propertygrid/internal/flat-items/FlatGridItem"; export * from "./components-react/propertygrid/internal/flat-items/MutableCategorizedArrayProperty"; export * from "./components-react/propertygrid/internal/flat-items/MutableCategorizedPrimitiveProperty"; export * from "./components-react/propertygrid/internal/flat-items/MutableCategorizedStructProperty"; export * from "./components-react/propertygrid/internal/flat-items/MutableFlatGridItem"; export * from "./components-react/propertygrid/internal/flat-items/MutableGridCategory"; export * from "./components-react/propertygrid/internal/flat-items/MutableGridItemFactory"; export * from "./components-react/propertygrid/internal/PropertyGridEventHandler"; export * from "./components-react/propertygrid/internal/PropertyGridHooks"; export * from "./components-react/propertygrid/internal/PropertyGridModel"; export * from "./components-react/propertygrid/internal/PropertyGridModelChangeEvent"; export * from "./components-react/propertygrid/internal/PropertyGridModelSource"; export * from "./components-react/propertygrid/dataproviders/FilteringDataProvider"; export * from "./components-react/propertygrid/dataproviders/filterers/PropertyCategoryLabelFilterer"; export * from "./components-react/propertygrid/dataproviders/filterers/CompositePropertyDataFilterer"; export * from "./components-react/propertygrid/dataproviders/filterers/DisplayValuePropertyDataFilterer"; export * from "./components-react/propertygrid/dataproviders/filterers/LabelPropertyDataFilterer"; export * from "./components-react/propertygrid/dataproviders/filterers/PropertyDataFiltererBase"; export * from "./components-react/selectable-content/SelectableContent"; export * from "./components-react/table/TableDataProvider"; export * from "./components-react/table/SimpleTableDataProvider"; export * from "./components-react/table/columnfiltering/ColumnFiltering"; export * from "./components-react/table/columnfiltering/TableFilterDescriptorCollection"; export * from "./components-react/table/component/Table"; export * from "./components-react/table/component/TableCell"; export * from "./components-react/table/component/TableColumn"; export * from "./components-react/table/component/dragdrop/BeDragDropContext"; export * from "./components-react/toolbar/Toolbar"; export * from "./components-react/toolbar/ToolbarWithOverflow"; export * from "./components-react/toolbar/PopupItem"; export * from "./components-react/toolbar/PopupItemWithDrag"; export * from "./components-react/toolbar/Item"; export * from "./components-react/toolbar/utilities/Direction"; export * from "./components-react/tree/TreeDataProvider"; export * from "./components-react/tree/SimpleTreeDataProvider"; export * from "./components-react/tree/HighlightingEngine"; export * from "./components-react/tree/ImageLoader"; export * from "./components-react/tree/controlled/TreeActions"; export * from "./components-react/tree/controlled/TreeEventDispatcher"; export * from "./components-react/tree/controlled/TreeEventHandler"; export * from "./components-react/tree/controlled/TreeEvents"; export * from "./components-react/tree/controlled/TreeModel"; export * from "./components-react/tree/controlled/TreeModelSource"; export * from "./components-react/tree/controlled/TreeNodeLoader"; export * from "./components-react/tree/controlled/Observable"; export * from "./components-react/tree/controlled/TreeHooks"; export * from "./components-react/tree/controlled/component/ControlledTree"; export * from "./components-react/tree/controlled/component/TreeNodeEditor"; export * from "./components-react/tree/controlled/component/TreeNodeRenderer"; export * from "./components-react/tree/controlled/component/TreeRenderer"; export * from "./components-react/tree/controlled/internal/SparseTree"; /** @docs-package-description * The components-react package contains React components that are data-oriented, such as PropertyGrid, Table and Tree. * For more information, see [learning about components-react]($docs/learning/ui/components/index.md). */ /** * @docs-group-description Common * Common classes used across various UI components. */ /** * @docs-group-description Breadcrumb * Classes and components for working with a Breadcrumb. * As of version 3.0, the Breadcrumb is deprecated. */ /** * @docs-group-description Date * Classes, interfaces, and components for showing and setting date and time. */ /** * @docs-group-description DragDrop * Classes and Higher Order Components for working with the DragDrop API. */ /** * @docs-group-description Favorite * Classes and components for displaying favorite properties. */ /** * @docs-group-description Filtering * Classes and components for working with filtering. */ /** * @docs-group-description Inputs * Input Components that format and parse input. */ /** * @docs-group-description SelectableContent * Classes and components for working with SelectableContent component. */ /** * @docs-group-description Properties * Classes and components for working with Properties. */ /** * @docs-group-description PropertyEditors * Classes and components for working with Property Editors. */ /** * @docs-group-description PropertyGrid * Classes and components for working with a PropertyGrid. */ /** * @docs-group-description Table * Classes and components for working with a Table. */ /** * @docs-group-description Toolbar * Functions and components that provide a Toolbar. */ /** * @docs-group-description Tree * Classes and components for working with a Tree. */ /** * @docs-group-description TypeConverters * Classes for working with Type Converters. */
the_stack
import { Signer, providers } from "ethers"; import { Evt } from "evt"; import { createLoggingContext, Logger, NxtpError, RequestContext } from "@connext/nxtp-utils"; import { ChainConfig } from "./config"; import { WriteTransaction, OnchainTransaction, NxtpTxServiceEventPayloads, NxtpTxServiceEvent, NxtpTxServiceEvents, TxServiceConfirmedEvent, TxServiceFailedEvent, TxServiceMinedEvent, TxServiceSubmittedEvent, ConfigurationError, ProviderNotConfigured, } from "./shared"; import { ChainReader } from "./chainreader"; import { TransactionDispatch } from "./dispatch"; // TODO: Should take on the logic of Dispatch (rename to TransactionDispatch) and consume ChainReader instead of extending it. /** * @classdesc Handles submitting, confirming, and bumping gas of arbitrary transactions onchain. Also performs onchain reads with embedded retries */ export class TransactionService extends ChainReader { // TODO: #152 Add an object/dictionary statically to the class prototype mapping the // signer to a flag indicating whether there is an instance using that signer. // This will prevent two queue instances using the same signer and therefore colliding. // Idea is to have essentially a modified 'singleton'-like pattern. // private static _instances: Map<string, TransactionService> = new Map(); private static instance?: TransactionService; /// Events emitted in lifecycle of TransactionService's sendTx. private evts: { [K in NxtpTxServiceEvent]: Evt<NxtpTxServiceEventPayloads[K]> } = { [NxtpTxServiceEvents.TransactionSubmitted]: Evt.create<TxServiceSubmittedEvent>(), [NxtpTxServiceEvents.TransactionMined]: Evt.create<TxServiceMinedEvent>(), [NxtpTxServiceEvents.TransactionConfirmed]: Evt.create<TxServiceConfirmedEvent>(), [NxtpTxServiceEvents.TransactionFailed]: Evt.create<TxServiceFailedEvent>(), }; /** * A singleton-like interface for handling all logic related to conducting on-chain transactions. * * @remarks * Using the Signer instance passed into this constructor outside of the context of this * class is not recommended, and may cause issues with nonce being tracked improperly * due to the caching mechanisms used here. * * @param logger The Logger used for logging. * @param signer The Signer or Wallet instance, or private key, for signing transactions. * @param config At least a partial configuration used by TransactionService for chains, * providers, etc. */ constructor(logger: Logger, config: any, signer: string | Signer) { super(logger, config, signer); const { requestContext, methodContext } = createLoggingContext("ChainService.constructor"); // TODO: #152 See above TODO. Should we have a getInstance() method and make constructor private ?? // const _signer: string = typeof signer === "string" ? signer : signer.getAddress(); // if (TransactionService._instances.has(_signer)) {} if (TransactionService.instance) { const msg = "CRITICAL: ChainService.constructor was called twice! Please report this incident."; const error = new NxtpError(msg); logger.error(msg, requestContext, methodContext, error, { instance: TransactionService.instance.toString(), }); throw error; } // Set the singleton instance. TransactionService.instance = this; } /** * Send specified transaction on specified chain and wait for the configured number of confirmations. * Will emit events throughout its lifecycle. * * @param tx - Tx to send * @param tx.chainId - Chain to send transaction on * @param tx.to - Address to send tx to * @param tx.value - Value to send tx with * @param tx.data - Calldata to execute * @param tx.from - (optional) Account to send tx from * * @returns TransactionReceipt once the tx is mined if the transaction was successful. * * @throws TransactionError with one of the reasons specified in ValidSendErrors. If another error occurs, * something went wrong within TransactionService process. * @throws TransactionServiceFailure, which indicates something went wrong with the service logic. */ public async sendTx(tx: WriteTransaction, context: RequestContext): Promise<providers.TransactionReceipt> { const { requestContext, methodContext } = createLoggingContext(this.sendTx.name, context); this.logger.debug("Method start", requestContext, methodContext, { tx: { ...tx, value: tx.value.toString(), data: `${tx.data.substring(0, 9)}...` }, }); return await this.getProvider(tx.chainId).send(tx, context); } /// LISTENER METHODS /** * Attaches a callback to the emitted event * * @param event - The event name to attach a handler for * @param callback - The callback to invoke on event emission * @param filter - (optional) A filter where callbacks are only invoked if the filter returns true * @param timeout - (optional) A timeout to detach the handler within. I.e. if no events fired within the timeout, then the handler is detached */ public attach<T extends NxtpTxServiceEvent>( event: T, callback: (data: NxtpTxServiceEventPayloads[T]) => void, filter: (data: NxtpTxServiceEventPayloads[T]) => boolean = (_data: NxtpTxServiceEventPayloads[T]) => true, timeout?: number, ): void { const args = [timeout, callback].filter((x) => !!x); this.evts[event].pipe(filter).attach(...(args as [number, any])); } /** * Attaches a callback to the emitted event that will be executed one time and then detached. * * @param event - The event name to attach a handler for * @param callback - The callback to invoke on event emission * @param filter - (optional) A filter where callbacks are only invoked if the filter returns true * @param timeout - (optional) A timeout to detach the handler within. I.e. if no events fired within the timeout, then the handler is detached * */ public attachOnce<T extends NxtpTxServiceEvent>( event: T, callback: (data: NxtpTxServiceEventPayloads[T]) => void, filter: (data: NxtpTxServiceEventPayloads[T]) => boolean = (_data: NxtpTxServiceEventPayloads[T]) => true, timeout?: number, ): void { const args = [timeout, callback].filter((x) => !!x); this.evts[event].pipe(filter).attachOnce(...(args as [number, any])); } /** * Removes all attached handlers from the given event. * * @param event - (optional) The event name to remove handlers from. If not provided, will detach handlers from *all* subgraph events */ public detach<T extends NxtpTxServiceEvent>(event?: T): void { if (event) { this.evts[event].detach(); return; } Object.values(this.evts).forEach((evt) => evt.detach()); } /** * Returns a promise that resolves when the event matching the filter is emitted * * @param event - The event name to wait for * @param timeout - The ms to continue waiting before rejecting * @param filter - (optional) A filter where the promise is only resolved if the filter returns true * * @returns Promise that will resolve with the event payload once the event is emitted, or rejects if the timeout is reached. * */ public waitFor<T extends NxtpTxServiceEvent>( event: T, timeout: number, filter: (data: NxtpTxServiceEventPayloads[T]) => boolean = (_data: NxtpTxServiceEventPayloads[T]) => true, ): Promise<NxtpTxServiceEventPayloads[T]> { return this.evts[event].pipe(filter).waitFor(timeout) as Promise<NxtpTxServiceEventPayloads[T]>; } /// HELPERS /** * Helper to wrap getting provider for specified chain ID. * @param chainId The ID of the chain for which we want a provider. * @returns The ChainRpcProvider for that chain. * @throws TransactionError.reasons.ProviderNotFound if provider is not configured for * that ID. */ public getProvider(chainId: number): TransactionDispatch { // Ensure that a signer, provider, etc are present to execute on this chainId. if (!this.providers.has(chainId)) { throw new ProviderNotConfigured(chainId.toString()); } return this.providers.get(chainId)! as TransactionDispatch; } // TODO: Use a generic type in ChainReader.setupProviders for this method such that we don't have to overload it here. /** * Populate the provider mapping using chain configurations. * @param context - The request context object used for logging. * @param signer - The signer that will be used for onchain operations. */ protected setupProviders(context: RequestContext, signer: string | Signer) { const { methodContext } = createLoggingContext(this.setupProviders.name, context); // For each chain ID / provider, map out all the utils needed for each chain. Object.keys(this.config).forEach((chainId) => { // Get this chain's config. const chain: ChainConfig = this.config[chainId]; // Ensure at least one provider is configured. if (chain.providers.length === 0) { const error = new ConfigurationError( [ { parameter: "providers", error: "No valid providers were supplied in configuration for this chain.", value: providers, }, ], { chainId, }, ); this.logger.error("Failed to create transaction service", context, methodContext, error.toJson(), { chainId, providers, }); throw error; } const chainIdNumber = parseInt(chainId); const provider = new TransactionDispatch(this.logger, chainIdNumber, chain, signer, { onSubmit: (transaction: OnchainTransaction) => this.evts[NxtpTxServiceEvents.TransactionSubmitted].post({ responses: transaction.responses }), onMined: (transaction: OnchainTransaction) => this.evts[NxtpTxServiceEvents.TransactionMined].post({ receipt: transaction.receipt! }), onConfirm: (transaction: OnchainTransaction) => this.evts[NxtpTxServiceEvents.TransactionConfirmed].post({ receipt: transaction.receipt! }), onFail: (transaction: OnchainTransaction) => this.evts[NxtpTxServiceEvents.TransactionFailed].post({ error: transaction.error!, receipt: transaction.receipt, }), }); this.providers.set(chainIdNumber, provider); }); } }
the_stack
import { Component, ContentChild, DoCheck, ElementRef, EventEmitter, forwardRef, HostBinding, Input, IterableDiffer, IterableDiffers, OnInit, Optional, Output, Renderer2, TemplateRef, ViewEncapsulation } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { IonItem, ModalController, Platform } from '@ionic/angular'; import { AnimationBuilder, ModalOptions } from '@ionic/core'; import { Subscription } from 'rxjs'; import { IonicSelectableAddItemTemplateDirective } from './ionic-selectable-add-item-template.directive'; import { IonicSelectableCloseButtonTemplateDirective } from './ionic-selectable-close-button-template.directive'; import { IonicSelectableFooterTemplateDirective } from './ionic-selectable-footer-template.directive'; import { IonicSelectableGroupEndTemplateDirective } from './ionic-selectable-group-end-template.directive'; import { IonicSelectableGroupTemplateDirective } from './ionic-selectable-group-template.directive'; import { IonicSelectableHeaderTemplateDirective } from './ionic-selectable-header-template.directive'; import { IonicSelectableItemEndTemplateDirective } from './ionic-selectable-item-end-template.directive'; import { IonicSelectableItemIconTemplateDirective } from './ionic-selectable-item-icon-template.directive'; import { IonicSelectableItemTemplateDirective } from './ionic-selectable-item-template.directive'; import { IonicSelectableMessageTemplateDirective } from './ionic-selectable-message-template.directive'; import { IonicSelectableModalComponent } from './ionic-selectable-modal.component'; import { IonicSelectablePlaceholderTemplateDirective } from './ionic-selectable-placeholder-template.directive'; import { IonicSelectableSearchFailTemplateDirective } from './ionic-selectable-search-fail-template.directive'; import { IonicSelectableTitleTemplateDirective } from './ionic-selectable-title-template.directive'; import { IonicSelectableValueTemplateDirective } from './ionic-selectable-value-template.directive'; import { IonicSelectableIconTemplateDirective } from './ionic-selectable-icon-template.directive'; @Component({ selector: 'ionic-selectable', templateUrl: './ionic-selectable.component.html', styleUrls: ['./ionic-selectable.component.scss'], encapsulation: ViewEncapsulation.None, providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => IonicSelectableComponent), multi: true }] }) export class IonicSelectableComponent implements ControlValueAccessor, OnInit, DoCheck { @HostBinding('class.ionic-selectable') _cssClass = true; @HostBinding('class.ionic-selectable-ios') _isIos: boolean; @HostBinding('class.ionic-selectable-md') _isMD: boolean; @HostBinding('class.ionic-selectable-is-multiple') get _isMultipleCssClass(): boolean { return this.isMultiple; } @HostBinding('class.ionic-selectable-has-value') get _hasValueCssClass(): boolean { return this.hasValue(); } @HostBinding('class.ionic-selectable-has-placeholder') get _hasPlaceholderCssClass(): boolean { return this._hasPlaceholder; } @HostBinding('class.ionic-selectable-has-label') get _hasIonLabelCssClass(): boolean { return this._hasIonLabel; } @HostBinding('class.ionic-selectable-label-default') get _hasDefaultIonLabelCssClass(): boolean { return this._ionLabelPosition === 'default'; } @HostBinding('class.ionic-selectable-label-fixed') get _hasFixedIonLabelCssClass(): boolean { return this._ionLabelPosition === 'fixed'; } @HostBinding('class.ionic-selectable-label-stacked') get _hasStackedIonLabelCssClass(): boolean { return this._ionLabelPosition === 'stacked'; } @HostBinding('class.ionic-selectable-label-floating') get _hasFloatingIonLabelCssClass(): boolean { return this._ionLabelPosition === 'floating'; } private _isOnSearchEnabled = true; private _isEnabled = true; private _shouldBackdropClose = true; private _isOpened = false; private _value: any = null; private _modal: HTMLIonModalElement; private _itemsDiffer: IterableDiffer<any>; private _hasObjects: boolean; private _canClear = false; private _hasConfirmButton = false; private _isMultiple = false; private _canAddItem = false; private _addItemObservable: Subscription; private _deleteItemObservable: Subscription; private onItemsChange: EventEmitter<any> = new EventEmitter(); private _ionItemElement: any; private _ionLabelElement: any; private _hasIonLabel = false; private _ionLabelPosition: 'fixed' | 'stacked' | 'floating' | 'default' | null = null; private _label: string = null; private get _hasInfiniteScroll(): boolean { return this.isEnabled && this._modalComponent && this._modalComponent._infiniteScroll ? true : false; } get _shouldStoreItemValue(): boolean { return this.shouldStoreItemValue && this._hasObjects; } _valueItems: any[] = []; _searchText = ''; _hasSearchText = false; _groups: any[] = []; _itemsToConfirm: any[] = []; _selectedItems: any[] = []; _modalComponent: IonicSelectableModalComponent; _filteredGroups: any[] = []; _hasGroups: boolean; _isSearching: boolean; _hasPlaceholder: boolean; _isAddItemTemplateVisible = false; _isFooterVisible = true; _itemToAdd: any = null; _footerButtonsCount = 0; _hasFilteredItems = false; /** * Text of [Ionic Label](https://ionicframework.com/docs/api/label). * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#label). * * @readonly * @default null * @memberof IonicSelectableComponent */ get label(): string { return this._label; } /** * Text that the user has typed in Searchbar. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#searchtext). * * @readonly * @default '' * @memberof IonicSelectableComponent */ get searchText(): string { return this._searchText; } set searchText(searchText: string) { this._searchText = searchText; this._setHasSearchText(); } /** * Determines whether search is running. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#issearching). * * @default false * @readonly * @memberof IonicSelectableComponent */ get isSearching(): boolean { return this._isSearching; } /** * Determines whether user has typed anything in Searchbar. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hassearchtext). * * @default false * @readonly * @memberof IonicSelectableComponent */ get hasSearchText(): boolean { return this._hasSearchText; } get value(): any { return this._value; } set value(value: any) { this._value = value; // Set value items. this._valueItems.splice(0, this._valueItems.length); if (this.isMultiple) { if (value && value.length) { Array.prototype.push.apply(this._valueItems, value); } } else { if (!this._isNullOrWhiteSpace(value)) { this._valueItems.push(value); } } this._setIonItemHasValue(); this._setHasPlaceholder(); } /** * A list of items. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#items). * * @default [] * @memberof IonicSelectableComponent */ @Input() items: any[] = []; @Output() itemsChange: EventEmitter<any> = new EventEmitter(); /** * Determines whether the component is enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#isenabled). * * @default true * @memberof IonicSelectableComponent */ @HostBinding('class.ionic-selectable-is-enabled') @Input('isEnabled') get isEnabled(): boolean { return this._isEnabled; } set isEnabled(isEnabled: boolean) { this._isEnabled = !!isEnabled; this.enableIonItem(this._isEnabled); } /** * Determines whether Modal should be closed when backdrop is clicked. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#shouldbackdropclose). * * @default true * @memberof IonicSelectableComponent */ @Input('shouldBackdropClose') get shouldBackdropClose(): boolean { return this._shouldBackdropClose; } set shouldBackdropClose(shouldBackdropClose: boolean) { this._shouldBackdropClose = !!shouldBackdropClose; } /** * Modal CSS class. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#modalcssclass). * * @default null * @memberof IonicSelectableComponent */ @Input() modalCssClass: string = null; /** * Modal enter animation. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#modalenteranimation). * * @default null * @memberof IonicSelectableComponent */ @Input() modalEnterAnimation: AnimationBuilder = null; /** * Modal leave animation. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#modalleaveanimation). * * @default null * @memberof IonicSelectableComponent */ @Input() modalLeaveAnimation: AnimationBuilder = null; /** * Determines whether Modal is opened. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#isopened). * * @default false * @readonly * @memberof IonicSelectableComponent */ get isOpened(): boolean { return this._isOpened; } /** * Determines whether Confirm button is enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#isconfirmbuttonenabled). * * @default true * @memberof IonicSelectableComponent */ @Input() isConfirmButtonEnabled = true; /** * Determines whether Confirm button is visible for single selection. * By default Confirm button is visible only for multiple selection. * **Note**: It is always true for multiple selection and cannot be changed. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hasconfirmbutton). * * @default true * @memberof IonicSelectableComponent */ @Input('hasConfirmButton') get hasConfirmButton(): boolean { return this._hasConfirmButton; } set hasConfirmButton(hasConfirmButton: boolean) { this._hasConfirmButton = !!hasConfirmButton; this._countFooterButtons(); } /** * Item property to use as a unique identifier, e.g, `'id'`. * **Note**: `items` should be an object array. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#itemvaluefield). * * @default null * @memberof IonicSelectableComponent */ @Input() itemValueField: string = null; /** * Item property to display, e.g, `'name'`. * **Note**: `items` should be an object array. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#itemtextfield). * * @default false * @memberof IonicSelectableComponent */ @Input() itemTextField: string = null; /** * * Group property to use as a unique identifier to group items, e.g. `'country.id'`. * **Note**: `items` should be an object array. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#groupvaluefield). * * @default null * @memberof IonicSelectableComponent */ @Input() groupValueField: string = null; /** * Group property to display, e.g. `'country.name'`. * **Note**: `items` should be an object array. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#grouptextfield). * * @default null * @memberof IonicSelectableComponent */ @Input() groupTextField: string = null; /** * Determines whether to show Searchbar. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#cansearch). * * @default false * @memberof IonicSelectableComponent */ @Input() canSearch = false; /** * Determines whether `onSearch` event is enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#isonsearchenabled). * * @default true * @memberof IonicSelectableComponent */ @Input('isOnSearchEnabled') get isOnSearchEnabled(): boolean { return this._isOnSearchEnabled; } set isOnSearchEnabled(isOnSearchEnabled: boolean) { this._isOnSearchEnabled = !!isOnSearchEnabled; } /** * Determines whether to show Clear button. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#canclear). * * @default false * @memberof IonicSelectableComponent */ @HostBinding('class.ionic-selectable-can-clear') @Input('canClear') get canClear(): boolean { return this._canClear; } set canClear(canClear: boolean) { this._canClear = !!canClear; this._countFooterButtons(); } /** * Determines whether Ionic [InfiniteScroll](https://ionicframework.com/docs/api/components/infinite-scroll/InfiniteScroll/) is enabled. * **Note**: Infinite scroll cannot be used together with virtual scroll. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hasinfinitescroll). * * @default false * @memberof IonicSelectableComponent */ @Input() hasInfiniteScroll = false; /** * Determines whether Ionic [VirtualScroll](https://ionicframework.com/docs/api/components/virtual-scroll/VirtualScroll/) is enabled. * **Note**: Virtual scroll cannot be used together with infinite scroll. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hasvirtualscroll). * * @default false * @memberof IonicSelectableComponent */ @Input() hasVirtualScroll = false; /** * See Ionic VirtualScroll [approxItemHeight](https://ionicframework.com/docs/api/components/virtual-scroll/VirtualScroll/). * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#virtualscrollapproxitemheight). * * @default '40px' * @memberof IonicSelectableComponent */ @Input() virtualScrollApproxItemHeight = '40px'; /** * A placeholder for Searchbar. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#searchplaceholder). * * @default 'Search' * @memberof IonicSelectableComponent */ @Input() searchPlaceholder = 'Search'; /** * A placeholder. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#placeholder). * * @default null * @memberof IonicSelectableComponent */ @Input() placeholder: string = null; /** * Determines whether multiple items can be selected. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#ismultiple). * * @default false * @memberof IonicSelectableComponent */ @Input('isMultiple') get isMultiple(): boolean { return this._isMultiple; } set isMultiple(isMultiple: boolean) { this._isMultiple = !!isMultiple; this._countFooterButtons(); } /** * Text to display when no items have been found during search. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#searchfailtext). * * @default 'No items found.' * @memberof IonicSelectableComponent */ @Input() searchFailText = 'No items found.'; /** * Clear button text. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#clearbuttontext). * * @default 'Clear' * @memberof IonicSelectableComponent */ @Input() clearButtonText = 'Clear'; /** * Add button text. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#addbuttontext). * * @default 'Add' * @memberof IonicSelectableComponent */ @Input() addButtonText = 'Add'; /** * Confirm button text. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#confirmbuttontext). * * @default 'OK' * @memberof IonicSelectableComponent */ @Input() confirmButtonText = 'OK'; /** * Close button text. * The field is only applicable to **iOS** platform, on **Android** only Cross icon is displayed. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#closebuttontext). * * @default 'Cancel' * @memberof IonicSelectableComponent */ @Input() closeButtonText = 'Cancel'; /** * Determines whether Searchbar should receive focus when Modal is opened. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#shouldfocussearchbar). * * @default false * @memberof IonicSelectableComponent */ @Input() shouldFocusSearchbar = false; /** * Header color. [Ionic colors](https://ionicframework.com/docs/theming/advanced#colors) are supported. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#headercolor). * * @default null * @memberof IonicSelectableComponent */ @Input() headerColor: string = null; /** * Group color. [Ionic colors](https://ionicframework.com/docs/theming/advanced#colors) are supported. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#groupcolor). * * @default null * @memberof IonicSelectableComponent */ @Input() groupColor: string = null; /** * Close button slot. [Ionic slots](https://ionicframework.com/docs/api/buttons) are supported. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#closebuttonslot). * * @default 'start' * @memberof IonicSelectableComponent */ @Input() closeButtonSlot = 'start'; /** * Item icon slot. [Ionic slots](https://ionicframework.com/docs/api/item) are supported. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#itemiconslot). * * @default 'start' * @memberof IonicSelectableComponent */ @Input() itemIconSlot = 'start'; /** * Fires when item/s has been selected and Modal closed. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onchange). * * @memberof IonicSelectableComponent */ @Output() onChange: EventEmitter<{ component: IonicSelectableComponent, value: any }> = new EventEmitter(); /** * Fires when the user is typing in Searchbar. * **Note**: `canSearch` and `isOnSearchEnabled` has to be enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onsearch). * * @memberof IonicSelectableComponent */ @Output() onSearch: EventEmitter<{ component: IonicSelectableComponent, text: string }> = new EventEmitter(); /** * Fires when no items have been found. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onsearchfail). * * @memberof IonicSelectableComponent */ @Output() onSearchFail: EventEmitter<{ component: IonicSelectableComponent, text: string }> = new EventEmitter(); /** * Fires when some items have been found. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onsearchsuccess). * * @memberof IonicSelectableComponent */ @Output() onSearchSuccess: EventEmitter<{ component: IonicSelectableComponent, text: string }> = new EventEmitter(); /** * Fires when the user has scrolled to the end of the list. * **Note**: `hasInfiniteScroll` has to be enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#oninfinitescroll). * * @memberof IonicSelectableComponent */ @Output() onInfiniteScroll: EventEmitter<{ component: IonicSelectableComponent, text: string }> = new EventEmitter(); /** * Fires when Modal has been opened. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onopen). * * @memberof IonicSelectableComponent */ @Output() onOpen: EventEmitter<{ component: IonicSelectableComponent }> = new EventEmitter(); /** * Fires when Modal has been closed. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onclose). * * @memberof IonicSelectableComponent */ @Output() onClose: EventEmitter<{ component: IonicSelectableComponent }> = new EventEmitter(); /** * Fires when an item has been selected or unselected. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onselect). * * @memberof IonicSelectableComponent */ @Output() onSelect: EventEmitter<{ component: IonicSelectableComponent, item: any, isSelected: boolean }> = new EventEmitter(); /** * Fires when Clear button has been clicked. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onclear). * * @memberof IonicSelectableComponent */ @Output() onClear: EventEmitter<{ component: IonicSelectableComponent, items: any[] }> = new EventEmitter(); /** * A list of items that are selected and awaiting confirmation by user, when he has clicked Confirm button. * After the user has clicked Confirm button items to confirm are cleared. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#itemstoconfirm). * * @default [] * @readonly * @memberof IonicSelectableComponent */ get itemsToConfirm(): any[] { return this._itemsToConfirm; } /** * How long, in milliseconds, to wait to filter items or to trigger `onSearch` event after each keystroke. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#searchdebounce). * * @default 250 * @memberof IonicSelectableComponent */ @Input() searchDebounce: Number = 250; /** * A list of items to disable. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#disableditems). * * @default [] * @memberof IonicSelectableComponent */ @Input() disabledItems: any[] = []; /** * Determines whether item value only should be stored in `ngModel`, not the entire item. * **Note**: Item value is defined by `itemValueField`. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#shouldstoreitemvalue). * * @default false * @memberof IonicSelectableComponent */ @Input() shouldStoreItemValue = false; /** * Determines whether to allow editing items. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#cansaveitem). * * @default false * @memberof IonicSelectableComponent */ @Input() canSaveItem = false; /** * Determines whether to allow deleting items. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#candeleteitem). * * @default false * @memberof IonicSelectableComponent */ @Input() canDeleteItem = false; /** * Determines whether to allow adding items. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#canadditem). * * @default false * @memberof IonicSelectableComponent */ @Input('canAddItem') get canAddItem(): boolean { return this._canAddItem; } set canAddItem(canAddItem: boolean) { this._canAddItem = !!canAddItem; this._countFooterButtons(); } /** * Fires when Edit item button has been clicked. * When the button has been clicked `ionicSelectableAddItemTemplate` will be shown. Use the template to create a form to edit item. * **Note**: `canSaveItem` has to be enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onsaveitem). * * @memberof IonicSelectableComponent */ @Output() onSaveItem: EventEmitter<{ component: IonicSelectableComponent, item: any }> = new EventEmitter(); /** * Fires when Delete item button has been clicked. * **Note**: `canDeleteItem` has to be enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#ondeleteitem). * * @memberof IonicSelectableComponent */ @Output() onDeleteItem: EventEmitter<{ component: IonicSelectableComponent, item: any }> = new EventEmitter(); /** * Fires when Add item button has been clicked. * When the button has been clicked `ionicSelectableAddItemTemplate` will be shown. Use the template to create a form to add item. * **Note**: `canAddItem` has to be enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#onadditem). * * @memberof IonicSelectableComponent */ @Output() onAddItem: EventEmitter<{ component: IonicSelectableComponent }> = new EventEmitter(); @ContentChild(IonicSelectableValueTemplateDirective, { read: TemplateRef }) valueTemplate: TemplateRef<any>; @ContentChild(IonicSelectableItemTemplateDirective, { read: TemplateRef }) itemTemplate: TemplateRef<any>; @ContentChild(IonicSelectableItemEndTemplateDirective, { read: TemplateRef }) itemEndTemplate: TemplateRef<any>; @ContentChild(IonicSelectableTitleTemplateDirective, { read: TemplateRef }) titleTemplate: TemplateRef<any>; @ContentChild(IonicSelectablePlaceholderTemplateDirective, { read: TemplateRef }) placeholderTemplate: TemplateRef<any>; @ContentChild(IonicSelectableMessageTemplateDirective, { read: TemplateRef }) messageTemplate: TemplateRef<any>; @ContentChild(IonicSelectableGroupTemplateDirective, { read: TemplateRef }) groupTemplate: TemplateRef<any>; @ContentChild(IonicSelectableGroupEndTemplateDirective, { read: TemplateRef }) groupEndTemplate: TemplateRef<any>; @ContentChild(IonicSelectableCloseButtonTemplateDirective, { read: TemplateRef }) closeButtonTemplate: TemplateRef<any>; @ContentChild(IonicSelectableSearchFailTemplateDirective, { read: TemplateRef }) searchFailTemplate: TemplateRef<any>; @ContentChild(IonicSelectableAddItemTemplateDirective, { read: TemplateRef }) addItemTemplate: TemplateRef<any>; @ContentChild(IonicSelectableFooterTemplateDirective, { read: TemplateRef }) footerTemplate: TemplateRef<any>; _addItemTemplateFooterHeight: string; @ContentChild(IonicSelectableHeaderTemplateDirective, { read: TemplateRef }) headerTemplate: TemplateRef<any>; @ContentChild(IonicSelectableItemIconTemplateDirective, { read: TemplateRef }) itemIconTemplate: TemplateRef<any>; @ContentChild(IonicSelectableIconTemplateDirective, { read: TemplateRef }) iconTemplate: TemplateRef<any>; /** * See Ionic VirtualScroll [headerFn](https://ionicframework.com/docs/api/components/virtual-scroll/VirtualScroll/). * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#virtualscrollheaderfn). * * @memberof IonicSelectableComponent */ @Input() virtualScrollHeaderFn = () => { return null; } constructor( private _modalController: ModalController, private _platform: Platform, @Optional() private ionItem: IonItem, private _iterableDiffers: IterableDiffers, private _element: ElementRef, private _renderer: Renderer2 ) { if (!this.items || !this.items.length) { this.items = []; } this._itemsDiffer = this._iterableDiffers.find(this.items).create(); } initFocus() { } enableIonItem(isEnabled: boolean) { if (!this.ionItem) { return; } this.ionItem.disabled = !isEnabled; } _isNullOrWhiteSpace(value: any): boolean { if (value === null || value === undefined) { return true; } // Convert value to string in case if it's not. return value.toString().replace(/\s/g, '').length < 1; } _setHasSearchText() { this._hasSearchText = !this._isNullOrWhiteSpace(this._searchText); } _hasOnSearch(): boolean { return this.isOnSearchEnabled && this.onSearch.observers.length > 0; } _hasOnSaveItem(): boolean { return this.canSaveItem && this.onSaveItem.observers.length > 0; } _hasOnAddItem(): boolean { return this.canAddItem && this.onAddItem.observers.length > 0; } _hasOnDeleteItem(): boolean { return this.canDeleteItem && this.onDeleteItem.observers.length > 0; } _emitValueChange() { this.propagateOnChange(this.value); this.onChange.emit({ component: this, value: this.value }); } _emitSearch() { if (!this.canSearch) { return; } this.onSearch.emit({ component: this, text: this._searchText }); } _emitOnSelect(item: any, isSelected: boolean) { this.onSelect.emit({ component: this, item: item, isSelected: isSelected }); } _emitOnClear(items: any[]) { this.onClear.emit({ component: this, items: items }); } _emitOnSearchSuccessOrFail(isSuccess: boolean) { const eventData = { component: this, text: this._searchText }; if (isSuccess) { this.onSearchSuccess.emit(eventData); } else { this.onSearchFail.emit(eventData); } } _formatItem(item: any): string { if (this._isNullOrWhiteSpace(item)) { return null; } return this.itemTextField ? item[this.itemTextField] : item.toString(); } _formatValueItem(item: any): string { if (this._shouldStoreItemValue) { // Get item text from the list as we store it's value only. const selectedItem = this.items.find(_item => { return _item[this.itemValueField] === item; }); return this._formatItem(selectedItem); } else { return this._formatItem(item); } } _getItemValue(item: any): any { if (!this._hasObjects) { return item; } return item[this.itemValueField]; } _getStoredItemValue(item: any): any { if (!this._hasObjects) { return item; } return this._shouldStoreItemValue ? item : item[this.itemValueField]; } _onSearchbarClear() { // Ionic Searchbar doesn't clear bind with ngModel value. // Do it ourselves. this._searchText = ''; } _filterItems() { this._setHasSearchText(); if (this._hasOnSearch()) { // Delegate filtering to the event. this._emitSearch(); } else { // Default filtering. let groups = []; if (!this._searchText || !this._searchText.trim()) { groups = this._groups; } else { const filterText = this._searchText.trim().toLowerCase(); this._groups.forEach(group => { const items = group.items.filter(item => { const itemText = (this.itemTextField ? item[this.itemTextField] : item).toString().toLowerCase(); return itemText.indexOf(filterText) !== -1; }); if (items.length) { groups.push({ value: group.value, text: group.text, items: items }); } }); // No items found. if (!groups.length) { groups.push({ items: [] }); } } this._filteredGroups = groups; this._hasFilteredItems = !this._areGroupsEmpty(groups); this._emitOnSearchSuccessOrFail(this._hasFilteredItems); } } _isItemDisabled(item: any): boolean { if (!this.disabledItems) { return; } return this.disabledItems.some(_item => { return this._getItemValue(_item) === this._getItemValue(item); }); } _isItemSelected(item: any) { return this._selectedItems.find(selectedItem => { return this._getItemValue(item) === this._getStoredItemValue(selectedItem); }) !== undefined; } _addSelectedItem(item: any) { if (this._shouldStoreItemValue) { this._selectedItems.push(this._getItemValue(item)); } else { this._selectedItems.push(item); } } _deleteSelectedItem(item: any) { let itemToDeleteIndex; this._selectedItems.forEach((selectedItem, itemIndex) => { if ( this._getItemValue(item) === this._getStoredItemValue(selectedItem) ) { itemToDeleteIndex = itemIndex; } }); this._selectedItems.splice(itemToDeleteIndex, 1); } _click() { if (!this.isEnabled) { return; } this._label = this._getLabelText(); this.open().then(() => { this.onOpen.emit({ component: this }); }); } _saveItem(event: Event, item: any) { event.stopPropagation(); this._itemToAdd = item; if (this._hasOnSaveItem()) { this.onSaveItem.emit({ component: this, item: this._itemToAdd }); } else { this.showAddItemTemplate(); } } _deleteItemClick(event: Event, item: any) { event.stopPropagation(); this._itemToAdd = item; if (this._hasOnDeleteItem()) { // Delegate logic to event. this.onDeleteItem.emit({ component: this, item: this._itemToAdd }); } else { this.deleteItem(this._itemToAdd); } } _addItemClick() { if (this._hasOnAddItem()) { this.onAddItem.emit({ component: this }); } else { this.showAddItemTemplate(); } } _positionAddItemTemplate() { // Wait for the template to render. setTimeout(() => { const footer = this._modalComponent._element.nativeElement .querySelector('.ionic-selectable-add-item-template ion-footer'); this._addItemTemplateFooterHeight = footer ? `calc(100% - ${footer.offsetHeight}px)` : '100%'; }, 100); } _close() { this.close().then(() => { this.onClose.emit({ component: this }); }); if (!this._hasOnSearch()) { this._searchText = ''; this._setHasSearchText(); } } _clear() { const selectedItems = this._selectedItems; this.clear(); this._emitValueChange(); this._emitOnClear(selectedItems); this.close().then(() => { this.onClose.emit({ component: this }); }); } _getMoreItems() { this.onInfiniteScroll.emit({ component: this, text: this._searchText }); } _setItemsToConfirm(items: any[]) { // Return a copy of original array, so it couldn't be changed from outside. this._itemsToConfirm = [].concat(items); } _doSelect(selectedItem: any) { this.value = selectedItem; this._emitValueChange(); } _select(item: any) { const isItemSelected = this._isItemSelected(item); if (this.isMultiple) { if (isItemSelected) { this._deleteSelectedItem(item); } else { this._addSelectedItem(item); } this._setItemsToConfirm(this._selectedItems); // Emit onSelect event after setting items to confirm so they could be used // inside the event. this._emitOnSelect(item, !isItemSelected); } else { if (this.hasConfirmButton || this.footerTemplate) { // Don't close Modal and keep track on items to confirm. // When footer template is used it's up to developer to close Modal. this._selectedItems = []; if (isItemSelected) { this._deleteSelectedItem(item); } else { this._addSelectedItem(item); } this._setItemsToConfirm(this._selectedItems); // Emit onSelect event after setting items to confirm so they could be used // inside the event. this._emitOnSelect(item, !isItemSelected); } else { if (!isItemSelected) { this._selectedItems = []; this._addSelectedItem(item); // Emit onSelect before onChange. this._emitOnSelect(item, true); if (this._shouldStoreItemValue) { this._doSelect(this._getItemValue(item)); } else { this._doSelect(item); } } this._close(); } } } _confirm() { this.confirm(); this._close(); } private _getLabelText(): string { return this._ionLabelElement ? this._ionLabelElement.textContent : null; } private _areGroupsEmpty(groups) { return groups.length === 0 || groups.every(group => { return !group.items || group.items.length === 0; }); } private _countFooterButtons() { let footerButtonsCount = 0; if (this.canClear) { footerButtonsCount++; } if (this.isMultiple || this._hasConfirmButton) { footerButtonsCount++; } if (this.canAddItem) { footerButtonsCount++; } this._footerButtonsCount = footerButtonsCount; } private _setItems(items: any[]) { // It's important to have an empty starting group with empty items (groups[0].items), // because we bind to it when using VirtualScroll. // See https://github.com/eakoriakin/ionic-selectable/issues/70. let groups: any[] = [{ items: items || [] }]; if (items && items.length) { if (this._hasGroups) { groups = []; items.forEach(item => { const groupValue = this._getPropertyValue(item, this.groupValueField), group = groups.find(_group => _group.value === groupValue); if (group) { group.items.push(item); } else { groups.push({ value: groupValue, text: this._getPropertyValue(item, this.groupTextField), items: [item] }); } }); } } this._groups = groups; this._filteredGroups = this._groups; this._hasFilteredItems = !this._areGroupsEmpty(this._filteredGroups); } private _getPropertyValue(object: any, property: string): any { if (!property) { return null; } return property.split('.').reduce((_object, _property) => { return _object ? _object[_property] : null; }, object); } private _setIonItemHasFocus(hasFocus: boolean) { if (!this.ionItem) { return; } // Apply focus CSS class for proper stylying of ion-item/ion-label. this._setIonItemCssClass('item-has-focus', hasFocus); } private _setIonItemHasValue() { if (!this.ionItem) { return; } // Apply value CSS class for proper stylying of ion-item/ion-label. this._setIonItemCssClass('item-has-value', this.hasValue()); } private _setHasPlaceholder() { this._hasPlaceholder = !this.hasValue() && (!this._isNullOrWhiteSpace(this.placeholder) || this.placeholderTemplate) ? true : false; } private propagateOnChange = (_: any) => { }; private propagateOnTouched = () => { }; private _setIonItemCssClass(cssClass: string, shouldAdd: boolean) { if (!this._ionItemElement) { return; } // Change to Renderer2 if (shouldAdd) { this._renderer.addClass(this._ionItemElement, cssClass); } else { this._renderer.removeClass(this._ionItemElement, cssClass); } } private _toggleAddItemTemplate(isVisible: boolean) { // It should be possible to show/hide the template regardless // canAddItem or canSaveItem parameters, so we could implement some // custom behavior. E.g. adding item when search fails using onSearchFail event. if (!this.addItemTemplate) { return; } // To make SaveItemTemplate visible we just position it over list using CSS. // We don't hide list with *ngIf or [hidden] to prevent its scroll position. this._isAddItemTemplateVisible = isVisible; this._isFooterVisible = !isVisible; } /* ControlValueAccessor */ writeValue(value: any) { this.value = value; } registerOnChange(method: any): void { this.propagateOnChange = method; } registerOnTouched(method: () => void) { this.propagateOnTouched = method; } setDisabledState(isDisabled: boolean) { this.isEnabled = !isDisabled; } /* .ControlValueAccessor */ ngOnInit() { this._isIos = this._platform.is('ios'); this._isMD = !this._isIos; this._hasObjects = !this._isNullOrWhiteSpace(this.itemValueField); // Grouping is supported for objects only. // Ionic VirtualScroll has it's own implementation of grouping. this._hasGroups = Boolean(this._hasObjects && this.groupValueField && !this.hasVirtualScroll); if (this.ionItem) { this._ionItemElement = this._element.nativeElement.closest('ion-item'); this._setIonItemCssClass('item-interactive', true); this._setIonItemCssClass('item-ionic-selectable', true); if (this._ionItemElement) { this._ionLabelElement = this._ionItemElement.querySelector('ion-label'); if (this._ionLabelElement) { this._hasIonLabel = true; this._ionLabelPosition = this._ionLabelElement.getAttribute('position') || 'default'; } } } this.enableIonItem(this.isEnabled); } ngDoCheck() { const itemsChanges = this._itemsDiffer.diff(this.items); if (itemsChanges) { this._setItems(this.items); this.value = this.value; this.onItemsChange.emit({ component: this }); } } /** * Adds item. * **Note**: If you want an item to be added to the original array as well use two-way data binding syntax on `[(items)]` field. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#additem). * * @param item Item to add. * @returns Promise that resolves when item has been added. * @memberof IonicSelectableComponent */ addItem(item: any): Promise<any> { const self = this; // Adding item triggers onItemsChange. // Return a promise that resolves when onItemsChange finishes. // We need a promise or user could do something after item has been added, // e.g. use search() method to find the added item. this.items.unshift(item); // Close any running subscription. if (this._addItemObservable) { this._addItemObservable.unsubscribe(); } return new Promise(function (resolve, reject) { // Complete callback isn't fired for some reason, // so unsubscribe in both success and fail cases. self._addItemObservable = self.onItemsChange.asObservable().subscribe(() => { self._addItemObservable.unsubscribe(); resolve(); }, () => { self._addItemObservable.unsubscribe(); reject(); }); }); } /** * Deletes item. * **Note**: If you want an item to be deleted from the original array as well use two-way data binding syntax on `[(items)]` field. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#deleteitem). * * @param item Item to delete. * @returns Promise that resolves when item has been deleted. * @memberof IonicSelectableComponent */ deleteItem(item: any): Promise<any> { const self = this; let hasValueChanged = false; // Remove deleted item from selected items. if (this._selectedItems) { this._selectedItems = this._selectedItems.filter(_item => { return this._getItemValue(item) !== this._getStoredItemValue(_item); }); } // Remove deleted item from value. if (this.value) { if (this.isMultiple) { const values = this.value.filter(value => { return value.id !== item.id; }); if (values.length !== this.value.length) { this.value = values; hasValueChanged = true; } } else { if (item === this.value) { this.value = null; hasValueChanged = true; } } } if (hasValueChanged) { this._emitValueChange(); } // Remove deleted item from list. const items = this.items.filter(_item => { return _item.id !== item.id; }); // Refresh items on parent component. this.itemsChange.emit(items); // Refresh list. this._setItems(items); this.onItemsChange.emit({ component: this }); // Close any running subscription. if (this._deleteItemObservable) { this._deleteItemObservable.unsubscribe(); } return new Promise(function (resolve, reject) { // Complete callback isn't fired for some reason, // so unsubscribe in both success and fail cases. self._deleteItemObservable = self.onItemsChange.asObservable().subscribe(() => { self._deleteItemObservable.unsubscribe(); resolve(); }, () => { self._deleteItemObservable.unsubscribe(); reject(); }); }); } /** * Determines whether any item has been selected. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hasvalue). * * @returns A boolean determining whether any item has been selected. * @memberof IonicSelectableComponent */ hasValue(): boolean { if (this.isMultiple) { return this._valueItems.length !== 0; } else { return this._valueItems.length !== 0 && !this._isNullOrWhiteSpace(this._valueItems[0]); } } /** * Opens Modal. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#open). * * @returns Promise that resolves when Modal has been opened. * @memberof IonicSelectableComponent */ open(): Promise<void> { const self = this; return new Promise(function (resolve, reject) { if (!self._isEnabled || self._isOpened) { reject('IonicSelectable is disabled or already opened.'); return; } self._filterItems(); self._isOpened = true; const modalOptions: ModalOptions = { component: IonicSelectableModalComponent, componentProps: { selectComponent: self }, backdropDismiss: self._shouldBackdropClose }; if (self.modalCssClass) { modalOptions.cssClass = self.modalCssClass; } if (self.modalEnterAnimation) { modalOptions.enterAnimation = self.modalEnterAnimation; } if (self.modalLeaveAnimation) { modalOptions.leaveAnimation = self.modalLeaveAnimation; } self._modalController.create(modalOptions).then(modal => { self._modal = modal; modal.present().then(() => { // Set focus after Modal has opened to avoid flickering of focus highlighting // before Modal opening. self._setIonItemHasFocus(true); resolve(); }); modal.onWillDismiss().then(() => { self._setIonItemHasFocus(false); }); modal.onDidDismiss().then(event => { self._isOpened = false; self._itemsToConfirm = []; // Closed by clicking on backdrop outside modal. if (event.role === 'backdrop') { self.onClose.emit({ component: self }); } }); }); }); } /** * Closes Modal. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#close). * * @returns Promise that resolves when Modal has been closed. * @memberof IonicSelectableComponent */ close(): Promise<void> { const self = this; return new Promise(function (resolve, reject) { if (!self._isEnabled || !self._isOpened) { reject('IonicSelectable is disabled or already closed.'); return; } self.propagateOnTouched(); self._isOpened = false; self._itemToAdd = null; self._modal.dismiss().then(() => { self._setIonItemHasFocus(false); self.hideAddItemTemplate(); resolve(); }); }); } /** * Clears value. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#clear). * * @memberof IonicSelectableComponent */ clear() { this.value = this.isMultiple ? [] : null; this._itemsToConfirm = []; this.propagateOnChange(this.value); } /** * Confirms selected items by updating value. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#confirm). * * @memberof IonicSelectableComponent */ confirm() { if (this.isMultiple) { this._doSelect(this._selectedItems); } else if (this.hasConfirmButton || this.footerTemplate) { this._doSelect(this._selectedItems[0] || null); } } /** * Selects or deselects all or specific items. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#toggleitems). * * @param isSelect Determines whether to select or deselect items. * @param [items] Items to toggle. If items are not set all items will be toggled. * @memberof IonicSelectableComponent */ toggleItems(isSelect: boolean, items?: any[]) { if (isSelect) { const hasItems = items && items.length; let itemsToToggle = this._groups.reduce((allItems, group) => { return allItems.concat(group.items); }, []); // Don't allow to select all items in single mode. if (!this.isMultiple && !hasItems) { itemsToToggle = []; } // Toggle specific items. if (hasItems) { itemsToToggle = itemsToToggle.filter(itemToToggle => { return items.find(item => { return this._getItemValue(itemToToggle) === this._getItemValue(item); }) !== undefined; }); // Take the first item for single mode. if (!this.isMultiple) { itemsToToggle.splice(0, 1); } } itemsToToggle.forEach(item => { this._addSelectedItem(item); }); } else { this._selectedItems = []; } this._setItemsToConfirm(this._selectedItems); } /** * Scrolls to the top of Modal content. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#scrolltotop). * * @returns Promise that resolves when scroll has been completed. * @memberof IonicSelectableComponent */ scrollToTop(): Promise<any> { const self = this; return new Promise(function (resolve, reject) { if (!self._isOpened) { reject('IonicSelectable content cannot be scrolled.'); return; } self._modalComponent._content.scrollToTop().then(() => { resolve(); }); }); } /** * Scrolls to the bottom of Modal content. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#scrolltobottom). * * @returns Promise that resolves when scroll has been completed. * @memberof IonicSelectableComponent */ scrollToBottom(): Promise<any> { const self = this; return new Promise(function (resolve, reject) { if (!self._isOpened) { reject('IonicSelectable content cannot be scrolled.'); return; } self._modalComponent._content.scrollToBottom().then(() => { resolve(); }); }); } /** * Starts search process by showing Loading spinner. * Use it together with `onSearch` event to indicate search start. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#startsearch). * * @memberof IonicSelectableComponent */ startSearch() { if (!this._isEnabled) { return; } this.showLoading(); } /** * Ends search process by hiding Loading spinner and refreshing items. * Use it together with `onSearch` event to indicate search end. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#endsearch). * * @memberof IonicSelectableComponent */ endSearch() { if (!this._isEnabled) { return; } this.hideLoading(); // When inside Ionic Modal and onSearch event is used, // ngDoCheck() doesn't work as _itemsDiffer fails to detect changes. // See https://github.com/eakoriakin/ionic-selectable/issues/44. // Refresh items manually. this._setItems(this.items); this._emitOnSearchSuccessOrFail(this._hasFilteredItems); } /** * Enables infinite scroll. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#enableinfinitescroll). * * @memberof IonicSelectableComponent */ enableInfiniteScroll() { if (!this._hasInfiniteScroll) { return; } this._modalComponent._infiniteScroll.disabled = false; } /** * Disables infinite scroll. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#disableinfinitescroll). * * @memberof IonicSelectableComponent */ disableInfiniteScroll() { if (!this._hasInfiniteScroll) { return; } this._modalComponent._infiniteScroll.disabled = true; } /** * Ends infinite scroll. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#endinfinitescroll). * * @memberof IonicSelectableComponent */ endInfiniteScroll() { if (!this._hasInfiniteScroll) { return; } this._modalComponent._infiniteScroll.complete(); this._setItems(this.items); } /** * Triggers search of items. * **Note**: `canSearch` has to be enabled. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#search). * * @param text Text to search items by. * @memberof IonicSelectableComponent */ search(text: string) { if (!this._isEnabled || !this._isOpened || !this.canSearch) { return; } this._searchText = text; this._setHasSearchText(); this._filterItems(); } /** * Shows Loading spinner. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#showloading). * * @memberof IonicSelectableComponent */ showLoading() { if (!this._isEnabled) { return; } this._isSearching = true; } /** * Hides Loading spinner. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hideloading). * * @memberof IonicSelectableComponent */ hideLoading() { if (!this._isEnabled) { return; } this._isSearching = false; } /** * Shows `ionicSelectableAddItemTemplate`. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#showadditemtemplate). * * @memberof IonicSelectableComponent */ showAddItemTemplate() { this._toggleAddItemTemplate(true); // Position the template only when it shous up. this._positionAddItemTemplate(); } /** * Hides `ionicSelectableAddItemTemplate`. * See more on [GitHub](https://github.com/eakoriakin/ionic-selectable/wiki/Documentation#hideadditemtemplate). * * @memberof IonicSelectableComponent */ hideAddItemTemplate() { // Clean item to add as it's no longer needed once Add Item Modal has been closed. this._itemToAdd = null; this._toggleAddItemTemplate(false); } }
the_stack
import {deleteCatalog, saveCatalog} from '@/services/data/tuples/catalog'; import {Catalog} from '@/services/data/tuples/catalog-types'; import {QueryTopicForHolder} from '@/services/data/tuples/query-topic-types'; import {QueryUserForHolder} from '@/services/data/tuples/query-user-types'; import {TopicId} from '@/services/data/tuples/topic-types'; import {TupleHolder} from '@/services/data/tuples/tuple-types'; import {UserId} from '@/services/data/tuples/user-types'; import {isFakedUuid} from '@/services/data/tuples/utils'; import {Button} from '@/widgets/basic/button'; import {ICON_LOADING} from '@/widgets/basic/constants'; import {Dropdown} from '@/widgets/basic/dropdown'; import {Input} from '@/widgets/basic/input'; import {InputLines} from '@/widgets/basic/input-lines'; import {ButtonInk, DropdownOption} from '@/widgets/basic/types'; import {useForceUpdate} from '@/widgets/basic/utils'; import {useEventBus} from '@/widgets/events/event-bus'; import {EventTypes} from '@/widgets/events/types'; import {TupleEventBusProvider} from '@/widgets/tuple-workbench/tuple-event-bus'; import {TupleItemPicker} from '@/widgets/tuple-workbench/tuple-item-picker'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import React, {ChangeEvent, useState} from 'react'; import {DQCCacheData} from '../../cache/types'; import {useDataQualityCacheData} from '../../cache/use-cache-data'; import {useCatalogEventBus} from '../catalog-event-bus'; import {CatalogEventTypes} from '../catalog-event-bus-types'; import {useUserData} from '../user-cache/use-user-data'; import { CatalogCell, CatalogEditButtons, CatalogEditCell, CatalogEditLabel, CatalogRowContainer, CatalogSeqCell } from './widgets'; interface EditCatalog extends Omit<Catalog, 'tags'>, TupleHolder { flatTags: string; } const asEditingCatalog = (catalog: Catalog): EditCatalog => { return { ...catalog, flatTags: (catalog.tags || []).join(' ') }; }; const getUserName = (users: Array<QueryUserForHolder>, userId?: UserId): string => { if (userId == null || userId.trim().length === 0) { return 'Not Designated'; } // eslint-disable-next-line return users.find(user => user.userId == userId)?.name ?? 'Not Designated'; }; export const CatalogRow = (props: { catalog: Catalog; index: number }) => { const {catalog, index} = props; const {fire: fireGlobal} = useEventBus(); const {fire} = useCatalogEventBus(); const [changed, setChanged] = useState(isFakedUuid(catalog)); const [expanded, setExpanded] = useState(isFakedUuid(catalog)); const [saving, setSaving] = useState(false); const [editingCatalog, setEditingCatalog] = useState<EditCatalog>(asEditingCatalog(catalog)); const [topics, setTopics] = useState<Array<QueryTopicForHolder>>([]); const [users, setUsers] = useState<Array<QueryUserForHolder>>([]); const forceUpdate = useForceUpdate(); const [dataHolder] = useState(() => { return { onTopicData: (data?: DQCCacheData) => { if (data) { setTopics((data.topics || []).map(topic => { return { topicId: topic.topicId, name: topic.name }; })); } }, onUserData: (users: Array<QueryUserForHolder>) => setUsers(users) }; }); useDataQualityCacheData({onDataRetrieved: dataHolder.onTopicData}); useUserData(dataHolder.onUserData); const changeAndForceUpdate = () => { if (!changed) { setChanged(true); fire(CatalogEventTypes.CATALOG_CHANGED, catalog); } else { forceUpdate(); } }; const onNameChanged = (event: ChangeEvent<HTMLInputElement>) => { editingCatalog.name = event.target.value; changeAndForceUpdate(); }; const changeOwnerId = (userId: UserId | '', owner: 'techOwnerId' | 'bizOwnerId') => { if (userId === '') { delete editingCatalog[owner]; } else { editingCatalog[owner] = userId; } changeAndForceUpdate(); }; const onTechOwnerChanged = (option: DropdownOption) => { changeOwnerId(option.value, 'techOwnerId'); }; const onBizOwnerChanged = (option: DropdownOption) => { changeOwnerId(option.value, 'bizOwnerId'); }; const onTagsChanged = (event: ChangeEvent<HTMLInputElement>) => { editingCatalog.flatTags = event.target.value; changeAndForceUpdate(); }; const onDescChanged = (event: ChangeEvent<HTMLTextAreaElement>) => { editingCatalog.description = event.target.value; changeAndForceUpdate(); }; const onSaveClicked = () => { setSaving(true); fireGlobal(EventTypes.INVOKE_REMOTE_REQUEST, async () => { const catalogToSave: Catalog = { ...editingCatalog, tags: (editingCatalog.flatTags || '').split(' ').map(tag => tag.trim()).filter(tag => tag !== '').map(tag => tag.toLowerCase()) }; // @ts-ignore delete catalogToSave.flatTags; await saveCatalog(catalogToSave); return catalogToSave; }, (catalogToSave: Catalog) => { // sync data to model Object.keys(catalogToSave).forEach(prop => { // @ts-ignore catalog[prop as keyof Catalog] = catalogToSave[prop as keyof Catalog]; }); setChanged(false); setSaving(false); fire(CatalogEventTypes.CATALOG_SAVED, catalog); }, () => setSaving(false)); }; const onDiscardClicked = () => { setEditingCatalog(asEditingCatalog(catalog)); setChanged(false); }; const onDeleteClicked = () => { fireGlobal(EventTypes.SHOW_YES_NO_DIALOG, 'Are you sure to delete selected catalog? Please note that deletion cannot be recovered.', () => { fireGlobal(EventTypes.HIDE_DIALOG); setSaving(true); fireGlobal(EventTypes.INVOKE_REMOTE_REQUEST, async () => await deleteCatalog(catalog), () => { setSaving(false); fire(CatalogEventTypes.CATALOG_DELETED, catalog); }, () => setSaving(false)); }, () => fireGlobal(EventTypes.HIDE_DIALOG)); }; const onCollapseClicked = () => { setExpanded(false); }; const onExpandClicked = () => { setExpanded(true); }; const ownerOptions: Array<DropdownOption> = [ {value: '', label: 'Not Designated'}, ...users.map(user => { return { value: user.userId, label: user.name }; }).sort((a, b) => { return (a.label || '').localeCompare(b.label || '', void 0, {sensitivity: 'base', caseFirst: 'upper'}); }) ]; const isHolding = () => editingCatalog.topicIds != null && editingCatalog.topicIds.length > 0; const getHoldIds = () => editingCatalog.topicIds || []; const getNameOfHold = (topicId: TopicId, topics: Array<QueryTopicForHolder>) => { // eslint-disable-next-line return topics.find(topic => topic.topicId == topicId)?.name ?? ''; }; const listTopics = async (search: string): Promise<Array<QueryTopicForHolder>> => { return new Promise<Array<QueryTopicForHolder>>(resolve => { resolve(topics.filter(topic => (topic.name || '').toLowerCase().indexOf((search || '').toLowerCase()) !== -1)); }); }; const getTopicId = (topic: QueryTopicForHolder) => topic.topicId; const getTopicName = (topic: QueryTopicForHolder) => topic.name; // eslint-disable-next-line const isTopicHold = (topic: QueryTopicForHolder) => (editingCatalog.topicIds || []).some(topicId => topic.topicId == topicId); const removeTopic = (topicOrId: string | QueryTopicForHolder) => { let topicId: TopicId; if (typeof topicOrId === 'string') { topicId = topicOrId; } else { topicId = topicOrId.topicId; } // eslint-disable-next-line const index = (editingCatalog.topicIds || []).findIndex(id => id == topicId); if (index !== -1) { (editingCatalog.topicIds || []).splice(index, 1); changeAndForceUpdate(); } }; const addTopic = (topic: QueryTopicForHolder) => { const {topicId} = topic; // eslint-disable-next-line const index = (editingCatalog.topicIds || []).findIndex(id => id == topicId); if (index === -1) { if (editingCatalog.topicIds == null) { editingCatalog.topicIds = []; } editingCatalog.topicIds.push(topicId); changeAndForceUpdate(); } }; return <CatalogRowContainer data-changed={changed} data-expanded={expanded} onClick={expanded ? (void 0) : onExpandClicked}> <CatalogSeqCell>{index}</CatalogSeqCell> <CatalogCell> {expanded ? <Input value={editingCatalog.name || ''} onChange={onNameChanged}/> : (editingCatalog.name || 'Noname Catalog')} </CatalogCell> <CatalogCell>{(editingCatalog.topicIds || []).length}</CatalogCell> <CatalogCell> {expanded ? <Dropdown value={editingCatalog.techOwnerId ?? ''} options={ownerOptions} onChange={onTechOwnerChanged}/> : getUserName(users, editingCatalog.techOwnerId)} </CatalogCell> <CatalogCell> {expanded ? <Dropdown value={editingCatalog.bizOwnerId ?? ''} options={ownerOptions} onChange={onBizOwnerChanged}/> : getUserName(users, editingCatalog.bizOwnerId)} </CatalogCell> <CatalogCell> </CatalogCell> <CatalogEditCell data-expanded={expanded}> <CatalogEditLabel>Topics</CatalogEditLabel> <TupleEventBusProvider> <TupleItemPicker actionLabel="Pick topics" holder={editingCatalog} codes={topics} isHolding={isHolding} getHoldIds={getHoldIds} getNameOfHold={getNameOfHold} listCandidates={listTopics} getIdOfCandidate={getTopicId} getNameOfCandidate={getTopicName} isCandidateHold={isTopicHold} removeHold={removeTopic} addHold={addTopic}/> </TupleEventBusProvider> <CatalogEditLabel>Tags</CatalogEditLabel> <Input value={editingCatalog.flatTags} onChange={onTagsChanged} placeholder="Tags split by space character."/> <CatalogEditLabel>Description</CatalogEditLabel> <InputLines value={editingCatalog.description ?? ''} onChange={onDescChanged}/> <CatalogEditLabel/> <CatalogEditButtons> <Button ink={ButtonInk.PRIMARY} onClick={onCollapseClicked}> <span>Collapse</span> </Button> {changed ? <> <Button ink={ButtonInk.PRIMARY} onClick={onSaveClicked}> {saving ? <FontAwesomeIcon icon={ICON_LOADING} spin={true}/> : null} <span>Save</span> </Button> <Button ink={ButtonInk.PRIMARY} onClick={onDiscardClicked}> <span>Discard</span> </Button> </> : null} <Button ink={ButtonInk.DANGER} onClick={onDeleteClicked}> {saving ? <FontAwesomeIcon icon={ICON_LOADING} spin={true}/> : null} <span>Delete</span> </Button> </CatalogEditButtons> </CatalogEditCell> </CatalogRowContainer>; };
the_stack
/** * @license Copyright © 2018 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQuery UI plugin that wraps Leaflet maps. */ namespace VRS { /* * Backwards compatible global options. These are not used, they are here so that custom scripts that * rely on them won't crash. */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.mapGoogleMapHttpUrl = VRS.globalOptions.mapGoogleMapHttpUrl || ''; VRS.globalOptions.mapGoogleMapHttpsUrl = VRS.globalOptions.mapGoogleMapHttpsUrl || ''; VRS.globalOptions.mapGoogleMapTimeout = VRS.globalOptions.mapGoogleMapTimeout || 30000; VRS.globalOptions.mapGoogleMapUseHttps = VRS.globalOptions.mapGoogleMapUseHttps !== undefined ? VRS.globalOptions.mapGoogleMapUseHttps : true; VRS.globalOptions.mapShowStreetView = VRS.globalOptions.mapShowStreetView !== undefined ? VRS.globalOptions.mapShowStreetView : false; VRS.globalOptions.mapShowHighContrastStyle = VRS.globalOptions.mapShowHighContrastStyle !== undefined ? VRS.globalOptions.mapShowHighContrastStyle : true; VRS.globalOptions.mapHighContrastMapStyle = VRS.globalOptions.mapHighContrastMapStyle !== undefined ? VRS.globalOptions.mapHighContrastMapStyle : []; /* * These options are shared with Google Maps. They should probably be moved out of both plugin modules to somewhere common. */ VRS.globalOptions.mapScrollWheelActive = VRS.globalOptions.mapScrollWheelActive !== undefined ? VRS.globalOptions.mapScrollWheelActive : true; VRS.globalOptions.mapDraggable = VRS.globalOptions.mapDraggable !== undefined ? VRS.globalOptions.mapDraggable : true; VRS.globalOptions.mapShowPointsOfInterest = VRS.globalOptions.mapShowPointsOfInterest !== undefined ? VRS.globalOptions.mapShowPointsOfInterest : false; VRS.globalOptions.mapShowScaleControl = VRS.globalOptions.mapShowScaleControl !== undefined ? VRS.globalOptions.mapShowScaleControl : true; /* * These options are only used by Leaflet. */ VRS.globalOptions.mapLeafletNoWrap = VRS.globalOptions.mapLeafletNoWrap !== undefined ? VRS.globalOptions.mapLeafletNoWrap : true; export type LeafletControlPosition = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; export class LeafletUtilities { fromLeafletLatLng(latLng: L.LatLng): ILatLng { return latLng; } toLeafletLatLng(latLng: ILatLng, map: L.Map): L.LatLng { if(latLng instanceof L.LatLng) { return latLng; } else if(latLng) { return map ? map.wrapLatLng([ latLng.lat, latLng.lng ]) : new L.LatLng(latLng.lat, latLng.lng); } return null; } fromLeafletLatLngArray(latLngArray: L.LatLng[]): ILatLng[] { return latLngArray; } toLeafletLatLngArray(latLngArray: ILatLng[], map: L.Map): L.LatLng[] { latLngArray = latLngArray || []; var result = []; var len = latLngArray.length; for(var i = 0;i < len;++i) { result.push(this.toLeafletLatLng(latLngArray[i], map)); } return result; } fromLeafletLatLngBounds(bounds: L.LatLngBounds): IBounds { if(!bounds) { return null; } return { tlLat: bounds.getNorth(), tlLng: bounds.getWest(), brLat: bounds.getSouth(), brLng: bounds.getEast() }; } toLeaftletLatLngBounds(bounds: IBounds, map: L.Map): L.LatLngBounds { if(!bounds) { return null; } return map ? map.wrapLatLngBounds(new L.LatLngBounds([ bounds.brLat, bounds.tlLng ], [ bounds.tlLat, bounds.brLng ])) : new L.LatLngBounds([ bounds.brLat, bounds.tlLng ], [ bounds.tlLat, bounds.brLng ]); } fromLeafletIcon(icon: L.Icon|L.DivIcon): IMapIcon { // For now I'm just supporting Icon objects if(icon === null || icon === undefined) { return null; } return new MapIcon( icon.options.iconUrl, VRS.leafletUtilities.fromLeafletSize(icon.options.iconSize), VRS.leafletUtilities.fromLeafletPoint(icon.options.iconAnchor), null, null ); } toLeafletIcon(icon: string|IMapIcon): L.Icon { if(typeof icon === 'string') { return null; } return L.icon({ iconUrl: icon.url, iconSize: VRS.leafletUtilities.toLeafletSize(icon.size), iconAnchor: VRS.leafletUtilities.toLeafletPoint(icon.anchor) }); } fromLeafletContent(content: L.Content): string { if(content === null || content === undefined) { return null; } else { if(typeof content === "string") { return content; } return (<HTMLElement>content).innerText; } } fromLeafletSize(size: L.PointExpression): ISize { if(size === null || size === undefined) { return null; } if(size instanceof L.Point) { return { width: size.x, height: size.y }; } return { width: (<L.PointTuple>size)[0], height: (<L.PointTuple>size)[1] }; } toLeafletSize(size: ISize): L.Point { if(size === null || size === undefined) { return null; } return L.point(size.width, size.height); } fromLeafletPoint(point: L.PointExpression): IPoint { if(point === null || point === undefined) { return null; } if(point instanceof L.Point) { return point; } return { x: (<L.PointTuple>point)[0], y: (<L.PointTuple>point)[1] }; } toLeafletPoint(point: IPoint): L.Point { if(point === null || point === undefined) { return null; } if(point instanceof L.Point) { return point; } return L.point(point.x, point.y); } fromLeafletMapPosition(mapPosition: LeafletControlPosition): VRS.MapPositionEnum { switch(mapPosition || '') { case 'topleft': return VRS.MapPosition.TopLeft; case 'bottomleft': return VRS.MapPosition.BottomLeft; case 'bottomright': return VRS.MapPosition.BottomRight; default: return VRS.MapPosition.TopRight; } } toLeafletMapPosition(mapPosition: VRS.MapPositionEnum): LeafletControlPosition { switch(mapPosition || VRS.MapPosition.TopRight) { case VRS.MapPosition.BottomCentre: case VRS.MapPosition.BottomLeft: case VRS.MapPosition.LeftBottom: case VRS.MapPosition.LeftCentre: return 'bottomleft'; case VRS.MapPosition.BottomRight: case VRS.MapPosition.RightBottom: case VRS.MapPosition.RightCentre: return 'bottomright'; case VRS.MapPosition.LeftTop: case VRS.MapPosition.TopCentre: case VRS.MapPosition.TopLeft: return 'topleft'; default: return 'topright'; } } toLeafletMapMarker(mapMarker: IMapMarker) : L.Marker { var wrapper = <MapMarker>mapMarker; return wrapper ? wrapper.marker : null; } toLeafletMapMarkers(mapMarkers: IMapMarker[]) : L.Marker[] { var result : L.Marker[] = []; var len = mapMarkers ? mapMarkers.length : 0; for(var i = 0;i < len;++i) { result.push(this.toLeafletMapMarker(mapMarkers[i])); } return result; } } export var leafletUtilities = new LeafletUtilities(); /* * jQueryUIHelper */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; jQueryUIHelper.getMapPlugin = (jQueryElement: JQuery) : IMap => { return <IMap>jQueryElement.data('vrsVrsMap'); } jQueryUIHelper.getMapOptions = (overrides: IMapOptions) : IMapOptions => { return $.extend({ // Google Maps options, these are ignored key: null, // Unused version: '', // Unused sensor: false, // Unused libraries: [], // Unused loadMarkerWithLabel:false, // Unused loadMarkerCluster: false, // Unused // Map options openOnCreate: true, // Open the map when the widget is created, if false then the code that creates the map has to call open() itself. waitUntilReady: true, // If true then the widget does not call afterOpen until after the map has completely loaded. If this is false then calling getBounds (and perhaps other calls) may fail until the map has loaded. zoom: 12, // The zoom level to open with center: { lat: 51.5, lng: -0.125 }, // The location to centre the map on showMapTypeControl: true, // True to show the map type control, false to hide it. mapTypeId: VRS.MapType.Hybrid, // The map type to start with streetViewControl: VRS.globalOptions.mapShowStreetView, // Whether to show Street View or not scrollwheel: VRS.globalOptions.mapScrollWheelActive, // Whether the scrollwheel zooms the map scaleControl: VRS.globalOptions.mapShowScaleControl, // Whether to show the scale control or not. draggable: VRS.globalOptions.mapDraggable, // Whether the map is draggable controlStyle: VRS.MapControlStyle.Default, // The style of map control to display controlPosition: undefined, // Where the map control should be placed pointsOfInterest: VRS.globalOptions.mapShowPointsOfInterest, // Whether to show Google Maps' points of interest showHighContrast: VRS.globalOptions.mapShowHighContrastStyle, // Whether to show the custom high-contrast map style or not. // Custom map open options mapControls: [], // Controls to add to the map after it has been opened. // Callbacks afterCreate: null, // Called after the map has been created but before it has been opened afterOpen: null, // Called after the map has been opened // Persistence options name: 'default', // The name to use to distinguish the state settings from those of other maps useStateOnOpen: false, // Load and apply state when opening the map autoSaveState: false, // Automatically save state whenever any state variable is changed by the user useServerDefaults: false, // Always use the server-supplied configuration settings rather than those in options. __nop: null }, overrides); } /** * An abstracted wrapper around an object that represents a leaflet marker. */ class MapMarker implements IMapMarker { id: string|number; mapPlugin: MapPlugin; marker: L.Marker; map: L.Map; mapIcon: IMapIcon; zIndex: number; isMarkerWithLabel: boolean; tag: any; visible: boolean; labelTooltip: L.Tooltip; private _eventsHooked = false; /** * Creates a new object. * @param {string|number} id The identifier of the marker. * @param {MapPlugin} mapPlugin The map plugin that owns this marker. * @param {L.Map} nativeMap The map that this marker will be (or is) attached to. * @param {L.Marker} nativeMarker The native map marker handle to wrap. * @param {L.MarkerOptions} markerOptions The options used when creating the marker. * @param {IMapMarkerSettings} userOptions The options passed for the creation of the marker. */ constructor(id: string|number, mapPlugin: MapPlugin, map: L.Map, nativeMarker: L.Marker, markerOptions: L.MarkerOptions, userOptions: IMapMarkerSettings) { this.id = id; this.mapPlugin = mapPlugin; this.map = map; this.marker = nativeMarker; this.mapIcon = VRS.leafletUtilities.fromLeafletIcon(markerOptions.icon); this.zIndex = markerOptions.zIndexOffset; this.isMarkerWithLabel = !!userOptions.useMarkerWithLabel; this.tag = userOptions.tag; this.visible = !!userOptions.visible; if(this.isMarkerWithLabel) { this.labelTooltip = new L.Tooltip({ permanent: true, className: userOptions.mwlLabelClass, direction: 'bottom', pane: 'shadowPane' }); this.labelTooltip.setLatLng(this.marker.getLatLng()); } this.hookEvents(true); } destroy() { if(this.labelTooltip) { this.setLabelVisible(false); this.labelTooltip = null; } this.hookEvents(false); this.setVisible(false); this.mapPlugin = null; this.marker = null; this.map = null; this.tag = null; } hookEvents(hook: boolean) { if(this._eventsHooked !== hook) { this._eventsHooked = hook; if(hook) this.marker.on ('click', this._marker_clicked, this); else this.marker.off('click', this._marker_clicked, this); if(hook) this.marker.on ('dragend', this._marker_dragged, this); else this.marker.off('dragend', this._marker_dragged, this); } } private _marker_clicked(e: Event) { this.mapPlugin.raiseMarkerClicked(this.id); } private _marker_dragged(e: L.DragEndEvent) { this.mapPlugin.raiseMarkerDragged(this.id); } /** * Returns true if the marker can be dragged. */ getDraggable() : boolean { return this.marker.dragging.enabled(); } /** * Sets a value indicating whether the marker can be dragged. */ setDraggable(draggable: boolean) { if(draggable) { this.marker.dragging.enable(); } else { this.marker.dragging.disable(); } } /** * Returns the icon for the marker. */ getIcon() : IMapIcon { return this.mapIcon; } /** * Sets the icon for the marker. */ setIcon(icon: IMapIcon) { this.marker.setIcon(VRS.leafletUtilities.toLeafletIcon(icon)); this.mapIcon = icon; } /** * Gets the coordinates of the marker. */ getPosition() : ILatLng { return VRS.leafletUtilities.fromLeafletLatLng(this.marker.getLatLng()); } /** * Sets the coordinates for the marker. */ setPosition(position: ILatLng) { this.marker.setLatLng(VRS.leafletUtilities.toLeafletLatLng(position, this.map)); if(this.labelTooltip) { this.labelTooltip.setLatLng(this.marker.getLatLng()); } } /** * Gets the tooltip for the marker. */ getTooltip() : string { var icon = this.marker.getElement(); return icon ? icon.title : null; } /** * Sets the tooltip for the marker. */ setTooltip(text: string) { var icon = this.marker.getElement(); if(icon) { icon.title = text; } } /** * Gets a value indicating that the marker is visible. */ getVisible() : boolean { return this.visible; } /** * Sets a value indicating whether the marker is visible. */ setVisible(visible: boolean) { if(visible !== this.getVisible()) { if(visible) { this.marker.addTo(this.map); } else { this.marker.removeFrom(this.map); } this.visible = visible; } } /** * Gets the z-index of the marker. */ getZIndex() : number { return this.zIndex; } /** * Sets the z-index of the marker. */ setZIndex(zIndex: number) { this.marker.setZIndexOffset(zIndex); this.zIndex = zIndex; } /** * Returns true if the marker was created with useMarkerWithLabel and the label is visible. * Note that this is not a part of the marker interface. */ getLabelVisible() : boolean { return this.labelTooltip && this.labelTooltip.isOpen(); } /** * Sets the visibility of a marker's label. Only works on markers that have been created with useMarkerWithLabel. * Note that this is not a part of the marker interface. */ setLabelVisible(visible: boolean) { if(this.labelTooltip) { if(visible !== this.getLabelVisible()) { if(visible) { this.map.openTooltip(this.labelTooltip); } else { this.map.closeTooltip(this.labelTooltip); } } } } /** * Sets the label content. Only works on markers that have been created with useMarkerWithLabel. */ getLabelContent(): string { return this.labelTooltip ? <string>this.labelTooltip.getContent() : ''; } /** * Sets the content of a marker's label. Only works on markers that have been created with useMarkerWithLabel. * Note that this is not a part of the marker interface. */ setLabelContent(content: string) { if(this.labelTooltip) { this.labelTooltip.setContent(content); } } /** * Gets the label anchor. Only works on markers that have been created with useMarkerWithLabel. */ getLabelAnchor() { return null; } /** * Sets the anchor for a marker's label. Only works on markers that have been created with useMarkerWithLabel. * Note that this is not a part of the marker interface. */ setLabelAnchor(anchor: IPoint) { ; } } /** * An object that wraps a map's native polyline object. */ class MapPolyline implements IMapPolyline { id: string | number; map: L.Map; polyline: L.Polyline; tag: any; visible: boolean; constructor(id: string | number, map: L.Map, nativePolyline: L.Polyline, tag: any, options: IMapPolylineSettings) { this.id = id; this.map = map; this.polyline = nativePolyline; this.tag = tag; this.visible = options.visible; this._StrokeColour = options.strokeColour; this._StrokeOpacity = options.strokeOpacity; this._StrokeWeight = options.strokeWeight; } destroy() { this.setVisible(false); this.polyline = null; this.map = null; this.tag = null; } getDraggable() : boolean { return false; } setDraggable(draggable: boolean) { ; } getEditable() : boolean { return false; } setEditable(editable: boolean) { ; } getVisible() : boolean { return this.visible; } setVisible(visible: boolean) { if(this.visible !== visible) { if(visible) { this.polyline.addTo(this.map); } else { this.polyline.removeFrom(this.map); } this.visible = visible; } } private _StrokeColour: string; getStrokeColour() : string { return this._StrokeColour; } setStrokeColour(value: string) { if(value !== this._StrokeColour) { this._StrokeColour = value; this.polyline.setStyle({ color: value }); } } private _StrokeOpacity: number; getStrokeOpacity() : number { return this._StrokeOpacity; } setStrokeOpacity(value: number) { if(value !== this._StrokeOpacity) { this._StrokeOpacity = value; this.polyline.setStyle({ opacity: value }); } } private _StrokeWeight: number; getStrokeWeight() : number { return this._StrokeWeight; } setStrokeWeight(value: number) { if(value !== this._StrokeWeight) { this._StrokeWeight = value; this.polyline.setStyle({ weight: value }); } } getPath() : ILatLng[] { return VRS.leafletUtilities.fromLeafletLatLngArray(<L.LatLng[]>(this.polyline.getLatLngs())); } setPath(path: ILatLng[]) { this.polyline.setLatLngs(VRS.leafletUtilities.toLeafletLatLngArray(path, this.map)); } getFirstLatLng() : ILatLng { var result = null; var nativePath = <L.LatLng[]>this.polyline.getLatLngs(); if(nativePath.length) result = VRS.leafletUtilities.fromLeafletLatLng(nativePath[0]); return result; } getLastLatLng() : ILatLng { var result = null; var nativePath = <L.LatLng[]>this.polyline.getLatLngs(); if(nativePath.length) result = VRS.leafletUtilities.fromLeafletLatLng(nativePath[nativePath.length - 1]); return result; } } /** * An object that wraps a map's native circle object. * @constructor */ class MapCircle implements IMapCircle { id: string | number; circle: L.Circle; map: L.Map; tag: any; visible: boolean; /** * Creates a new object. * @param {string|number} id The unique identifier of the circle object. * @param {L.Map} map The map to add the circle to or remove the circle from. * @param {L.Circle} nativeCircle The native object that is being wrapped. * @param {*} tag An object attached to the circle. * @param {IMapCircleSettings} options The options used when the circle was created. */ constructor(id: string | number, map: L.Map, nativeCircle: L.Circle, tag: any, options: IMapCircleSettings) { this.id = id; this.circle = nativeCircle; this.map = map; this.tag = tag; this.visible = options.visible; this._FillOpacity = options.fillOpacity; this._FillColour = options.fillColor; this._StrokeOpacity = options.strokeOpacity; this._StrokeColour = options.strokeColor; this._StrokeWeight = options.strokeWeight; this._ZIndex = options.zIndex; } destroy() { this.setVisible(false); this.circle = null; this.map = null; this.tag = null; } getBounds() : IBounds { return VRS.leafletUtilities.fromLeafletLatLngBounds(this.circle.getBounds()); } getCenter() : ILatLng { return VRS.leafletUtilities.fromLeafletLatLng(this.circle.getLatLng()); } setCenter(value: ILatLng) { this.circle.setLatLng(VRS.leafletUtilities.toLeafletLatLng(value, this.map)); } getDraggable() : boolean { return false; } setDraggable(value: boolean) { ; } getEditable() : boolean { return false; } setEditable(value: boolean) { ; } getRadius() : number { return this.circle.getRadius(); } setRadius(value: number) { this.circle.setRadius(value); } getVisible() : boolean { return this.visible; } setVisible(visible: boolean) { if(this.visible !== visible) { if(visible) { this.circle.addTo(this.map); } else { this.circle.removeFrom(this.map); } this.visible = visible; } } private _FillColour: string; getFillColor() : string { return this._FillColour; } setFillColor(value: string) { if(this._FillColour !== value) { this._FillColour = value; this.circle.setStyle({ fillColor: value }); } } private _FillOpacity: number; getFillOpacity() : number { return this._FillOpacity; } setFillOpacity(value: number) { if(this._FillOpacity !== value) { this._FillOpacity = value; this.circle.setStyle({ fillOpacity: value }); } } private _StrokeColour: string; getStrokeColor() : string { return this._StrokeColour; } setStrokeColor(value: string) { if(this._StrokeColour !== value) { this._StrokeColour = value; this.circle.setStyle({ color: value }); } } private _StrokeOpacity: number; getStrokeOpacity() : number { return this._StrokeOpacity; } setStrokeOpacity(value: number) { if(this._StrokeOpacity !== value) { this._StrokeOpacity = value; this.circle.setStyle({ opacity: value }); } } private _StrokeWeight: number; getStrokeWeight() : number { return this._StrokeWeight; } setStrokeWeight(value: number) { if(this._StrokeWeight !== value) { this._StrokeWeight = value; this.circle.setStyle({ weight: value }); } } private _ZIndex: number; getZIndex() : number { return this._ZIndex; } setZIndex(value: number) { this._ZIndex = value; } } class MapControl extends L.Control { constructor(readonly element: JQuery | HTMLElement, options: L.ControlOptions) { super(options); } onAdd(map: L.Map): HTMLElement { var result = $('<div class="leaflet-control"></div>'); result.append(this.element); return result[0]; } } /** * Describes a polygon on a map. */ class MapPolygon implements IMapPolygon { id: string | number; map: L.Map; polygon: L.Polygon; tag: any; visible: boolean; constructor(id: string | number, nativeMap: L.Map, nativePolygon: L.Polygon, tag: any, options: IMapPolygonSettings) { this.id = id; this.map = nativeMap; this.polygon = nativePolygon; this.tag = tag; this.visible = options.visible; this._FillColour = options.fillColour; this._FillOpacity = options.fillOpacity; this._StrokeColour = options.strokeColour; this._StrokeOpacity = options.strokeOpacity; this._StrokeWeight = options.strokeWeight; this._ZIndex = options.zIndex; } destroy() { this.setVisible(false); this.map = null; this.polygon = null; this.tag = null; } getDraggable() : boolean { return false; } setDraggable(draggable: boolean) { ; } getEditable() : boolean { return false; } setEditable(editable: boolean) { ; } getVisible() : boolean { return this.visible; } setVisible(visible: boolean) { if(visible != this.visible) { if(visible) { this.polygon.addTo(this.map); } else { this.polygon.removeFrom(this.map); } this.visible = visible; } } getFirstPath() : ILatLng[] { return VRS.leafletUtilities.fromLeafletLatLngArray(<L.LatLng[]>this.polygon.getLatLngs()); } setFirstPath(path: ILatLng[]) { this.polygon.setLatLngs(path); } getPaths() : ILatLng[][] { // For now I'm just supporting single path polygons return <ILatLng[][]> [ this.getFirstPath() ]; } setPaths(paths: ILatLng[][]) { // For now I'm just supporting single path polygons this.setFirstPath(paths[0]); } getClickable() : boolean { return this.polygon.options.interactive; } setClickable(value: boolean) { if(value !== this.getClickable()) { this.polygon.options.interactive = value; } } private _FillColour: string; getFillColour() : string { return this._FillColour; } setFillColour(value: string) { if(value !== this._FillColour) { this._FillColour = value; this.polygon.setStyle({ fillColor: value }); } } private _FillOpacity: number; getFillOpacity() : number { return this._FillOpacity; } setFillOpacity(value: number) { if(value !== this._FillOpacity) { this._FillOpacity = value; this.polygon.setStyle({ fillOpacity: value }); } } private _StrokeColour: string; getStrokeColour() : string { return this._StrokeColour; } setStrokeColour(value: string) { if(value !== this._StrokeColour) { this._StrokeColour = value; this.polygon.setStyle({ color: value }); } } private _StrokeOpacity: number; getStrokeOpacity() : number { return this._StrokeOpacity; } setStrokeOpacity(value: number) { if(value !== this._StrokeOpacity) { this._StrokeOpacity = value; this.polygon.setStyle({ opacity: value }); } } private _StrokeWeight: number; getStrokeWeight() : number { return this._StrokeWeight; } setStrokeWeight(value: number) { if(value !== this._StrokeWeight) { this._StrokeWeight = value; this.polygon.setStyle({ weight: value }); } } private _ZIndex: number; getZIndex() : number { return this._ZIndex; } setZIndex(value: number) { if(value !== this._ZIndex) { this._ZIndex = value; } } } /** * A wrapper around a map's native info window. */ class MapInfoWindow implements IMapInfoWindow { id: string | number; map: L.Map; infoWindow: L.Popup; tag: any; isOpen: boolean; boundMarker: MapMarker; /** * Creates a new object. * @param {string|number} id The unique identifier of the info window * @param {L.Popup} nativeInfoWindow The map's native info window object that this wraps. * @param {*} tag An abstract object that is associated with the info window. * @param {IMapInfoWindowSettings} options The options used to create the info window. */ constructor(id: string | number, nativeMap: L.Map, nativeInfoWindow: L.Popup, tag: any, options: IMapInfoWindowSettings) { this.id = id; this.map = nativeMap; this.infoWindow = nativeInfoWindow; this.tag = tag; this.isOpen = false; this._DisableAutoPan = options.disableAutoPan; this._MaxWidth = options.maxWidth; this._PixelOffset = options.pixelOffset; } destroy() { this.infoWindow.setContent(''); this.map = null; this.tag = null; this.infoWindow = null; } getContent() : Element { return <Element>this.infoWindow.getContent(); } setContent(value: Element) { this.infoWindow.setContent(<any>value); } private _DisableAutoPan: boolean; getDisableAutoPan() : boolean { return this._DisableAutoPan; } setDisableAutoPan(value: boolean) { if(this._DisableAutoPan !== value) { this._DisableAutoPan = value; this.infoWindow.options.autoPan = !value; } } private _MaxWidth: number; getMaxWidth() : number { return this._MaxWidth; } setMaxWidth(value: number) { if(this._MaxWidth !== value) { this._MaxWidth = value; this.infoWindow.options.maxWidth = value; } } private _PixelOffset: ISize; getPixelOffset() : ISize { return this._PixelOffset; } setPixelOffset(value: ISize) { if(this._PixelOffset !== value) { this._PixelOffset = value; this.infoWindow.options.offset = VRS.leafletUtilities.toLeafletSize(value); } } getPosition() : ILatLng { return VRS.leafletUtilities.fromLeafletLatLng(this.infoWindow.getLatLng()); } setPosition(value: ILatLng) { this.infoWindow.setLatLng(VRS.leafletUtilities.toLeafletLatLng(value, this.map)); } getZIndex() : number { return 1; } setZIndex(value: number) { ; } open(mapMarker: MapMarker) { this.close(); if(!this.isOpen) { this.isOpen = true; if(!mapMarker) { this.map.openPopup(this.infoWindow); } else { this.boundMarker = mapMarker; var markerHeight = mapMarker.getIcon().size.height; this.setPixelOffset({ width: 0, height: -markerHeight }); mapMarker.marker.bindPopup(this.infoWindow).openPopup(); } } } close() { if(this.isOpen) { this.isOpen = false; if(!this.boundMarker) { this.map.closePopup(this.infoWindow); } else { if(this.boundMarker.marker) { this.boundMarker.marker.closePopup(); this.boundMarker.marker.unbindPopup(); } this.boundMarker = null; } } } } /** * A wrapper around the leaflet marker cluster plugin */ class MapMarkerClusterer implements IMapMarkerClusterer { map: L.Map; clusterGroup: L.MarkerClusterGroup; maxZoom: number; constructor(nativeMap: L.Map, settings: IMapMarkerClustererSettings) { this.map = nativeMap; this.maxZoom = settings.maxZoom; this.createClusterGroup(); } private createClusterGroup() { var mapMarkers : L.Layer[] = null; if(this.clusterGroup) { mapMarkers = this.clusterGroup.getLayers(); this.destroyClusterGroup(); } var options : L.MarkerClusterGroupOptions = { disableClusteringAtZoom: this.maxZoom + 1, spiderfyOnMaxZoom: false, showCoverageOnHover: true }; this.clusterGroup = L.markerClusterGroup(options); if(mapMarkers && mapMarkers.length > 0) { this.clusterGroup.addLayers(mapMarkers); } this.map.addLayer(this.clusterGroup); } private destroyClusterGroup() { if(this.clusterGroup) { this.clusterGroup.removeLayers(this.clusterGroup.getLayers()); this.map.removeLayer(this.clusterGroup); this.clusterGroup = null; } } getNative() : any { return this.clusterGroup; } getNativeType() { return 'OpenStreetMap'; } getMaxZoom() : number { return this.maxZoom; } setMaxZoom(maxZoom: number) { if(maxZoom !== this.maxZoom) { this.maxZoom = maxZoom; this.createClusterGroup(); } } addMarker(marker: IMapMarker, noRepaint?: boolean) { if(marker) { var nativeMarker = VRS.leafletUtilities.toLeafletMapMarker(marker); nativeMarker.remove(); this.clusterGroup.addLayer(nativeMarker); } } addMarkers(markers: IMapMarker[], noRepaint?: boolean) { if(markers) { var nativeMarkers = VRS.leafletUtilities.toLeafletMapMarkers(markers); var len = nativeMarkers.length; for(var i = 0;i < len;++i) { nativeMarkers[i].remove(); } this.clusterGroup.addLayers(nativeMarkers); } } removeMarker(marker: IMapMarker, noRepaint?: boolean) { if(marker) { this.clusterGroup.removeLayer(VRS.leafletUtilities.toLeafletMapMarker(marker)); } } removeMarkers(markers: IMapMarker[], noRepaint?: boolean) { if(markers) { this.clusterGroup.removeLayers(VRS.leafletUtilities.toLeafletMapMarkers(markers)); } } repaint() { this.clusterGroup.refreshClusters(); } } /** * The state held for a layer. */ class MapLayer { map: L.Map; layer: L.TileLayer; constructor(nativeMap: L.Map, nativeLayer: L.TileLayer) { this.map = nativeMap; this.layer = nativeLayer; } destroy() { this.map = null; this.layer = null; } getOpacity() : number { return this.layer.options.opacity; } setOpacity(value: number) { this.layer.setOpacity(value); } } /** * The state held for every map plugin object. */ class MapPluginState { /** * The map's container. */ mapContainer: JQuery = undefined; /** * The leaflet map. */ map: L.Map = undefined; /** * The name of the current map's tile server settings. */ mapName: string = undefined; /** * The map tile layer. */ tileLayer: L.TileLayer = undefined; /** * An associative array of marker IDs to markers. */ markers: { [markerId: string]: MapMarker } = {}; /** * An associative array of polyline IDs to polylines. */ polylines: { [polylineId: string]: MapPolyline } = {}; /** * An associative array of circle IDs to circles. */ circles: { [circleId: string]: MapCircle } = {}; /** * An associative array of polygon IDs to polygons. */ polygons: { [polygonId: string]: MapPolygon } = {}; /** * An associative array of info window IDs to info windows. */ infoWindows: { [infoWindowId: string]: MapInfoWindow } = {}; /** * An associative array of layer names to open layer objects. */ layers: { [layerName: string]: MapLayer } = {}; /** * True if the map's events have been hooked. */ eventsHooked = false; /** * The map centre that we're setting. Used to prevent recursive map events * while moving the map. */ settingCenter: ILatLng = undefined; /** * The default brightness specified by the tile server settings. */ defaultBrightness: number = undefined; /** * The map brightness where 100 = normal brightness and 150 is 50% extra bright. */ brightness = 100; } /** * A jQuery plugin that wraps Leaflet maps. */ class MapPlugin extends JQueryUICustomWidget implements IMap { options: IMapOptions; private _EventPluginName = 'vrsMap'; constructor() { super(); this.options = VRS.jQueryUIHelper.getMapOptions(); } private _getState() : MapPluginState { var result = this.element.data('mapPluginState'); if(result === undefined) { result = new MapPluginState(); this.element.data('mapPluginState', result); } return result; } _create() { if(this.options.useServerDefaults && VRS.serverConfig) { var config = VRS.serverConfig.get(); if(config) { this.options.center = { lat: config.InitialLatitude, lng: config.InitialLongitude }; this.options.mapTypeId = config.InitialMapType; this.options.zoom = config.InitialZoom; } } var state = this._getState(); state.mapContainer = $('<div />') .addClass('vrsMap') .appendTo(this.element); if(VRS.refreshManager) { VRS.refreshManager.registerTarget(this.element, this._targetResized, this); } if(this.options.afterCreate) { this.options.afterCreate(this); } if(this.options.openOnCreate) { this.open(); } } _destroy() { var state = this._getState(); this._hookEvents(state, false); if(VRS.refreshManager) VRS.refreshManager.unregisterTarget(this.element); if(state.mapContainer) state.mapContainer.remove(); } _hookEvents(state: MapPluginState, hook: boolean) { if(state.map) { if((hook && !state.eventsHooked) || (!hook && state.eventsHooked)) { state.eventsHooked = hook; if(hook) state.map.on ('resize', this._map_resized, this); else state.map.off('resize', this._map_resized, this); if(hook) state.map.on ('move', this._map_moved, this); else state.map.off('move', this._map_moved, this); if(hook) state.map.on ('moveend', this._map_moveEnded, this); else state.map.off('moveend', this._map_moveEnded, this); if(hook) state.map.on ('click', this._map_clicked, this); else state.map.off('click', this._map_clicked, this); if(hook) state.map.on ('dblclick', this._map_doubleClicked, this); else state.map.off('dblclick', this._map_doubleClicked, this); if(hook) state.map.on ('zoomend', this._map_zoomEnded, this); else state.map.off('zoomend', this._map_zoomEnded, this); if(hook) state.tileLayer.on ('load', this._tileLayer_loaded, this); else state.tileLayer.off('load', this._tileLayer_loaded, this); } } } _map_resized(e: L.ResizeEvent) { this._raiseBoundsChanged(); } _map_moved(e: Event) { this._raiseCenterChanged(); } _map_moveEnded(e: Event) { this._onIdle(); } _map_clicked(e: MouseEvent) { this._userNotIdle(); this._raiseClicked(e); } _map_doubleClicked(e: MouseEvent) { this._userNotIdle(); this._raiseDoubleClicked(e); } _map_zoomEnded(e: Event) { this._raiseZoomChanged(); this._onIdle(); } _tileLayer_loaded(e:Event) { this._raiseTilesLoaded(); } getNative(): any { return this._getState().map; } getNativeType() : string { return 'OpenStreetMap'; } isOpen() : boolean { return !!this._getState().map; } isReady() : boolean { var state = this._getState(); return !!state.map; } getBounds() : IBounds { return this._getBounds(this._getState()); } private _getBounds(state: MapPluginState) { return state.map ? VRS.leafletUtilities.fromLeafletLatLngBounds(state.map.getBounds()) : { tlLat: 0, tlLng: 0, brLat: 0, brLng: 0}; } getCenter() : ILatLng { return this._getCenter(this._getState()); } private _getCenter(state: MapPluginState) { return state.map ? VRS.leafletUtilities.fromLeafletLatLng(state.map.getCenter()) : this.options.center; } setCenter(latLng: ILatLng) { this._setCenter(this._getState(), latLng); } private _setCenter(state: MapPluginState, latLng: ILatLng) { if(state.settingCenter === undefined || state.settingCenter === null || state.settingCenter.lat != latLng.lat || state.settingCenter.lng != latLng.lng) { try { state.settingCenter = latLng; if(state.map) state.map.panTo(VRS.leafletUtilities.toLeafletLatLng(latLng, state.map)); else this.options.center = latLng; } finally { state.settingCenter = undefined; } } } getDraggable() : boolean { return this.options.draggable; } getMapType() : MapTypeEnum { return this._getMapType(this._getState()); } private _getMapType(state: MapPluginState) : MapTypeEnum { return this.options.mapTypeId; } setMapType(mapType: MapTypeEnum) { this._setMapType(this._getState(), mapType); } private _setMapType(state: MapPluginState, mapType: MapTypeEnum) { this.options.mapTypeId = mapType; } getScrollWheel() : boolean { return this.options.scrollwheel; } getStreetView() : boolean { return this.options.streetViewControl; } getZoom() : number { return this._getZoom(this._getState()); } private _getZoom(state: MapPluginState) : number { return state.map ? state.map.getZoom() : this.options.zoom; } setZoom(zoom: number) { this._setZoom(this._getState(), zoom); } private _setZoom(state: MapPluginState, zoom: number) { if(state.map) state.map.setZoom(zoom); else this.options.zoom = zoom; } unhook(hookResult: IEventHandleJQueryUI) { VRS.globalDispatch.unhookJQueryUIPluginEvent(this.element, hookResult); } hookBoundsChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'boundsChanged', callback, forceThis); } private _raiseBoundsChanged() { this._trigger('boundsChanged'); } hookBrightnessChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'brightnessChanged', callback, forceThis); } private _raiseBrightnessChanged() { this._trigger('brightnessChanged'); } hookCenterChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'centerChanged', callback, forceThis); } private _raiseCenterChanged() { this._trigger('centerChanged'); } hookClicked(callback: (event?: Event, data?: IMapMouseEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'clicked', callback, forceThis); } private _raiseClicked(mouseEvent: Event) { this._trigger('clicked', null, <IMapMouseEventArgs>{ mouseEvent: mouseEvent }); } hookDoubleClicked(callback: (event?: Event, data?: IMapMouseEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'doubleClicked', callback, forceThis); } private _raiseDoubleClicked(mouseEvent: Event) { this._trigger('doubleClicked', null, <IMapMouseEventArgs>{ mouseEvent: mouseEvent }); } hookIdle(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'idle', callback, forceThis); } private _raiseIdle() { this._trigger('idle'); } hookMapTypeChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'mapTypeChanged', callback, forceThis); } private _raiseMapTypeChanged() { this._trigger('mapTypeChanged'); } hookRightClicked(callback: (event?: Event, data?: IMapMouseEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'mouseEvent', callback, forceThis); } private _raiseRightClicked(mouseEvent: Event) { this._trigger('mouseEvent', null, <IMapMouseEventArgs>{ mouseEvent: mouseEvent }); } hookTilesLoaded(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'tilesLoaded', callback, forceThis); } private _raiseTilesLoaded() { this._trigger('tilesLoaded'); } hookZoomChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'zoomChanged', callback, forceThis); } private _raiseZoomChanged() { this._trigger('zoomChanged'); } hookMarkerClicked(callback: (event?: Event, data?: IMapMarkerEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'markerClicked', callback, forceThis); } raiseMarkerClicked(id: string | number) { this._trigger('markerClicked', null, <IMapMarkerEventArgs>{ id: id }); } hookMarkerDragged(callback: (event?: Event, data?: IMapMarkerEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'markerDragged', callback, forceThis); } raiseMarkerDragged(id: string | number) { this._trigger('markerDragged', null, <IMapMarkerEventArgs>{ id: id }); } hookInfoWindowClosedByUser(callback: (event?: Event, data?: IMapInfoWindowEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, 'vrsMap', 'infoWindowClosedByUser', callback, forceThis); } private _raiseInfoWindowClosedByUser(id: string | number) { this._trigger('infoWindowClosedByUser', null, <IMapInfoWindowEventArgs>{ id: id }); } /** * Called when the map becomes idle. */ private _onIdle() { if(this.options.autoSaveState) this.saveState(); this._raiseIdle(); } /** * Called after the map type has changed. */ private _onMapTypeChanged() { if(this.options.autoSaveState) this.saveState(); this._raiseMapTypeChanged(); } open(userOptions?: IMapOpenOptions) { var tileServerSettings = VRS.serverConfig.get().TileServerSettings; if(tileServerSettings) { var mapOptions: IMapOptions = $.extend(<IMapOptions>{}, userOptions, { zoom: this.options.zoom, center: this.options.center, mapTypeControl: this.options.showMapTypeControl, mapTypeId: this.options.mapTypeId, streetViewControl: this.options.streetViewControl, scrollwheel: this.options.scrollwheel, scaleControl: this.options.scaleControl, draggable: this.options.draggable, showHighContrast: this.options.showHighContrast, controlStyle: this.options.controlStyle, controlPosition: this.options.controlPosition, mapControls: this.options.mapControls }); var overrideBrightness = tileServerSettings.DefaultBrightness; if(this.options.useStateOnOpen) { var settings = this.loadState(); mapOptions.zoom = settings.zoom; mapOptions.center = settings.center; mapOptions.mapTypeId = settings.mapTypeId; if(tileServerSettings.Name === settings.brightnessMapName && settings.brightness) { overrideBrightness = settings.brightness; } } mapOptions.zoom = this._normaliseZoom(mapOptions.zoom, tileServerSettings.MinZoom, tileServerSettings.MaxZoom); var leafletOptions: L.MapOptions = { attributionControl: true, zoom: mapOptions.zoom, center: VRS.leafletUtilities.toLeafletLatLng(mapOptions.center, null), scrollWheelZoom: mapOptions.scrollwheel, dragging: mapOptions.draggable, zoomControl: mapOptions.scaleControl }; var state = this._getState(); state.map = L.map(state.mapContainer[0], leafletOptions); state.mapName = tileServerSettings.Name; state.defaultBrightness = tileServerSettings.DefaultBrightness; var tileServerOptions = this._buildTileServerOptions(state, tileServerSettings, overrideBrightness); state.tileLayer = L.tileLayer(tileServerSettings.Url, tileServerOptions); state.tileLayer.addTo(state.map); this._hookEvents(state, true); if(mapOptions.mapControls) { $.each(mapOptions.mapControls, (idx, ctrl) => { this.addControl(ctrl.control, ctrl.position); }); } var waitUntilReady = () => { if(this.options.waitUntilReady && !this.isReady()) { setTimeout(waitUntilReady, 100); } else { if(this.options.afterOpen) this.options.afterOpen(this); } }; waitUntilReady(); } } private _buildTileServerOptions(state: MapPluginState, settings: ITileServerSettings, overrideBrightness: number) : L.TileLayerOptions { var result: L.TileLayerOptions = { attribution: this._attributionToHtml(settings.Attribution), detectRetina: settings.DetectRetina, zoomReverse: settings.ZoomReverse, }; if(VRS.globalOptions.mapLeafletNoWrap) { result.noWrap = true; } if(settings.ClassName) { result.className = settings.ClassName; } if(!settings.IsLayer) { var brightness = overrideBrightness && !isNaN(overrideBrightness) ? overrideBrightness : settings.DefaultBrightness; result.className = this._setBrightnessClass(result.className, state.brightness, brightness); state.brightness = brightness; } else { if(settings.DefaultOpacity > 0 && settings.DefaultOpacity < 100) { result.opacity = settings.DefaultOpacity / 100; } } if(settings.MaxNativeZoom !== null && settings.MaxNativeZoom !== undefined) { result.maxNativeZoom = settings.MaxNativeZoom; } if(settings.MinNativeZoom !== null && settings.MinNativeZoom !== undefined) { result.minNativeZoom = settings.MinNativeZoom; } if(settings.MaxZoom !== null && settings.MaxZoom !== undefined) { result.maxZoom = settings.MaxZoom; } if(settings.MinZoom !== null && settings.MinZoom !== undefined) { result.minZoom = settings.MinZoom; } if(settings.Subdomains !== null && settings.Subdomains !== undefined) { result.subdomains = settings.Subdomains; } if(settings.ZoomOffset !== null && settings.ZoomOffset !== undefined) { result.zoomOffset = settings.ZoomOffset; } if(settings.IsTms) { result.tms = true; } if(settings.ErrorTileUrl != null) { result.errorTileUrl = settings.ErrorTileUrl; } var countExpandos = settings.ExpandoOptions === null || settings.ExpandoOptions === undefined ? 0 : settings.ExpandoOptions.length; for(var i = 0;i < countExpandos;++i) { var expando = settings.ExpandoOptions[i]; result[expando.Option] = VRS.stringUtility.htmlEscape(expando.Value); } return result; } private _attributionToHtml(attribution: string) : string { var result = VRS.stringUtility.htmlEscape(attribution); result = result.replace(/\[c\]/g, '&copy;'); result = result.replace(/\[\/a\]/g, '</a>'); result = result.replace(/\[a href=(.+?)\]/g, '<a href="$1">'); return result; } private _normaliseZoom(zoom: number, minZoom: number, maxZoom: number) : number { var result = zoom; if(result !== undefined && result !== null) { if(minZoom !== undefined && minZoom !== null && result < minZoom) { result = minZoom; } if(maxZoom !== undefined && maxZoom !== null && result > maxZoom) { result = maxZoom; } } return result; } private _userNotIdle() { if(VRS.timeoutManager) VRS.timeoutManager.resetTimer(); } refreshMap() { var state = this._getState(); if(state.map) { state.map.invalidateSize(); } } panTo(mapCenter: ILatLng) { this._panTo(mapCenter, this._getState()); } private _panTo(mapCenter: ILatLng, state: MapPluginState) { if(state.settingCenter === undefined || state.settingCenter === null || state.settingCenter.lat != mapCenter.lat || state.settingCenter.lng != mapCenter.lng) { try { state.settingCenter = mapCenter; if(state.map) state.map.panTo(VRS.leafletUtilities.toLeafletLatLng(mapCenter, state.map)); else this.options.center = mapCenter; } finally { state.settingCenter = undefined; } } } fitBounds(bounds: IBounds) { var state = this._getState(); if(state.map) { state.map.fitBounds(VRS.leafletUtilities.toLeaftletLatLngBounds(bounds, state.map)); } } saveState() { var settings = this._createSettings(); VRS.configStorage.save(this._persistenceKey(), settings); } loadState() : IMapSaveState { var savedSettings = VRS.configStorage.load(this._persistenceKey(), {}); return $.extend(this._createSettings(), savedSettings); } applyState(config: IMapSaveState) { config = config || <IMapSaveState>{}; var state = this._getState(); if(config.center) this._setCenter(state, config.center); if(config.zoom || config.zoom === 0) this._setZoom(state, config.zoom); if(config.mapTypeId) this._setMapType(state, config.mapTypeId); if(state.mapName === config.brightnessMapName) { this.setMapBrightness(config.brightness); } }; loadAndApplyState() { this.applyState(this.loadState()); } private _persistenceKey() : string { return 'vrsMapState-' + (this.options.name || 'default'); } private _createSettings() : IMapSaveState { var state = this._getState(); return { zoom: this._getZoom(state), mapTypeId: this._getMapType(state), center: this._getCenter(state), brightnessMapName: state.mapName, brightness: state.brightness === state.defaultBrightness ? 0 : state.brightness }; } addMarker(id: string | number, userOptions: IMapMarkerSettings): IMapMarker { var result: MapMarker; var state = this._getState(); if(state.map) { if(userOptions.zIndex === null || userOptions.zIndex === undefined) { userOptions.zIndex = 0; } if(userOptions.draggable) { userOptions.clickable = true; } var leafletOptions: L.MarkerOptions = { interactive: userOptions.clickable !== undefined ? userOptions.clickable : true, draggable: userOptions.draggable !== undefined ? userOptions.draggable : false, zIndexOffset: userOptions.zIndex, }; if(userOptions.icon) { leafletOptions.icon = VRS.leafletUtilities.toLeafletIcon(userOptions.icon); } if(userOptions.tooltip) { leafletOptions.title = userOptions.tooltip; } var position = userOptions.position ? VRS.leafletUtilities.toLeafletLatLng(userOptions.position, state.map) : state.map.getCenter(); this.destroyMarker(id); var nativeMarker = L.marker(position, leafletOptions); if(userOptions.visible) { nativeMarker.addTo(state.map); } result = new MapMarker(id, this, state.map, nativeMarker, leafletOptions, userOptions); state.markers[id] = result; } return result; } getMarker(idOrMarker: string | number | IMapMarker): IMapMarker { if(idOrMarker instanceof MapMarker) return idOrMarker; var state = this._getState(); return state.markers[<string | number>idOrMarker]; } destroyMarker(idOrMarker: string | number | IMapMarker) { var state = this._getState(); var marker = <MapMarker>this.getMarker(idOrMarker); if(marker) { marker.destroy(); delete state.markers[marker.id]; marker.id = null; } } centerOnMarker(idOrMarker: string | number | IMapMarker) { var state = this._getState(); var marker = <MapMarker>this.getMarker(idOrMarker); if(marker) { this.setCenter(marker.getPosition()); } } createMapMarkerClusterer(settings?: IMapMarkerClustererSettings): IMapMarkerClusterer { var result: MapMarkerClusterer = null; var state = this._getState(); if(state.map) { var options = $.extend(<IMapMarkerClustererSettings>{}, settings, { }); // The clusterer as implemented does work but it has two problems: // 1. The info window flickers when markers are moved. I think it may be related to this issue here: // https://github.com/Leaflet/Leaflet.markercluster/issues/774 [Using marker.setLatLng triggers paint flashing] // 2. It will not cluster single aircraft without permanently modifying their icon. // // Unfortunately (1) is a show-stopper, it looks awful. I don't think leaflet.markercluster is going to work for // VRS until the issue is resolved. I've left the code in place but commented out the create call, if you want to // put the clusterer back then just uncomment this line: // result = new MapMarkerClusterer(state.map, options); } return result; } addPolyline(id: string | number, userOptions: IMapPolylineSettings): IMapPolyline { var result: MapPolyline; var state = this._getState(); if(state.map) { var options = $.extend(<IMapPolylineSettings>{}, userOptions, { visible: true }); var leafletOptions: L.PolylineOptions = { color: options.strokeColour || '#000000' }; if(options.strokeOpacity || leafletOptions.opacity === 0) leafletOptions.opacity = options.strokeOpacity; if(options.strokeWeight || leafletOptions.weight === 0) leafletOptions.weight = options.strokeWeight; var path: L.LatLng[] = []; if(options.path) path = VRS.leafletUtilities.toLeafletLatLngArray(options.path, state.map); this.destroyPolyline(id); var polyline = L.polyline(path, leafletOptions); if(options.visible) { polyline.addTo(state.map); } result = new MapPolyline(id, state.map, polyline, options.tag, { strokeColour: options.strokeColour, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); state.polylines[id] = result; } return result; } getPolyline(idOrPolyline: string | number | IMapPolyline): IMapPolyline { if(idOrPolyline instanceof MapPolyline) return idOrPolyline; var state = this._getState(); return state.polylines[<string | number>idOrPolyline]; } destroyPolyline(idOrPolyline: string | number | IMapPolyline) { var state = this._getState(); var polyline = <MapPolyline>this.getPolyline(idOrPolyline); if(polyline) { polyline.destroy(); delete state.polylines[polyline.id]; polyline.id = null; } } trimPolyline(idOrPolyline: string | number | IMapPolyline, countPoints: number, fromStart: boolean): IMapTrimPolylineResult { var emptied = false; var countRemoved = 0; if(countPoints > 0) { var polyline = <MapPolyline>this.getPolyline(idOrPolyline); var points = <L.LatLng[]>polyline.polyline.getLatLngs(); var length = points.length; if(length < countPoints) countPoints = length; if(countPoints > 0) { countRemoved = countPoints; emptied = countPoints === length; if(emptied) { points = []; } else { if(fromStart) { points.splice(0, countPoints); } else { points.splice(length - countPoints, countPoints); } } polyline.polyline.setLatLngs(points); } } return { emptied: emptied, countRemoved: countRemoved }; } removePolylinePointAt(idOrPolyline: string | number | IMapPolyline, index: number) { var polyline = <MapPolyline>this.getPolyline(idOrPolyline); var points = <L.LatLng[]>polyline.polyline.getLatLngs(); points.splice(index, 1); polyline.polyline.setLatLngs(points); } appendToPolyline(idOrPolyline: string | number | IMapPolyline, path: ILatLng[], toStart: boolean) { var length = !path ? 0 : path.length; if(length > 0) { var state = this._getState(); var polyline = <MapPolyline>this.getPolyline(idOrPolyline); var points = <L.LatLng[]>polyline.polyline.getLatLngs(); var insertAt = toStart ? 0 : -1; for(var i = 0;i < length;++i) { var leafletPoint = VRS.leafletUtilities.toLeafletLatLng(path[i], state.map); if(toStart) { points.splice(insertAt++, 0, leafletPoint); } else { points.push(leafletPoint); } } polyline.polyline.setLatLngs(points); } } replacePolylinePointAt(idOrPolyline: string | number | IMapPolyline, index: number, point: ILatLng) { var polyline = <MapPolyline>this.getPolyline(idOrPolyline); var points = <L.LatLng[]>polyline.polyline.getLatLngs(); var length = points.length; if(index === -1) index = length - 1; if(index >= 0 && index < length) { var state = this._getState(); points.splice(index, 1, VRS.leafletUtilities.toLeafletLatLng(point, state.map)); polyline.polyline.setLatLngs(points); } } addPolygon(id: string | number, userOptions: IMapPolygonSettings): IMapPolygon { var result: MapPolygon; var state = this._getState(); if(state.map) { var options: IMapPolygonSettings = $.extend(<IMapPolygonSettings>{}, userOptions, { visible: true }); var leafletOptions: L.PolylineOptions = { color: options.strokeColour || '#000000', fillColor: options.fillColour || '#ffffff', }; if(options.strokeOpacity || leafletOptions.opacity === 0) leafletOptions.opacity = options.strokeOpacity; if(options.fillOpacity || leafletOptions.fillOpacity === 0) leafletOptions.fillOpacity = options.fillOpacity; if(options.strokeWeight || leafletOptions.weight === 0) leafletOptions.weight = options.strokeWeight; var paths: L.LatLng[] = []; if(options.paths) paths = VRS.leafletUtilities.toLeafletLatLngArray(options.paths[0], state.map); this.destroyPolygon(id); var polygon = new L.Polygon(paths, leafletOptions); if(options.visible) { polygon.addTo(state.map); } result = new MapPolygon(id, state.map, polygon, userOptions.tag, userOptions); state.polygons[id] = result; } return result; } getPolygon(idOrPolygon: string | number | IMapPolygon): IMapPolygon { if(idOrPolygon instanceof MapPolygon) return idOrPolygon; var state = this._getState(); return state.polygons[<string | number>idOrPolygon]; } destroyPolygon(idOrPolygon: string | number | IMapPolygon) { var state = this._getState(); var polygon = <MapPolygon>this.getPolygon(idOrPolygon); if(polygon) { polygon.destroy(); delete state.polygons[polygon.id]; polygon.id = null; } } addCircle(id: string | number, userOptions: IMapCircleSettings): IMapCircle { var result: MapCircle = null; var state = this._getState(); if(state.map) { var options: IMapCircleSettings = $.extend({}, userOptions, { visible: true }); var leafletOptions: L.CircleMarkerOptions = { fillColor: options.fillColor || '#000', fillOpacity: options.fillOpacity !== null && options.fillOpacity !== undefined ? options.fillOpacity : 0, color: options.strokeColor || '#000', opacity: options.strokeOpacity !== null && options.strokeOpacity !== undefined ? options.strokeOpacity : 1, weight: options.strokeWeight !== null && options.strokeWeight !== undefined ? options.strokeWeight : 1, radius: options.radius || 0 }; var centre = VRS.leafletUtilities.toLeafletLatLng(options.center, state.map); this.destroyCircle(id); var circle = L.circle(centre, leafletOptions); if(options.visible) { circle.addTo(state.map); } result = new MapCircle(id, state.map, circle, options.tag, options); state.circles[id] = result; } return result; } getCircle(idOrCircle: string | number | IMapCircle): IMapCircle { if(idOrCircle instanceof MapCircle) return idOrCircle; var state = this._getState(); return state.circles[<string | number>idOrCircle]; } destroyCircle(idOrCircle: string | number | IMapCircle) { var state = this._getState(); var circle = <MapCircle>this.getCircle(idOrCircle); if(circle) { circle.destroy(); delete state.circles[circle.id]; circle.id = null; } } getUnusedInfoWindowId(): string { var result; var state = this._getState(); for(var i = 1;i > 0;++i) { result = 'autoID' + i; if(!state.infoWindows[result]) break; } return result; } addInfoWindow(id: string | number, userOptions: IMapInfoWindowSettings): IMapInfoWindow { var result: MapInfoWindow = null; var state = this._getState(); if(state.map) { var options: IMapInfoWindowSettings = $.extend({ visible: true }, userOptions); var leafletOptions: L.PopupOptions = { autoPan: !!!options.disableAutoPan, autoClose: false, closeOnClick: false, maxWidth: options.maxWidth }; if(options.pixelOffset) { leafletOptions.offset = VRS.leafletUtilities.toLeafletSize(options.pixelOffset); } this.destroyInfoWindow(id); var infoWindow = new L.Popup(leafletOptions); if(options.position) { infoWindow.setLatLng(VRS.leafletUtilities.toLeafletLatLng(options.position, state.map)); } if(options.content) { infoWindow.setContent(<HTMLElement>options.content); } result = new MapInfoWindow(id, state.map, infoWindow, options.tag, options); state.infoWindows[id] = result; } return result; } getInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow): IMapInfoWindow { if(idOrInfoWindow instanceof MapInfoWindow) return idOrInfoWindow; var state = this._getState(); return state.infoWindows[<string | number>idOrInfoWindow]; } destroyInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow) { var state = this._getState(); var infoWindow = <MapInfoWindow>this.getInfoWindow(idOrInfoWindow); if(infoWindow) { this.closeInfoWindow(infoWindow); infoWindow.destroy(); delete state.infoWindows[infoWindow.id]; infoWindow.id = null; } } openInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow, mapMarker?: IMapMarker) { var state = this._getState(); var infoWindow = <MapInfoWindow>this.getInfoWindow(idOrInfoWindow); if(infoWindow && state.map) { infoWindow.open(<MapMarker>mapMarker); } } closeInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow) { var infoWindow = <MapInfoWindow>this.getInfoWindow(idOrInfoWindow); infoWindow.close(); } addControl(element: JQuery | HTMLElement, mapPosition: MapPositionEnum) { var state = this._getState(); if(state.map) { var controlOptions: L.ControlOptions = { position: VRS.leafletUtilities.toLeafletMapPosition(mapPosition) }; var control = new MapControl(element, controlOptions); control.addTo(state.map); } } // // MAP LAYER METHODS // addLayer(layerTileSettings: ITileServerSettings, opacity: number) { var state = this._getState(); if(state.map && layerTileSettings && layerTileSettings.IsLayer && layerTileSettings.Name) { var mapLayer = state.layers[layerTileSettings.Name]; if(!mapLayer) { var layerOptions = this._buildTileServerOptions(state, layerTileSettings, 100); if(opacity !== null && opacity !== undefined) { layerOptions.opacity = Math.min(1.0, Math.max(0, opacity / 100.0)); } $.extend({ opacity: 1.0 }, layerOptions); var tileLayer = L.tileLayer(layerTileSettings.Url, layerOptions); tileLayer.addTo(state.map); mapLayer = new MapLayer(state.map, tileLayer); state.layers[layerTileSettings.Name] = mapLayer; } } } destroyLayer(layerName: string) { var state = this._getState(); if(state.map && layerName) { var mapLayer = state.layers[layerName]; if(mapLayer) { mapLayer.layer.removeFrom(state.map); mapLayer.destroy(); delete state.layers[layerName]; } } } hasLayer(layerName: string) : boolean { var state = this._getState(); return !!(state.map && layerName && state.layers[layerName]); } getLayerOpacity(layerName: string) { var result: number = undefined; var state = this._getState(); if(state.map && layerName) { var mapLayer = state.layers[layerName]; if(mapLayer) { result = mapLayer.getOpacity() * 100.0; } } return result; } setLayerOpacity(layerName: string, opacity: number) { var state = this._getState(); if(state.map && layerName && !isNaN(opacity)) { var mapLayer = state.layers[layerName]; if(mapLayer) { mapLayer.setOpacity(Math.min(1.0, Math.max(0.0, opacity / 100.0))); } } } // // BRIGHTNESS METHODS // getCanSetMapBrightness() : boolean { return true; } getDefaultMapBrightness() : number { var state = this._getState(); return state.defaultBrightness; } getMapBrightness() : number { var state = this._getState(); return state.brightness; } setMapBrightness(value: number) { var state = this._getState(); if(value && !isNaN(value) && state.brightness !== value) { if(!state.map) { state.brightness = value; } else { var container = state.tileLayer.getContainer(); container.className = this._setBrightnessClass( container.className, state.brightness, value ); state.brightness = value; } this.saveState(); this._raiseBrightnessChanged(); } } private _setBrightnessClass(currentClassName: string, currentBrightness: number, newBrightness: number) : string { var result = currentClassName; if(currentBrightness !== newBrightness) { if(!result) { result = ''; } var currentBrightnessClass = this._classNameForMapBrightness(currentBrightness); if(currentBrightnessClass !== '') { result = result .replace(currentBrightnessClass, '') .trim(); } var newBrightnessClass = this._classNameForMapBrightness(newBrightness); if(newBrightnessClass !== '') { if(result.length > 0) { result += ' '; } result += newBrightnessClass; } } return result; } private _classNameForMapBrightness(brightness: number) : string { var result = ''; if(brightness && !isNaN(brightness) && brightness > 0 && brightness <= 150 && brightness !== 100 && brightness / 10 === Math.floor(brightness / 10)) { result = 'vrs-brightness-' + brightness; } return result; } // // VRS EVENTS SUBSCRIBED // /** * Called when the refresh manager indicates that one of our parents has resized, or done something that we need * to refresh for. */ private _targetResized() { var state = this._getState(); var center = this._getCenter(state); this.refreshMap(); this._setCenter(state, center); } } $.widget('vrs.vrsMap', new MapPlugin()); } declare interface JQuery { vrsMap(); vrsMap(options: VRS.IMapOptions); vrsMap(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import {toHex, toHexByte} from "z80-base"; import {ProgramAnnotation} from "./ProgramAnnotation.js"; // Number of bytes per row. const STRIDE = 16; // Unicode for a vertical ellipsis. const VERTICAL_ELLIPSIS = 0x22EE; /** * Returns whether two string arrays are the same. * * Lodash has isEqual(), but it adds about 15 kB after minimization! (It's a deep comparison * that has to deal with all sorts of data types.) */ export function isSameStringArray(a: string[], b: string[]): boolean { return a.length === b.length && a.every((value, index) => value === b[index]); } /** * Compare two parts of an array for equality. */ function segmentsEqual(binary: Uint8Array, start1: number, start2: number, length: number): boolean { while (length-- > 0) { if (binary[start1++] !== binary[start2++]) { return false; } } return true; } /** * Count consecutive bytes that are around "addr". */ function countConsecutive(binary: Uint8Array, addr: number) { const value = binary[addr]; let startAddr = addr; while (startAddr > 0 && binary[startAddr - 1] === value) { startAddr--; } while (addr < binary.length - 1 && binary[addr + 1] === value) { addr++; } return addr - startAddr + 1; } /** * Whether this segment is made up of the same value. */ function allSameByte(binary: Uint8Array, addr: number, length: number): boolean { for (let i = 1; i < length; i++) { if (binary[addr + i] !== binary[addr]) { return false; } } return true; } /** * Generates a hexdump for the given binary. * * The LINE_TYPE type keeps track of an entire line being output. It's made of several SPAN_TYPE objects. */ export abstract class HexdumpGenerator<LINE_TYPE, SPAN_TYPE> { private readonly binary: Uint8Array; private readonly collapse: boolean; private readonly annotations: ProgramAnnotation[]; protected constructor(binary: Uint8Array, collapse: boolean, annotations: ProgramAnnotation[]) { this.binary = binary; this.collapse = collapse; this.annotations = annotations; } /** * Create a new line object. */ protected abstract newLine(): LINE_TYPE; /** * Get the accumulated text for a line. */ protected abstract getLineText(line: LINE_TYPE): string; /** * Add a span with the given text and classes to the specified line. * * The classes are: * * - address: hex address of a row. * - hex: hex data. * - ascii: plain ASCII data. * - ascii-unprintable: ASCII data but not printable (e.g., control character). * - annotation: text annotations on the right side. * - outside-annotation: mixin class for data that's outside the current line's annotation. Should * be displayed dimly or not at all. */ protected abstract newSpan(line: LINE_TYPE, text: string, ...cssClass: string[]): SPAN_TYPE; /** * Add the text to the span. */ protected abstract addTextToSpan(span: SPAN_TYPE, text: string): void; /** * Generate all HTML elements for this binary. */ public *generate(): Generator<LINE_TYPE, void, void> { const binary = this.binary; const [addrDigits, addrSpaces] = this.computeAddressSize(); // Sort in case they were generated out of order. this.annotations.sort((a, b) => a.begin - b.begin); let lastAnnotation: ProgramAnnotation | undefined = undefined; for (const annotation of this.annotations) { if (lastAnnotation !== undefined && lastAnnotation.end < annotation.begin) { yield* this.generateAnnotation(new ProgramAnnotation("", lastAnnotation.end, annotation.begin)); } // Make sure there are no overlapping annotations. if (lastAnnotation === undefined || lastAnnotation.end <= annotation.begin) { yield* this.generateAnnotation(annotation); } lastAnnotation = annotation; } const lastAnnotationEnd = lastAnnotation !== undefined ? lastAnnotation.end : 0; if (lastAnnotationEnd < binary.length) { yield* this.generateAnnotation(new ProgramAnnotation("", lastAnnotationEnd, binary.length)); } // Final address to show where file ends. const finalLine = this.newLine(); this.newSpan(finalLine, toHex(binary.length, addrDigits), "address"); yield finalLine; } /** * Generate all the lines for an annotation. * @param annotation the annotation to generate. */ private *generateAnnotation(annotation: ProgramAnnotation): Generator<LINE_TYPE, void, void> { const binary = this.binary; const [addrDigits, addrSpaces] = this.computeAddressSize(); const beginAddr = Math.floor(annotation.begin/STRIDE)*STRIDE; const endAddr = Math.min(Math.ceil(annotation.end/STRIDE)*STRIDE, binary.length); let lastAddr: number | undefined = undefined; for (let addr = beginAddr; addr < endAddr; addr += STRIDE) { if (this.collapse && lastAddr !== undefined && binary.length - addr >= STRIDE && segmentsEqual(binary, lastAddr, addr, STRIDE)) { // Collapsed section. See if we want to print the text for it this time. if (addr === lastAddr + STRIDE) { const line = this.newLine(); if (allSameByte(binary, addr, STRIDE)) { // Lots of the same byte repeated. Say many there are. const count = countConsecutive(binary, addr); this.newSpan(line, addrSpaces + " ... ", "address"); this.newSpan(line, count.toString(), "ascii"); this.newSpan(line, " (", "address"); this.newSpan(line, "0x" + count.toString(16).toUpperCase(), "ascii"); this.newSpan(line, ") consecutive bytes of ", "address"); this.newSpan(line, "0x" + toHexByte(binary[addr]), "hex"); this.newSpan(line, " ...", "address"); } else { // A repeating pattern, but not all the same byte. Say how many times repeated. let count = 1; for (let otherAddr = addr + STRIDE; otherAddr <= binary.length - STRIDE; otherAddr += STRIDE) { if (segmentsEqual(binary, lastAddr, otherAddr, STRIDE)) { count += 1; } else { break; } } this.newSpan(line, addrSpaces + " ... ", "address"); this.newSpan(line, count.toString(), "ascii"); const plural = count === 1 ? "" : "s"; this.newSpan(line, ` repetition${plural} of previous row ...`, "address"); } // Draw vertical ellipsis. if (annotation.text !== "" && addr !== beginAddr) { // textContent doesn't trigger a reflow. Don't use innerText, which does. const lineText = this.getLineText(line); const width = addrDigits + STRIDE*4 + 9; const label = String.fromCodePoint(VERTICAL_ELLIPSIS).padStart(width - lineText.length, " "); this.newSpan(line, label, "annotation"); } yield line; } } else { // Non-collapsed row. lastAddr = addr; let label: string = ""; if (annotation.text !== "") { if (addr === beginAddr) { label = annotation.text; } else { // Vertical ellipsis. label = " " + String.fromCodePoint(VERTICAL_ELLIPSIS); } } yield this.generateRow(addr, addrDigits, annotation.begin, annotation.end, label); } } } /** * Generates a single row of hex and ASCII. * @param addr address for the line. * @param addrDigits the number of digits in the address. * @param beginAddr the first address of this annotation (inclusive). * @param endAddr this last address of this annotation (exclusive). * @param label the label to show on this row. * @return the created row. */ private generateRow(addr: number, addrDigits: number, beginAddr: number, endAddr: number, label: string): LINE_TYPE { const binary = this.binary; const line = this.newLine(); const cssClass = ["address"]; if (addr < beginAddr) { cssClass.push("outside-annotation"); } this.newSpan(line, toHex(addr, addrDigits) + " ", ...cssClass); // Utility function for adding text to a line, minimizing the number of needless spans. let currentCssClass: string[] | undefined = undefined; let e: SPAN_TYPE | undefined = undefined; const addText = (text: string, ...cssClass: string[]) => { if (e === undefined || currentCssClass === undefined || !isSameStringArray(cssClass, currentCssClass)) { e = this.newSpan(line, text, ...cssClass); currentCssClass = cssClass.slice(); } else { this.addTextToSpan(e, text); } }; // Hex. let subAddr: number; for (subAddr = addr; subAddr < binary.length && subAddr < addr + STRIDE; subAddr++) { const cssClass = ["hex"]; if (subAddr < beginAddr || subAddr >= endAddr) { cssClass.push("outside-annotation"); } addText(toHexByte(binary[subAddr]) + " ", ...cssClass); } addText("".padStart((addr + STRIDE - subAddr) * 3 + 2, " "), "hex"); // ASCII. for (subAddr = addr; subAddr < binary.length && subAddr < addr + STRIDE; subAddr++) { const c = binary[subAddr]; const cssClass = ["hex"]; let char; if (c >= 32 && c < 127) { cssClass.push("ascii"); char = String.fromCharCode(c); } else { cssClass.push("ascii-unprintable"); char = "."; } if (subAddr < beginAddr || subAddr >= endAddr) { cssClass.push("outside-annotation"); } addText(char, ...cssClass); } if (label !== "") { addText("".padStart(addr + STRIDE - subAddr + 2, " ") + label, "annotation"); } return line; } /** * Computes the number of hex digits in the displayed address, and the spaces this represents. */ private computeAddressSize(): [number, string] { // Figure out the number of digits in the address: 4 or 6. const addrDigits = this.binary.length < (2 << 16) ? 4 : 6; const addrSpaces = "".padStart(addrDigits, " "); return [addrDigits, addrSpaces]; } }
the_stack
import express from 'express'; import accepts from 'accepts'; import passport from 'passport'; import multer from 'multer'; import * as os from 'os'; import * as ThingTalk from 'thingtalk'; import * as semver from 'semver'; import * as db from '../util/db'; import * as entityModel from '../model/entity'; import * as stringModel from '../model/strings'; import * as commandModel from '../model/example'; import * as orgModel from '../model/organization'; import ThingpediaClient from '../util/thingpedia-client'; import * as SchemaUtils from '../util/manifest_to_schema'; import * as userUtils from '../util/user'; import * as iv from '../util/input_validation'; import { ForbiddenError, AuthenticationError } from '../util/errors'; import * as errorHandling from '../util/error_handling'; import * as I18n from '../util/i18n'; import { uploadEntities, uploadStringDataset } from '../util/upload_dataset'; import { validatePageAndSize } from '../util/pagination'; import { getCommandDetails } from '../util/commandpedia'; import { uploadDevice } from '../util/import_device'; import * as Config from '../config'; const everything = express.Router(); // apis are CORS enabled always everything.use('/', (req, res, next) => { res.set('Access-Control-Allow-Origin', '*'); res.set('Vary', 'Origin'); next(); }); everything.options('/[^]{0,}', (req, res, next) => { res.set('Access-Control-Max-Age', '86400'); res.set('Access-Control-Allow-Methods', 'GET, POST'); res.set('Access-Control-Allow-Headers', 'Authorization, Accept, Content-Type'); res.set('Access-Control-Allow-Origin', '*'); res.set('Vary', 'Origin'); res.send(''); }); const commonQueryArgs = { developer_key: '?string', locale: '?string', thingtalk_version: '?string', } as const; // expose some legacy unversioned endpoints that were used until recently by // the browser code of Almond everything.get('/devices', iv.validateGET({ ...commonQueryArgs, class: '?string' }), (req, res, next) => { if (!isValidDeviceClass(req, res)) return; const client = new ThingpediaClient(req.query.developer_key, req.query.locale); client.getDeviceFactories(req.query.class).then((obj) => { // convert to v1 format obj = obj.map((d) : any => { return { primary_kind: d.kind, name: d.text, factory: d }; }); res.cacheFor(86400000); res.json(obj); }).catch(next); }); everything.get('/devices/icon/:kind', (req, res) => { // cache for forever, this redirect will never expire res.cacheFor(6, 'months'); res.redirect(301, Config.CDN_HOST + '/icons/' + req.params.kind + '.png'); }); const v3 = express.Router(); // NOTES on versioning // // The whole API is exposed under /thingpedia/api/vX // // Any time an endpoint is changed incompatibly, make a // copy of the endpoint and mount it under the newer vN // // To add a new endpoint, add it to the new vN only // To remove an endpoint, add it to the vN with // `next('router')` as the handler: this will cause the // vN router to be skipped, failing back to the handler // for / at the top (which returns 404) /** * @api {get} /v3/schema/:schema_ids Get Type Information And Metadata * @apiName GetSchema * @apiGroup Schemas * @apiVersion 0.3.0 * * @apiDescription Retrieve the ThingTalk type information and natural language metadata * associated with the named device classes; multiple devices can be requested at once, * separated by a comma. * This API returns a single ThingTalk library file containing all the requested classes * that could be found. Invalid or inaccessible class names are silently ignored. * * @apiParam {String[]} schema_ids The identifiers (kinds) of the schemas * to retrieve * @apiParam {Number{0-1}} meta Include natural language metadata in the output * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned **/ v3.get('/schema/:schemas', iv.validateGET(commonQueryArgs), (req, res, next) => { // do content negotiation for two reasons: // - one is to force legacy clients that try to talk v3 and do JSON output into // producing ThingTalk output instead // - the other is to recognize browsers, so we show the ThingTalk code inline instead // of downloading, which is quite convenient const accept = accepts(req).types(['application/x-thingtalk', 'text/html']); if (!accept) { res.status(405).json({ error: 'must accept application/x-thingtalk' }); return; } const schemas = req.params.schemas.split(','); const withMetadata = req.query.meta === '1'; const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getSchemas(schemas, withMetadata).then((obj) => { res.set('Vary', 'Accept'); // don't cache if the user is a developer if (!req.query.developer_key) res.cacheFor(86400000); if (typeof obj === 'string') res.set('Content-Type', accept === 'text/html' ? 'text/plain' : accept).send(obj); else res.json({ result: 'ok', data: obj }); }).catch(next); }); /** * @api {get} /v3/devices/code/:kind Get Device Manifest * @apiName GetDeviceCode * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Retrieve the manifest associated with the named device. * See the [Guide to writing Thingpedia Entries](../thingpedia-device-intro.md) * for a complete description of the manifest format. * This API performs content negotiation, based on the `Accept` header. If * the `Accept` header is unset or set to `application/x-thingtalk`, then a ThingTalk * dataset is returned. Otherwise, the accept header must be set to `application/json`, * or a 405 Not Acceptable error occurs. * * @apiParam {String} kind The identifier of the device to retrieve * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object} data The manifest, as a JSON object */ v3.get('/devices/code/:kind', iv.validateGET(commonQueryArgs), (req, res, next) => { const accept = accepts(req).types(['application/x-thingtalk', 'text/html']); if (!accept) { res.status(405).json({ error: 'must accept application/x-thingtalk' }); return; } const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getDeviceCode(req.params.kind).then((code) => { res.set('Vary', 'Accept'); const match = /#\[version=([0-9]+)\]/.exec(code); const version = match ? match[1] : -1; if (version >= 0) res.set('ETag', `W/"version=${version}"`); res.cacheFor(86400000); res.set('Content-Type', accept === 'text/html' ? 'text/plain' : accept); res.send(code); }).catch(next); }); /** * @api {get} /v3/devices/setup/:kinds Get Device Setup Information * @apiName GetDeviceSetup * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Retrieve configuration factories for the named devices * or abstract classes. Returns an object with one property for each type given in the * input. * * If an abstract class is implemented by multiple devices, the return value is a factory * of type `multiple`, with a single array `choices` containing multiple factories * for each concrete device that implements the abstract class. * If a device does not exist, is not visible, or is not configurable, * a factory of type `multiple` with an empty list of `choices` is returned. * * @apiParam {String} kinds The identifiers of the devices or types to configure, separated by a comma * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object} data An object with one property for each requested kind * @apiSuccess {Object} data.factory A configuration factory * @apiSuccess {String} data.factory.kind The exact kind of the concrete device being configured * @apiSuccess {String} data.factory.text The user visible name of the device from the database * @apiSuccess {String="physical","online","data"} data.factory.category Whether the device is a phyisical device, online account, or public service * @apiSuccess {String="none","form","oauth2","discovery","interactive"} data.factory.type The factory type * @apiSuccess {String="upnp","bluetooth"} [data.factory.discoveryType] Discovery protocol; only present if `type` is equal to `discovery` * @apiSuccess {String="upnp","bluetooth"} [data.factory.discoveryType] Discovery protocol; only present if `type` is equal to `discovery` * @apiSuccess {Object[]} [data.factory.fields] Form fields to configure the device; only present if `type` is equal to `form` * @apiSuccess {String} [data.factory.fields.name] Parameter name associated with this form field * @apiSuccess {String} [data.factory.fields.label] User visible label for this field * @apiSuccess {String="text","password"} [data.factory.fields.type] The type of the form field; the meaning is the same as HTML5 `<input type>` * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": { * "com.twitter": { * "type": "oauth2", * "category": "online", * "kind": "com.twitter", * "text": "Twitter Account" * }, * "com.nest.security_camera": { * "type": "oauth2", * "category": "online", * "kind": "com.nest", * "text": "Nest Account" * } * } * } */ v3.get('/devices/setup/:kinds', iv.validateGET(commonQueryArgs), (req, res, next) => { const kinds = req.params.kinds.split(','); const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getDeviceSetup(kinds).then((result) => { res.cacheFor(86400000); res.status(200).json({ result: 'ok', data: result }); }).catch(next); }); /** * @api {get} /v3/devices/icon/:kind Get Device Icon * @apiName GetDeviceIcon * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Download the icon for a given device. * NOTE: this API returns the icon directly (it does not return JSON); * it is suitable to use in e.g. `<img src>` but the caller must support * HTTP redirects. * * @apiParam {String} kind The identifier of the device for which the icon is desired. */ v3.get('/devices/icon/:kind', (req, res) => { // cache for forever, this redirect will never expire res.cacheFor(6, 'months'); res.redirect(301, Config.CDN_HOST + '/icons/' + req.params.kind + '.png'); }); /** * @api {get} /v3/devices/package/:kind Get Device Package * @apiName GetDevicePackage * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Download the JS package for a given device. * * @apiParam {String} kind The identifier of the desired device. */ v3.get('/devices/package/:kind', iv.validateGET({ ...commonQueryArgs, version: '?integer' }), (req, res, next) => { const kind = req.params.kind; const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getModuleLocation(kind, req.query.version ? Number(req.query.version) : undefined).then((location) => { res.cacheFor(60000); res.redirect(302, location); }).catch(next); }); function isValidDeviceClass(req : express.Request, res : express.Response) { if (req.query.class && ['online', 'physical', 'data', 'system', 'media', 'social-network', 'home', 'communication', 'health', 'service', 'data-management'].indexOf(req.query.class as string) < 0) { res.status(400).json({ error: "Invalid device class", code: 'EINVAL' }); return false; } else { return true; } } /** * @api {get} /v3/devices/setup Get Device Setup List * @apiName GetDeviceSetupList * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Retrieve configuration factories for all devices in Thingpedia. * * @apiParam {String="physical","online","data"} [class] If provided, only devices of this category are returned * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data The array of all factories * @apiSuccess {String} data.kind The exact kind of the concrete device being configured * @apiSuccess {String} data.text The user visible name of the device from the database * @apiSuccess {String="physical","online","data"} data.category Whether the device is a phyisical device, online account, or public service * @apiSuccess {String="none","form","oauth2","discovery","interactive"} data.type The factory type * @apiSuccess {String="upnp","bluetooth"} [data.discoveryType] Discovery protocol; only present if `type` is equal to `discovery` * @apiSuccess {String="upnp","bluetooth"} [data.discoveryType] Discovery protocol; only present if `type` is equal to `discovery` * @apiSuccess {Object[]} [data.fields] Form fields to configure the device; only present if `type` is equal to `form` * @apiSuccess {String} [data.fields.name] Parameter name associated with this form field * @apiSuccess {String} [data.fields.label] User visible label for this field * @apiSuccess {String="text","password"} [data.fields.type] The type of the form field; the meaning is the same as HTML5 `<input type>` * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "type": "oauth2", * "category": "online", * "kind": "com.twitter", * "text": "Twitter Account" * }, * { * "type": "oauth2", * "category": "online", * "kind": "com.nest", * "text": "Nest Account" * }, * ... * ] * } */ v3.get('/devices/setup', iv.validateGET({ ...commonQueryArgs, class: '?string' }), (req, res, next) => { if (!isValidDeviceClass(req, res)) return; const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getDeviceFactories(req.query.class).then((obj) => { res.cacheFor(86400000); res.json({ result: 'ok', data: obj }); }).catch(next); }); /** * @api {get} /v3/devices/all Get Full Device List * @apiName GetDeviceList * @apiGroup Devices * @apiVersion 0.3.1 * * @apiDescription Retrieve the list of all devices in Thingpedia. * Results are paginated according to the `page` and `page_size` parameters. * * @apiParam {String="physical","online","data"} [class] If provided, only devices of this category are returned * @apiParam {Number{0-}} [page=0] Page number (0-based); negative page numbers are ignored * @apiParam {Number{1-50}} [page_size=10] Number of results to return * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data The array of all devices * @apiSuccess {String} data.primary_kind The primary identifier of the device * @apiSuccess {String} data.name The user visible name of the device * @apiSuccess {String} data.description A longer, user visible, description of the device * @apiSuccess {String} data.license The license for the device package, as a SPDX string * @apiSuccess {String} data.website The primary website for the device or service * @apiSuccess {String} data.repository A link to a public source code repository for the device * @apiSuccess {String} data.issue_tracker A link to page where users can report bugs for the device * @apiSuccess {String="physical","online","data"} data.category Whether the device is a phyisical device, online account, or public service * @apiSuccess {String="home","data-management","communication","social-network","health","media","service"} data.subcategory The general domain of this device * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "primary_kind": "com.twitter", * "name": "Twitter Account", * "description": "Connect your Almond with Twitter", * "category": "online", * "subcategory": "social-network" * }, * ... * ] * } */ v3.get('/devices/all', iv.validateGET({ ...commonQueryArgs, class: '?string', page: '?integer', page_size: '?integer', }), (req, res, next) => { const [page, page_size] = validatePageAndSize(req, 10, 50); if (!isValidDeviceClass(req, res)) return; const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getDeviceList(req.query.class, page, page_size).then((devices) => { res.cacheFor(86400000); res.json({ result: 'ok', data: devices }); }).catch(next); }); /** * @api {get} /v3/devices/search Search Devices by Keyword * @apiName GetDeviceSearch * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Search devices by keyword or name * * @apiParam {String} q Query string * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data The array of all devices * @apiSuccess {String} data.primary_kind The primary identifier of the device * @apiSuccess {String} data.name The user visible name of the device * @apiSuccess {String} data.description A longer, user visible, description of the device * @apiSuccess {String="physical","online","data"} data.category Whether the device is a phyisical device, online account, or public service * @apiSuccess {String="home","data-management","communication","social-network","health","media","service"} data.subcategory The general domain of this device * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "primary_kind": "com.twitter", * "name": "Twitter Account", * "description": "Connect your Almond with Twitter", * "category": "online", * "subcategory": "social-network" * } * ] * } */ v3.get('/devices/search', iv.validateGET({ ...commonQueryArgs, q: 'string' }), (req, res, next) => { const q = req.query.q; const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.searchDevice(q).then((devices) => { res.cacheFor(86400000); res.json({ result: 'ok', data: devices }); }).catch(next); }); /** * @api {get} /v3/commands/all Get All Commands from Commandpedia * @apiName GetAllCommands * @apiGroup Commandpedia * @apiVersion 0.3.0 * * @apiDescription Retrieve the list of Commandpedia commands. * Results are paginated according to the `page` and `page_size` parameters. * * @apiParam {Number{0-}} [page=0] Page number (0-based); negative page numbers are ignored * @apiParam {Number{1-50}} [page_size=9] Number of results to return * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data The array of all commands * @apiSuccess {Number} data.id Command ID * @apiSuccess {String} data.language 2 letter language code for this command * @apiSuccess {String="commandpedia"} data.type The internal command type * @apiSuccess {String} data.utterance The original, unprocessed command * @apiSuccess {String} data.preprocessed The command in tokenized form, as a list of tokens separated by a space * @apiSuccess {String} data.target_code The stored code associated with this command, in preprocess NN-Syntax ThingTalk * @apiSuccess {Number} data.click_count How popular this command is (number of users who have favorited it) * @apiSuccess {String} data.owner_name The username of the user who contributed this command * @apiSuccess {String[]} data.devices IDs of the devices referenced by this command * @apiSuccess {String[]} data.deviceNames User visible names of the devices referenced by this command * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "id": 1687826, * "language": "en", * "type": "commandpedia", * "utterance": "if bitcoin price goes above $10000, notify me", * "preprocessed": "if bitcoin price goes above CURRENCY_0 , notify me", * "target_code": "edge ( monitor ( @com.cryptonator.get_price param:currency:Entity(tt:cryptocurrency_code) = \" bitcoin \" ^^tt:cryptocurrency_code ) ) on param:price:Currency >= CURRENCY_0 => notify", * "click_count": 2, * "owner_name": "sileixu", * "devices": [ * "com.cryptonator" * ], * }, * ... * ] * } */ v3.get('/commands/all', iv.validateGET({ ...commonQueryArgs, page: '?integer', page_size: '?integer', }), (req, res, next) => { const locale = req.query.locale || 'en-US'; const language = I18n.localeToLanguage(locale); const gettext = I18n.get(locale).gettext; const [page, page_size] = validatePageAndSize(req, 9, 50); db.withTransaction(async (client) => { const commands = await commandModel.getCommands(client, language, page * page_size, page_size); getCommandDetails(gettext, commands); res.cacheFor(30 * 1000); res.json({ result: 'ok', data: commands }); }).catch(next); }); /** * @api {get} /v3/commands/search Search Commands by Keyword * @apiName SearchCommands * @apiGroup Commandpedia * @apiVersion 0.3.0 * * @apiDescription Search commands in Commandpedia by keyword. * * @apiParam {String} q Query string * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data The array of all commands * @apiSuccess {Number} data.id Command ID * @apiSuccess {String} data.language 2 letter language code for this command * @apiSuccess {String="commandpedia"} data.type The internal command type * @apiSuccess {String} data.utterance The original, unprocessed command * @apiSuccess {String} data.preprocessed The command in tokenized form, as a list of tokens separated by a space * @apiSuccess {String} data.target_code The stored code associated with this command, in preprocess NN-Syntax ThingTalk * @apiSuccess {Number} data.click_count How popular this command is (number of users who have favorited it) * @apiSuccess {String} data.owner_name The username of the user who contributed this command * @apiSuccess {String[]} data.devices IDs of the devices referenced by this command * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "id": 1687826, * "language": "en", * "type": "commandpedia", * "utterance": "if bitcoin price goes above $10000, notify me", * "preprocessed": "if bitcoin price goes above CURRENCY_0 , notify me", * "target_code": "edge ( monitor ( @com.cryptonator.get_price param:currency:Entity(tt:cryptocurrency_code) = \" bitcoin \" ^^tt:cryptocurrency_code ) ) on param:price:Currency >= CURRENCY_0 => notify", * "click_count": 2, * "owner_name": "sileixu", * "devices": [ * "com.cryptonator" * ] * }, * ... * ] * } */ v3.get('/commands/search', iv.validateGET({ ...commonQueryArgs, q: 'string' }), (req, res, next) => { const q = req.query.q; const locale = req.query.locale || 'en-US'; const language = I18n.localeToLanguage(locale); const gettext = I18n.get(locale).gettext; db.withTransaction(async (client) => { const commands = await commandModel.getCommandsByFuzzySearch(client, language, q); getCommandDetails(gettext, commands); res.cacheFor(30 * 1000); res.json({ result: 'ok', data: commands }); }).catch(next); }); /** * @api {post} /v3/devices/discovery Resolve Discovery Information * @apiName Discovery * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Convert public discovery information gathered locally * to the identifier of a device in Thingpedia. * * See the thingpedia-discovery module for documentation on the format * of the discovery data. * * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object} data Result from the Thingpedia lookup * @apiSuccess {String} data.kind The identifier of the best device to use for this discovery operation * */ // the /discovery endpoint was moved to /devices/discovery in v3 v3.post('/devices/discovery', iv.validateGET(commonQueryArgs), (req, res, next) => { const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getKindByDiscovery(req.body).then((result) => { res.cacheFor(86400000); res.status(200).json({ result: 'ok', data: { kind: result } }); }).catch(next); }); /** * @api {get} /v3/examples/by-kinds/:kinds Get Example Commands By Device * @apiName GetExamplesByKinds * @apiGroup Cheatsheet * @apiVersion 0.3.0 * * @apiDescription Retrieve the example commands from the cheatsheet for * the given devices. * * This API performs content negotiation, based on the `Accept` header. If * the `Accept` header is unset or set to `application/x-thingtalk`, then a ThingTalk * dataset is returned. Otherwise, the accept header must be set to `application/json`, * or a 405 Not Acceptable error occurs. * * @apiParam {String[]} kinds Comma-separated list of device identifiers for which to return examples * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Return examples in this language * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of example commands * @apiSuccess {Number} data.id Command ID * @apiSuccess {String} data.language 2 letter language code for this command * @apiSuccess {String="thingpedia"} data.type The internal command type * @apiSuccess {String} data.utterance The original, unprocessed command * @apiSuccess {String} data.preprocessed The command in tokenized form, as a list of tokens separated by a space * @apiSuccess {String} data.target_code The stored code associated with this command, in preprocess NN-Syntax ThingTalk * @apiSuccess {Number} data.click_count How popular this command is (number of users who have clicked it from suggestions) * @apiSuccess {Number} data.like_count How popular this command is (number of users who have liked it on the front page) * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "id": 1688881, * "language": "en", * "type": "thingpedia", * "utterance": "when someone i follow replies to user ${p_in_reply_to} on twitter", * "preprocessed": "when someone i follow replies to user ${p_in_reply_to} on twitter", * "target_code": "let stream x := \\(p_in_reply_to :Entity(tt:username)) -> monitor ((@com.twitter.home_timeline()), in_reply_to == p_in_reply_to);", * "click_count": 55, * "like_count": 1 * } * ] * } * */ v3.get('/examples/by-kinds/:kinds', iv.validateGET(commonQueryArgs), (req, res, next) => { const kinds = req.params.kinds.split(','); const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); const accept = accepts(req).types(['application/x-thingtalk', 'application/x-thingtalk;editMode=1', 'text/html']); if (!accept) { res.status(405).json({ error: 'must accept application/x-thingtalk' }); return; } client.getExamplesByKinds(kinds, accept as string).then((result) => { res.set('Vary', 'Accept'); res.cacheFor(300000); res.status(200); res.set('Content-Type', accept === 'text/html' ? 'text/plain' : accept); if (typeof result === 'string') res.send(result); else res.status(200).json({ result: 'ok', data: result }); }).catch(next); }); /** * @api {get} /v3/examples/all Get All Examples * @apiName GetAllExamples * @apiGroup Cheatsheet * @apiVersion 0.3.0 * * @apiDescription Retrieve all the example commands from Thingpedia. This corresponds * to the whole cheatsheet. * * This API performs content negotiation, based on the `Accept` header. If * the `Accept` header is unset or set to `application/x-thingtalk`, then a ThingTalk * dataset is returned. Otherwise, the accept header must be set to `application/json`, * or a 405 Not Acceptable error occurs. * * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Return examples in this language * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of example commands * @apiSuccess {Number} data.id Command ID * @apiSuccess {String} data.language 2 letter language code for this command * @apiSuccess {String="thingpedia"} data.type The internal command type * @apiSuccess {String} data.utterance The original, unprocessed command * @apiSuccess {String} data.preprocessed The command in tokenized form, as a list of tokens separated by a space * @apiSuccess {String} data.target_code The stored code associated with this command, in preprocess NN-Syntax ThingTalk * @apiSuccess {Number} data.click_count How popular this command is (number of users who have clicked it from suggestions) * @apiSuccess {Number} data.like_count How popular this command is (number of users who have liked it on the front page) * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "id": 1688881, * "language": "en", * "type": "thingpedia", * "utterance": "when someone i follow replies to user ${p_in_reply_to} on twitter", * "preprocessed": "when someone i follow replies to user ${p_in_reply_to} on twitter", * "target_code": "let stream x := \\(p_in_reply_to :Entity(tt:username)) -> monitor ((@com.twitter.home_timeline()), in_reply_to == p_in_reply_to);", * "click_count": 55, * "like_count": 1 * } * ] * } * */ v3.get('/examples/all', iv.validateGET(commonQueryArgs), (req, res, next) => { const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); const accept = accepts(req).types(['application/x-thingtalk', 'application/x-thingtalk;editMode=1', 'text/html']); if (!accept) { res.status(405).json({ error: 'must accept application/x-thingtalk' }); return; } client.getAllExamples(accept as string).then((result) => { res.set('Vary', 'Accept'); res.cacheFor(300000); res.status(200); res.set('Content-Type', accept === 'text/html' ? 'text/plain' : accept); if (typeof result === 'string') res.send(result); else res.status(200).json({ result: 'ok', data: result }); }).catch(next); }); /** * @api {get} /v3/examples/search Get Example Commands By Keyword * @apiName SearchExamples * @apiGroup Cheatsheet * @apiVersion 0.3.0 * * @apiDescription Search the example commands matching the given query * string. Use this API endpoint to perform autocompletion and provide suggestions. * * This API performs content negotiation, based on the `Accept` header. If * the `Accept` header is unset or set to `application/x-thingtalk`, then a ThingTalk * dataset is returned. Otherwise, the accept header must be set to `application/json`, * or a 405 Not Acceptable error occurs. * * @apiParam {String} q Query string * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Return examples in this language * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of example commands * @apiSuccess {Number} data.id Command ID * @apiSuccess {String} data.language 2 letter language code for this command * @apiSuccess {String="thingpedia"} data.type The internal command type * @apiSuccess {String} data.utterance The original, unprocessed command * @apiSuccess {String} data.preprocessed The command in tokenized form, as a list of tokens separated by a space * @apiSuccess {String} data.target_code The stored code associated with this command, in preprocess NN-Syntax ThingTalk * @apiSuccess {Number} data.click_count How popular this command is (number of users who have clicked it from suggestions) * @apiSuccess {Number} data.like_count How popular this command is (number of users who have liked it on the front page) * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "id": 1688881, * "language": "en", * "type": "thingpedia", * "utterance": "when someone i follow replies to user ${p_in_reply_to} on twitter", * "preprocessed": "when someone i follow replies to user ${p_in_reply_to} on twitter", * "target_code": "let stream x := \\(p_in_reply_to :Entity(tt:username)) -> monitor ((@com.twitter.home_timeline()), in_reply_to == p_in_reply_to);", * "click_count": 55, * "like_count": 1 * } * ] * } * */ v3.get('/examples/search', iv.validateGET({ ...commonQueryArgs, q: 'string' }), (req, res, next) => { const accept = accepts(req).types(['application/x-thingtalk', 'application/x-thingtalk;editMode=1', 'text/html']); if (!accept) { res.status(405).json({ error: 'must accept application/x-thingtalk' }); return; } const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getExamplesByKey(req.query.q, accept as string).then((result) => { res.cacheFor(300000); res.status(200); res.set('Content-Type', accept === 'text/html' ? 'text/plain' : accept); if (typeof result === 'string') res.send(result); else res.json({ result: 'ok', data: result }); }).catch(next); }); /** * @api {post} /v3/examples/click/:id Record Usage of Example Command * @apiName ClickExample * @apiGroup Cheatsheet * @apiVersion 0.3.0 * * @apiDescription Record that the example with the given ID was used (clicked on). * * @apiParam {Number} id Example command ID * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * * @apiSuccessExample {json} Example Response: * { * "result": "ok" * } * */ v3.post('/examples/click/:id', iv.validateGET(commonQueryArgs), (req, res, next) => { const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.clickExample(Number(req.params.id)).then(() => { res.cacheFor(300000); res.status(200).json({ result: 'ok' }); }).catch(next); }); function getAllEntities(req : express.Request<any, any, any, { snapshot ?: string, developer_key ?: string, locale ?: string, thingtalk_version ?: string }>, res : express.Response, next : express.NextFunction) { const snapshotId = req.query.snapshot ? parseInt(req.query.snapshot) : -1; const etag = `"snapshot-${snapshotId}"`; if (snapshotId >= 0 && req.headers['if-none-match'] === etag) { res.set('ETag', etag); res.status(304).send(''); return; } const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getAllEntityTypes(snapshotId).then((data) => { // apply API compatibility with older clients that only expect a single subtype_of if (semver.lt(req.query.thingtalk_version || ThingTalk.version, '2.1.0-alpha.2')) { for (const type of data) { if (type.subtype_of?.length === 0) type.subtype_of = null; else (type as any).subtype_of = type.subtype_of?.[0] ?? null; } } if (data.length > 0 && snapshotId >= 0) { res.cacheFor(6, 'months'); res.set('ETag', etag); } else { res.cacheFor(86400000); } res.status(200).json({ result: 'ok', data }); }).catch(next); } /** * @api {get} /v3/entities/all Get List of Entity Types * @apiName GetAllEntities * @apiGroup Entities * @apiVersion 0.3.0 * * @apiDescription Retrieve the full list of entities supported entity types. * * @apiParam {Number} [snapshot=-1] Snapshot number. If provided, data corresponding to the given Thingpedia snapshot is returned; defaults to returning the current contents of Thingpedia. * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of entity types * @apiSuccess {Number} data.type Entity type identifier * @apiSuccess {String} data.name User-visible name of this entity type * @apiSuccess {Boolean} data.is_well_known Whether the entity type corresponds to a builtin type in ThingTalk * @apiSuccess {Boolean} data.has_ner_support Whether constants of this entity type * can be expressed in natural language, and identified using Named Entity Recognition (NER) * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "type": "com.gmail:email_id", * "name": "GMail Email ID", * "is_well_known": 0, * "has_ner_support": 0 * }, * { * "type": "org.freedesktop:app_id", * "name": "Freedesktop App Identifier", * "is_well_known": 0, * "has_ner_support": 1 * }, * { * "type": "tt:stock_id", * "name": "Company Stock ID", * "is_well_known": 0, * "has_ner_support": 1 * }, * { * "type": "tt:email_address", * "name": "Email Address", * "is_well_known": 1, * "has_ner_support": 0 * }, * ... * ] * } * */ v3.get('/entities/all', iv.validateGET({ ...commonQueryArgs, snapshot: '?string' }), getAllEntities); /** * @api {get} /v3/entities/lookup Lookup Entity By Name * @apiName EntityLookup * @apiGroup Entities * @apiVersion 0.3.0 * * @apiDescription Lookup the type and value of an entity given its name. * Use this endpoint to perform both Named Entity Recognition and Entity Linking. * * @apiParam {String} q Query String * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of candidate entity values; the list is not sorted and it is up to the client to identify the correct one * @apiSuccess {String} data.type Entity type identifier * @apiSuccess {String} data.value Opaque entity identifier * @apiSuccess {String} data.name User-visible name of this entity * @apiSuccess {String} data.canonical Preprocessed (tokenized and lower-cased) version of the user-visible name * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "type": "tt:stock_id", * "value": "wmt", * "canonical": "walmart inc.", * "name": "Walmart Inc." * } * ] * } * */ v3.get('/entities/lookup', iv.validateGET({ ...commonQueryArgs, q: 'string' }), (req, res, next) => { const language = (req.query.locale || 'en').split(/[-_@.]/)[0]; const token = req.query.q; db.withClient((dbClient) => { return entityModel.lookup(dbClient, language, token); }).then((rows) => { res.cacheFor(86400000); res.status(200).json({ result: 'ok', data: rows.map((r) => ({ type: r.entity_id, value: r.entity_value, canonical: r.entity_canonical, name: r.entity_name })) }); }).catch(next); }); /** * @api {get} /v3/entities/lookup/:type Lookup Entity By Type and Name * @apiName EntityLookupByType * @apiGroup Entities * @apiVersion 0.3.0 * * @apiDescription Lookup the value of an entity given its type and name. * Use this endpoint to perform Entity Linking after identifying an entity of * a certain type. * * @apiParam {String} type Entity Type * @apiParam {String} q Query String * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of candidate entity values; the list is not sorted and it is up to the client to identify the correct one * @apiSuccess {String} data.type Entity type identifier * @apiSuccess {String} data.value Opaque entity identifier * @apiSuccess {String} data.name User-visible name of this entity * @apiSuccess {String} data.canonical Preprocessed (tokenized and lower-cased) version of the user-visible name * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "type": "tt:stock_id", * "value": "wmt", * "canonical": "walmart inc.", * "name": "Walmart Inc." * } * ] * } * */ v3.get('/entities/lookup/:type', iv.validateGET({ ...commonQueryArgs, q: 'string' }), (req, res, next) => { const language = (req.query.locale || 'en').split(/[-_@.]/)[0]; const token = req.query.q; db.withClient((dbClient) => { return Promise.all([entityModel.lookupWithType(dbClient, language, req.params.type, token), entityModel.get(dbClient, req.params.type, language)]); }).then(([rows, meta]) => { res.cacheFor(86400000); res.status(200).json({ result: 'ok', meta: { name: meta.name, has_ner_support: meta.has_ner_support, is_well_known: meta.is_well_known }, data: rows.map((r) => ({ type: r.entity_id, value: r.entity_value, canonical: r.entity_canonical, name: r.entity_name })) }); }).catch(next); }); /** * @api {get} /v3/entities/list/:type List Entity Values * @apiName EntityList * @apiGroup Entities * @apiVersion 0.3.0 * * @apiDescription Enumerate all allowed values for an entity of the given type. * * @apiParam {String} type Entity Type * @apiParam {String} q Query String * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of entity values * @apiSuccess {String} data.value Opaque entity identifier * @apiSuccess {String} data.name User-visible name of this entity * @apiSuccess {String} data.canonical Preprocessed (tokenized and lower-cased) version of the user-visible name * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "value": "aacc", * "name": "Asset Acceptance Capital Corp.", * "canonical": "asset acceptance capital corp." * }, * { * "value": "aait", * "name": "iShares Trust iShares MSCI All Country Asia Information Techno", * "canonical": "ishares trust ishares msci all country asia information techno" * }, * { * "value": "aame", * "name": "Atlantic American Corporation", * "canonical": "atlantic american corporation" * }, * ... * ] * } * */ v3.get('/entities/list/:type', (req, res, next) => { db.withClient((dbClient) => { return entityModel.getValues(dbClient, req.params.type); }).then((rows) => { res.cacheFor(86400000); res.status(200).json({ result: 'ok', data: rows.map((r) => ({ value: r.entity_value, name: r.entity_name, canonical: r.entity_canonical })) }); }).catch(next); }); function getAllStrings(req : express.Request<any, any, any, { developer_key ?: string, locale ?: string, thingtalk_version ?: string }>, res : express.Response, next : express.NextFunction) { const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getAllStrings().then((data) => { if (data.length > 0) res.cacheFor(6, 'months'); else res.cacheFor(86400000); res.status(200).json({ result: 'ok', data }); }).catch(next); } /** * @api {get} /v3/strings/all Get List of String Datasets * @apiName GetAllStrings * @apiGroup String Dataset * @apiVersion 0.3.0 * * @apiDescription Retrieve the full list of string datasets. * * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of entity types * @apiSuccess {String} data.type String dataset type * @apiSuccess {String} data.name User-visible name of this string dataset * @apiSuccess {String} data.license Software license of the string dataset * @apiSuccess {String} data.attribution Copyright and attribution, including citations of relevant papers * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "type": "tt:long_free_text", * "name": "General Text (paragraph)", * "license": "non-commercial", * "attribution": "The Brown Corpus " * }, * { * "type": "tt:path_name", * "name": "File and directory names", * "license": "public-domain", * "attribution": "" * }, * { * "type": "tt:person_first_name", * "name": "First names of people", * "license": "public-domain", * "attribution": "" * }, * ... * ] * } * */ v3.get('/strings/all', iv.validateGET(commonQueryArgs), getAllStrings); /** * @api {get} /v3/strings/list/:type List String Values * @apiName StringList * @apiGroup String Dataset * @apiVersion 0.3.0 * * @apiDescription Download the named string parameter dataset. * * @apiParam {String} type String Dataset name * @apiParam {String} developer_key Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of string values * @apiSuccess {String} data.value String value * @apiSuccess {String} data.preprocessed Tokenized form of string value * @apiSuccess {String} data.weight Weight * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "value": "the fulton county grand jury", * "weight": 1, * }, * { * "value": "took place", * "weight": 1, * }, * { * "value": "the jury further", * "weight": 1 * }, * ... * ] * } * */ v3.get('/strings/list/:type', iv.validateGET({ ...commonQueryArgs, developer_key: 'string' }), (req, res, next) => { db.withClient(async (dbClient) => { const org = (await orgModel.getByDeveloperKey(dbClient, req.query.developer_key))[0]; if (!org) throw new ForbiddenError(`A valid developer key is required to download string datasets`); const language = I18n.localeToLanguage(req.query.locale || 'en-US'); // check for the existence of this type, and also check if the dataset can be downloaded const stringType = await stringModel.getByTypeName(dbClient, req.params.type, language); if (stringType.license === 'proprietary') throw new ForbiddenError(`This dataset is proprietary and cannot be downloaded`); return stringModel.getValues(dbClient, req.params.type, language); }).then((rows) => { res.cacheFor(86400000); res.status(200).json({ result: 'ok', data: rows.map((r) => ({ value: r.value, preprocessed: r.preprocessed, weight: r.weight })) }); }).catch(next); }); /** * @api {get} /v3/locations/lookup Lookup Location By Name * @apiName LookupLocation * @apiGroup Entities * @apiVersion 0.3.0 * * @apiDescription Lookup a location given its name (also known as "geocoding"). * Use this endpoint to perform Entity Linking after identifying an span corresponding to a locationn. * * @apiParam {String} q Query String * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of candidate locations values; the list is sorted by importance * @apiSuccess {Number{-90,90}} data.latitude Latitude * @apiSuccess {Number{-180,180}} data.longitude Longitude * @apiSuccess {String} data.display User-visible name of this location * @apiSuccess {Number} data.canonical Preprocessed (tokenized and lower-cased) version of the user-visible name * * @apiSuccessExample {json} Example Response: * { * "result": "ok", * "data": [ * { * "type": "tt:stock_id", * "value": "wmt", * "canonical": "walmart inc.", * "name": "Walmart Inc." * } * ] * } * */ v3.get('/locations/lookup', iv.validateGET({ ...commonQueryArgs, q: 'string', latitude: '?number', longitude: '?number' }), (req, res, next) => { const searchKey = req.query.q; const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.lookupLocation(searchKey, req.query.latitude && req.query.longitude ? { latitude: Number(req.query.latitude), longitude: Number(req.query.longitude) } : undefined).then((data) => { res.cacheFor(300000); res.status(200).json({ result: 'ok', data }); }).catch(next); }); /** * @api {get} /v3/snapshot/:snapshot Get Thingpedia Snapshot * @apiName GetSnapshot * @apiGroup Schemas * @apiVersion 0.3.0 * * @apiDescription Retrieve the ThingTalk type information and natural language metadata * from all the devices that were present in Thingpedia at the time of the * given snapshot. * * This API performs content negotiation, based on the `Accept` header. If * the `Accept` header is unset or set to `application/x-thingtalk`, then a ThingTalk * meta file is returned. Otherwise, the accept header must be set to `application/json`, * or a 405 Not Acceptable error occurs. * * @apiParam {Number} snapshot The numeric Thingpedia snapshot identifier. Use -1 to refer to * the current contents of Thingpedia. * @apiParam {Number{0-1}} meta Include natural language metadata in the output * @apiParam {String} [developer_key] Developer key to use for this operation * @apiParam {String} [locale=en-US] Locale in which metadata should be returned * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * @apiSuccess {Object[]} data List of schemas * @apiSuccess {Object} data.id Each schema * @apiSuccess {Object} data.id.triggers The triggers in this schema (obsolete, and always empty) * @apiSuccess {Object} data.id.queries The queries in this schema * @apiSuccess {Object} data.id.actions The actions in this schema * @apiSuccess {String[]} data.id.actions.args The names of all parameters of this functions * @apiSuccess {String[]} data.id.actions.types The ThingTalk type of all parameters of this function * @apiSuccess {Boolean[]} data.id.actions.required For each parameter, the corresponding element in this array is `true` if the parameter is required, and `false` otherwise * @apiSuccess {Boolean[]} data.id.actions.is_input For each parameter, the corresponding element in this array is `true` if the parameter is an input parameter, and `false` otherwise if the parameter is an output * @apiSuccess {Boolean} data.id.actions.is_list Whether this function returns a list; this is always false for actions * @apiSuccess {Boolean} data.id.actions.is_monitorable Whether this function can be monitored; this is always false for actions * @apiSuccess {String} data.id.confirmation Confirmation string for this function * @apiSuccess {String} data.id.confirmation_remote Remote confirmation string (obsolete) * @apiSuccess {String} data.id.doc Documentation string for this function, to be shown eg. in a reference manual for the device * @apiSuccess {String} data.id.canonical Short, concise description of this function, omitting stop words * @apiSuccess {String[]} data.id.argcanonicals Translated argument names, to be used to construct sentences and display to the user; one element per argument * @apiSuccess {String[]} data.id.questions Slot-filling questions * **/ function getSnapshot(req : express.Request<any, any, any, { locale ?: string, developer_key ?: string; thingtalk_version ?: string; meta ?: string; }>, res : express.Response, next : express.NextFunction, accept : string) { const getMeta = req.query.meta === '1'; const language = (req.query.locale || 'en').split(/[-_@.]/)[0]; const snapshotId = parseInt(req.params.id); const developerKey = req.query.developer_key; const etag = `"snapshot-${snapshotId}-meta:${getMeta}-lang:${language}-developerKey:${developerKey}"`; if (snapshotId >= 0 && req.headers['if-none-match'] === etag) { res.set('ETag', etag); res.status(304).send(''); return; } const client = new ThingpediaClient(req.query.developer_key, req.query.locale, req.query.thingtalk_version); client.getThingpediaSnapshot(getMeta, snapshotId).then((rows) => { if (rows.length > 0 && snapshotId >= 0) { res.cacheFor(6, 'months'); res.set('ETag', etag); } else { res.cacheFor(3600000); } res.set('Content-Type', accept === 'text/html' ? 'text/plain' : accept); res.send(ThingTalk.Syntax.serialize(SchemaUtils.schemaListToClassDefs(rows, getMeta), ThingTalk.Syntax.SyntaxType.Normal, undefined, { compatibility: req.query.thingtalk_version })); }).catch(next); } v3.get('/snapshot/:id', iv.validateGET({ ...commonQueryArgs, meta: '?string' }), (req, res, next) => { const accept = accepts(req).types(['application/x-thingtalk', 'text/html']); if (!accept) { res.status(405).json({ error: 'must accept application/x-thingtalk' }); return; } res.set('Vary', 'Accept'); getSnapshot(req, res, next, accept as string); }); // the POST apis below require OAuth v3.use((req, res, next) => { if (typeof req.query.access_token === 'string' || (req.headers['authorization'] && req.headers['authorization'].startsWith('Bearer '))) passport.authenticate('bearer', {session: false})(req, res, next); else next(new AuthenticationError()); }); /** * @api {post} /v3/entities/create Create a new entity type * @apiName NewEntity * @apiGroup Entities * @apiVersion 0.3.0 * * @apiDescription Create a new entity type. * * @apiParam {String} entity_id The ID of the entity to create * @apiParam {String} entity_name The name of the entity * @apiParam {Boolean} no_ner_support If this entity is an opaque identifier that cannot be used from natural language * @apiParam {File} [upload] A CSV file with all the values of this entity, * one per line, formatted as "value, name" * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * */ v3.post('/entities/create', userUtils.requireScope('developer-upload'), multer({ dest: os.tmpdir() }).single('upload'), iv.validatePOST({ entity_id: 'string', entity_name: 'string', no_ner_support: 'boolean' }, { json: true }), (req, res, next) => { uploadEntities(req).then(() => { res.json({ result: 'ok' }); }).catch(next); }); /** * @api {post} /v3/devices/create Create or update a new device class * @apiName NewDevice * @apiGroup Devices * @apiVersion 0.3.0 * * @apiDescription Create a new device class, or update an existing device class. * * @apiParam {String} primary_kind The ID of the device to create or update * @apiParam {String} name The name of the device in Thingpedia * @apiParam {String} description The description of the device in Thingpedia * @apiParam {String} license The SPDX identifier of the license of the code * @apiParam {Boolean} license_gplcompatible Whether the license is GPL-compatible * @apiParam {String} [website] A URL of a website associated with this device or service * @apiParam {String} [repository] A link to a public source code repository for the device * @apiParam {String} [issue_tracker] A link to page where users can report bugs for the device * @apiParam {String="home","data-management","communication","social-network","health","media","service"} subcategory The general domain of this device * @apiParam {String} code The ThingTalk class definition for this device * @apiParam {String} dataset The ThingTalk dataset definition for this device * @apiParam {File} [zipfile] The ZIP file containing the source code for this device * @apiParam {File} [icon] A PNG or JPEG file to use as the icon for this device; preferred size is 512x512 * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * */ const deviceCreateArguments = { primary_kind: 'string', name: 'string', description: 'string', license: 'string', license_gplcompatible: 'boolean', website: '?string', repository: '?string', issue_tracker: '?string', subcategory: 'string', code: 'string', dataset: 'string', approve: 'boolean' } as const; v3.post('/devices/create', userUtils.requireScope('developer-upload'), multer({ dest: os.tmpdir() }).fields([ { name: 'zipfile', maxCount: 1 }, { name: 'icon', maxCount: 1 } ]), iv.validatePOST(deviceCreateArguments, { json: true }), (req, res, next) => { uploadDevice(req).then(() => { res.json({ result: 'ok' }); }).catch(next); }); /** * @api {post} /v3/strings/upload Upload a new string dataset * @apiName NewStringDataset * @apiGroup String Dataset * @apiVersion 0.3.0 * * @apiDescription Upload a new string dataset * * @apiParam {String} type_name The ID of the dataset * @apiParam {String} name The name of the dataset * @apiParam {File} upload A TSV file with all the value for this entity, * one per line, formatted as "value<tab>weight", where value is the string value and * weight is the unnormalized sampling probability for this value. * Including weights in the file is optional. * If the weights are provided, the dataset used for training will reflect the given distribution. * If weights are omitted for any row, they default to 1.0. * @apiParam {Boolean} preprocessed If this value in the file is tokenized * @apiParam {String} license The license of the dataset * @apiParam {String} [attribution] Use this field to provide details of the copyright and attribution, * including any citations of relevant papers. * * @apiSuccess {String} result Whether the API call was successful; always the value `ok` * */ v3.post('/strings/upload', userUtils.requireScope('developer-upload'), multer({ dest: os.tmpdir() }).single('upload'), iv.validatePOST({ type_name: 'string', name: 'string', license: 'string', attribution: '?string', preprocessed: 'boolean' }, { json: true }), (req, res, next) => { uploadStringDataset(req).then(() => { res.json({ result: 'ok' }); }).catch(next); }); everything.use('/v3', v3); // if nothing handled the route, return a 404 everything.use('/', (req, res) => { res.status(404).json({ error: 'Invalid endpoint' }); }); // if something failed, return a 500 in json form, or the appropriate status code everything.use(errorHandling.json); export default everything;
the_stack
import { LengthPercentage, Length, Angle, RBType } from '..' import { serializeAtomicValue } from '../shared' const isMatrix = (x: TransformFunction): x is TransformFunction<'matrix'> => x.valueConstructor === TransformFunction.matrix const isMatrix3d = (x: TransformFunction): x is TransformFunction<'matrix3d'> => x.valueConstructor === TransformFunction.matrix3d const isPerspective = ( x: TransformFunction, ): x is TransformFunction<'perspective'> => x.valueConstructor === TransformFunction.perspective const isRotateX = (x: TransformFunction): x is TransformFunction<'rotateX'> => x.valueConstructor === TransformFunction.rotateX const isRotateY = (x: TransformFunction): x is TransformFunction<'rotateY'> => x.valueConstructor === TransformFunction.rotateY const isRotateZ = (x: TransformFunction): x is TransformFunction<'rotateZ'> => x.valueConstructor === TransformFunction.rotateZ const isRotate = (x: TransformFunction): x is TransformFunction<'rotate'> => x.valueConstructor === TransformFunction.rotate const isRotate3d = (x: TransformFunction): x is TransformFunction<'rotate3d'> => x.valueConstructor === TransformFunction.rotate3d const isScaleX = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.scaleX const isScaleY = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.scaleY const isScaleZ = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.scaleZ const isScale = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.scale const isScale3d = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.scale3d const isSkewX = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.skewX const isSkewY = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.skewY const isSkew = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.skew const isTranslateX = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.translateX const isTranslateY = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.translateY const isTranslateZ = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.translateZ const isTranslate = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.translate const isTranslate3d = (x: TransformFunction): boolean => x.valueConstructor === TransformFunction.translate3d const serializeSkewX = (x: TransformFunction<'skewX'>): string => `skewX(${serializeAtomicValue(x.data)})` const serializeSkewY = (x: TransformFunction<'skewY'>): string => `skewY(${serializeAtomicValue(x.data)})` const serializeSkew = (x: TransformFunction<'skew'>): string => `skew(${serializeAtomicValue(x.data[0])}${ x.data[1] ? `, ${serializeAtomicValue(x.data[1])}` : '' })` const serializeMatrix = (x: TransformFunction<'matrix'>): string => `matrix(${x.data.reduce( (acc, val, idx) => idx !== x.data.length - 1 ? acc + `${val}, ` : acc + val, '', )})` const serializeMatrix3d = (x: TransformFunction<'matrix3d'>): string => `matrix3d(${x.data.reduce( (acc, val, idx) => idx !== x.data.length - 1 ? acc + `${val}, ` : acc + val, '', )})` const serializePerspective = (x: TransformFunction<'perspective'>): string => `perspective(${serializeAtomicValue(x.data)})` const serializeScaleX = (x: TransformFunction<'scaleX'>): string => `scaleX(${x.data})` const serializeScaleY = (x: TransformFunction<'scaleY'>): string => `scaleY(${x.data})` const serializeScaleZ = (x: TransformFunction<'scaleZ'>): string => `scaleZ(${x.data})` const serializeScale = (x: TransformFunction<'scale'>): string => `scale(${x.data[0]}${x.data[1] ? `, ${x.data[1]}` : ''})` const serializeScale3d = (x: TransformFunction<'scale3d'>): string => `scale3d(${x.data[0]}, ${x.data[1]}, ${x.data[2]})` const serializeRotateX = (x: TransformFunction<'rotateX'>): string => `rotateX(${serializeAtomicValue(x.data)})` const serializeRotateY = (x: TransformFunction<'rotateY'>): string => `rotateY(${serializeAtomicValue(x.data)})` const serializeRotateZ = (x: TransformFunction<'rotateZ'>): string => `rotateZ(${serializeAtomicValue(x.data)})` const serializeRotate = (x: TransformFunction<'rotate'>): string => `rotate(${serializeAtomicValue(x.data)})` const serializeRotate3d = (x: TransformFunction<'rotate3d'>): string => { const [x0, x1, x2, x3] = x.data return `rotate3d(${x0}, ${x1}, ${x2}, ${serializeAtomicValue(x3)})` } const serializeTranslateX = (x: TransformFunction<'translateX'>): string => `translateX(${serializeAtomicValue(x.data[0])})` const serializeTranslateY = (value: TransformFunction<'translateY'>): string => `translateY(${serializeAtomicValue(value.data[0])})` const serializeTranslateZ = (value: TransformFunction<'translateZ'>): string => `translateZ(${serializeAtomicValue(value.data[0])})` const serializeTranslate = (value: TransformFunction<'translate'>): string => { const xAxis = serializeAtomicValue(value.data[0]) const yAxis = value.data[1] ? `, ${serializeAtomicValue(value.data[1])}` : '' const zAxis = value.data[2] ? `, ${serializeAtomicValue(value.data[2])}` : '' return `translate(${xAxis}${yAxis}${zAxis})` } const serializeTranslate3d = ( value: TransformFunction<'translate3d'>, ): string => `translate3d(${serializeAtomicValue(value.data[0])}, ${serializeAtomicValue( value.data[1], )}, ${serializeAtomicValue(value.data[2])})` const serializeTransformFunction = (x: TransformFunction): string => { if (isMatrix(x)) return serializeMatrix(x) if (isMatrix3d(x)) return serializeMatrix3d(x) if (isPerspective(x)) return serializePerspective(x) if (isRotateX(x)) return serializeRotateX(x) if (isRotateY(x)) return serializeRotateY(x) if (isRotateZ(x)) return serializeRotateZ(x) if (isRotate(x)) return serializeRotate(x) if (isRotate3d(x)) return serializeRotate3d(x) if (isScaleX(x)) return serializeScaleX(x) if (isScaleY(x)) return serializeScaleY(x) if (isScaleZ(x)) return serializeScaleZ(x) if (isScale(x)) return serializeScale(x) if (isScale(x)) return serializeScale(x) if (isScale3d(x)) return serializeScale3d(x) if (isSkewX(x)) return serializeSkewX(x) if (isSkewY(x)) return serializeSkewY(x) if (isSkew(x)) return serializeSkew(x) if (isTranslateX(x)) return serializeTranslateX(x) if (isTranslateY(x)) return serializeTranslateY(x) if (isTranslateZ(x)) return serializeTranslateZ(x) if (isTranslate(x)) return serializeTranslate(x) if (isTranslate3d(x)) return serializeTranslate3d(x) throw new Error('Unrecognized type') } type TransformationType = | 'scaleX' | 'scaleY' | 'scaleZ' | 'scale' | 'scale3d' | 'translateX' | 'translateY' | 'translateZ' | 'translate' | 'translate3d' | 'rotateX' | 'rotateY' | 'rotateZ' | 'rotate' | 'rotate3d' | 'skewX' | 'skewY' | 'skew' | 'matrix' | 'matrix3d' | 'perspective' /** * * A type that maps to CSS's **`<transform-function>`** type. */ export class TransformFunction< A extends TransformationType = TransformationType > implements RBType<any> { serialize: () => string valueConstructor: Function data: A extends 'translateX' ? [LengthPercentage] : A extends 'translateY' ? [LengthPercentage] : A extends 'translateZ' ? [Length] : A extends 'translate' ? | [LengthPercentage] | [LengthPercentage, LengthPercentage] | [LengthPercentage, LengthPercentage, LengthPercentage] : A extends 'translate3d' ? [LengthPercentage, LengthPercentage, LengthPercentage] : A extends 'scaleX' ? number : A extends 'scaleY' ? number : A extends 'scaleZ' ? number : A extends 'scale' ? [number] | [number, number] : A extends 'scale3d' ? [number, number, number] : A extends 'rotateX' ? Angle : A extends 'rotateY' ? Angle : A extends 'rotateZ' ? Angle : A extends 'rotate' ? Angle : A extends 'rotate3d' ? [number, number, number, Angle] : A extends 'skewX' ? Angle : A extends 'skewY' ? Angle : A extends 'skew' ? [Angle] | [Angle, Angle] : A extends 'matrix' ? [number, number, number, number, number, number] : A extends 'matrix3d' ? [ number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, ] : A extends 'perspective' ? Length : any private constructor(data: any, valueConstructor: Function) { this.data = data this.valueConstructor = valueConstructor this.serialize = () => serializeTransformFunction(this) } /** Constructs a value of type **`TransformFunction<'matrix'>`**. */ static matrix( x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, ): TransformFunction<'matrix'> { return new TransformFunction( [x1, x2, x3, x4, x5, x6], TransformFunction.matrix, ) } /** Constructs a value of type **`TransformFunction<'matrix3d'>`**. */ static matrix3d( x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number, x8: number, x9: number, x10: number, x11: number, x12: number, x13: number, x14: number, x15: number, x16: number, ): TransformFunction<'matrix3d'> { return new TransformFunction( [ x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, ], TransformFunction.matrix3d, ) } /** Constructs a value of type **`TransformFunction<'perspective'>`**. */ static perspective(x: Length): TransformFunction<'perspective'> { return new TransformFunction(x, TransformFunction.perspective) } /** Constructs a value of type **`TransformFunction<'rotateX'>`**. */ static rotateX(x: Angle): TransformFunction<'rotateX'> { return new TransformFunction(x, TransformFunction.rotateX) } /** Constructs a value of type **`TransformFunction<'rotateY'>`**. */ static rotateY(x: Angle): TransformFunction<'rotateY'> { return new TransformFunction(x, TransformFunction.rotateY) } /** Constructs a value of type **`TransformFunction<'rotateZ'>`**. */ static rotateZ(x: Angle): TransformFunction<'rotateZ'> { return new TransformFunction(x, TransformFunction.rotateZ) } /** Constructs a value of type **`TransformFunction<'rotate'>`**. */ static rotate(x: Angle): TransformFunction<'rotate'> { return new TransformFunction(x, TransformFunction.rotate) } /** Constructs a value of type **`TransformFunction<'rotate3d'>`**. */ static rotate3d( x: number, y: number, z: number, a: Angle, ): TransformFunction<'rotate3d'> { return new TransformFunction([x, y, z, a], TransformFunction.rotate3d) } /** Constructs a value of type **`TransformFunction<'scaleX'>`**. */ static scaleX(x: number): TransformFunction<'scaleX'> { return new TransformFunction(x, TransformFunction.scaleX) } /** Constructs a value of type **`TransformFunction<'scaleY'>`**. */ static scaleY(x: number): TransformFunction<'scaleY'> { return new TransformFunction(x, TransformFunction.scaleY) } /** Constructs a value of type **`TransformFunction<'scaleZ'>`**. */ static scaleZ(x: number): TransformFunction<'scaleZ'> { return new TransformFunction(x, TransformFunction.scaleZ) } /** Constructs a value of type **`TransformFunction<'scale'>`**. */ static scale(x: number, y?: number): TransformFunction<'scale'> { return new TransformFunction(y ? [x, y] : [x], TransformFunction.scale) } /** Constructs a value of type **`TransformFunction<'scale3d'>`**. */ static scale3d( x: number, y: number, z: number, ): TransformFunction<'scale3d'> { return new TransformFunction([x, y, z], TransformFunction.scale3d) } /** Constructs a value of type **`TransformFunction<'skewX'>`**. */ static skewX(x: Angle): TransformFunction<'skewX'> { return new TransformFunction(x, TransformFunction.skewX) } /** Constructs a value of type **`TransformFunction<'skewY'>`**. */ static skewY(x: Angle): TransformFunction<'skewY'> { return new TransformFunction(x, TransformFunction.skewY) } /** Constructs a value of type **`TransformFunction<'skew'>`**. */ static skew(x: Angle, y?: Angle): TransformFunction<'skew'> { return new TransformFunction(y ? [x, y] : [x], TransformFunction.skew) } /** Constructs a value of type **`TransformFunction<'translateX'>`**. */ static translateX(x: LengthPercentage): TransformFunction<'translateX'> { return new TransformFunction([x], TransformFunction.translateX) } /** Constructs a value of type **`TransformFunction<'translateY'>`**. */ static translateY(x: LengthPercentage): TransformFunction<'translateY'> { return new TransformFunction([x], TransformFunction.translateY) } /** Constructs a value of type **`TransformFunction<'translateZ'>`**. */ static translateZ(x: LengthPercentage): TransformFunction<'translateZ'> { return new TransformFunction([x], TransformFunction.translateZ) } /** Constructs a value of type **`TransformFunction<'translate'>`**. */ static translate( x: LengthPercentage, y?: LengthPercentage, z?: LengthPercentage, ): TransformFunction<'translate'> { return new TransformFunction([x, y, z], TransformFunction.translate) } /** Constructs a value of type **`TransformFunction<'translate3d'>`**. */ static translate3d( x: LengthPercentage, y: LengthPercentage, z: LengthPercentage, ): TransformFunction<'translate3d'> { return new TransformFunction([x, y, z], TransformFunction.translate3d) } } /** * Constructs a value of type **`TransformFunction<'matrix'>`**. * @category Value constructor */ export const matrix = TransformFunction.matrix /** * Constructs a value of type **`TransformFunction<'matrix3d'>`**. * @category Value constructor */ export const matrix3d = TransformFunction.matrix3d /** * Constructs a value of type **`TransformFunction<'perspective'>`**. * @category Value constructor */ export const perspective = TransformFunction.perspective /** * Constructs a value of type **`TransformFunction<'rotateX'>`**. * @category Value constructor */ export const rotateX = TransformFunction.rotateX /** * Constructs a value of type **`TransformFunction<'rotateY'>`**. * @category Value constructor */ export const rotateY = TransformFunction.rotateY /** * Constructs a value of type **`TransformFunction<'rotateZ'>`**. * @category Value constructor */ export const rotateZ = TransformFunction.rotateZ /** * Constructs a value of type **`TransformFunction<'rotate'>`**. * @category Value constructor */ export const rotate = TransformFunction.rotate /** * Constructs a value of type **`TransformFunction<'rotate3d'>`**. * @category Value constructor */ export const rotate3d = TransformFunction.rotate3d /** * Constructs a value of type **`TransformFunction<'scaleX'>`**. * @category Value constructor */ export const scaleX = TransformFunction.scaleX /** * Constructs a value of type **`TransformFunction<'scaleY'>`**. * @category Value constructor */ export const scaleY = TransformFunction.scaleY /** * Constructs a value of type **`TransformFunction<'scaleZ'>`**. * @category Value constructor */ export const scaleZ = TransformFunction.scaleZ /** * Constructs a value of type **`TransformFunction<'scale'>`**. * @category Value constructor */ export const scale = TransformFunction.scale /** * Constructs a value of type **`TransformFunction<'scale3d'>`**. * @category Value constructor */ export const scale3d = TransformFunction.scale3d /** * Constructs a value of type **`TransformFunction<'skewX'>`**. * @category Value constructor */ export const skewX = TransformFunction.skewX /** * Constructs a value of type **`TransformFunction<'skewY'>`**. * @category Value constructor */ export const skewY = TransformFunction.skewY /** * Constructs a value of type **`TransformFunction<'skew'>`**. * @category Value constructor */ export const skew = TransformFunction.skew /** * Constructs a value of type **`TransformFunction<'translateX'>`**. * @category Value constructor */ export const translateX = TransformFunction.translateX /** * Constructs a value of type **`TransformFunction<'translateY'>`**. * @category Value constructor */ export const translateY = TransformFunction.translateY /** * Constructs a value of type **`TransformFunction<'translateZ'>`**. * @category Value constructor */ export const translateZ = TransformFunction.translateZ /** * Constructs a value of type **`TransformFunction<'translate'>`**. * @category Value constructor */ export const translate = TransformFunction.translate /** * Constructs a value of type **`TransformFunction<'translate3d'>`**. * @category Value constructor */ export const translate3d = TransformFunction.translate3d
the_stack
import { ApiResponse, RequestOptions } from '../core'; import { AddGroupToCustomerResponse, addGroupToCustomerResponseSchema, } from '../models/addGroupToCustomerResponse'; import { CreateCustomerCardRequest, createCustomerCardRequestSchema, } from '../models/createCustomerCardRequest'; import { CreateCustomerCardResponse, createCustomerCardResponseSchema, } from '../models/createCustomerCardResponse'; import { CreateCustomerRequest, createCustomerRequestSchema, } from '../models/createCustomerRequest'; import { CreateCustomerResponse, createCustomerResponseSchema, } from '../models/createCustomerResponse'; import { DeleteCustomerCardResponse, deleteCustomerCardResponseSchema, } from '../models/deleteCustomerCardResponse'; import { DeleteCustomerResponse, deleteCustomerResponseSchema, } from '../models/deleteCustomerResponse'; import { ListCustomersResponse, listCustomersResponseSchema, } from '../models/listCustomersResponse'; import { RemoveGroupFromCustomerResponse, removeGroupFromCustomerResponseSchema, } from '../models/removeGroupFromCustomerResponse'; import { RetrieveCustomerResponse, retrieveCustomerResponseSchema, } from '../models/retrieveCustomerResponse'; import { SearchCustomersRequest, searchCustomersRequestSchema, } from '../models/searchCustomersRequest'; import { SearchCustomersResponse, searchCustomersResponseSchema, } from '../models/searchCustomersResponse'; import { UpdateCustomerRequest, updateCustomerRequestSchema, } from '../models/updateCustomerRequest'; import { UpdateCustomerResponse, updateCustomerResponseSchema, } from '../models/updateCustomerResponse'; import { bigint, number, optional, string } from '../schema'; import { BaseApi } from './baseApi'; export class CustomersApi extends BaseApi { /** * Lists customer profiles associated with a Square account. * * Under normal operating conditions, newly created or updated customer profiles become available * for the listing operation in well under 30 seconds. Occasionally, propagation of the new or updated * profiles can take closer to one minute or longer, especially during network incidents and outages. * * @param cursor A pagination cursor returned by a previous call to this endpoint. Provide this cursor * to retrieve the next set of results for your original query. For more information, * see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination). * @param limit The maximum number of results to return in a single page. This limit is advisory. The * response might contain more or fewer results. The limit is ignored if it is less than * 1 or greater than 100. The default value is 100. For more information, see * [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination). * @param sortField Indicates how customers should be sorted. The default value is `DEFAULT`. * @param sortOrder Indicates whether customers should be sorted in ascending (`ASC`) or descending * (`DESC`) order. The default value is `ASC`. * @return Response from the API call */ async listCustomers( cursor?: string, limit?: number, sortField?: string, sortOrder?: string, requestOptions?: RequestOptions ): Promise<ApiResponse<ListCustomersResponse>> { const req = this.createRequest('GET', '/v2/customers'); const mapped = req.prepareArgs({ cursor: [cursor, optional(string())], limit: [limit, optional(number())], sortField: [sortField, optional(string())], sortOrder: [sortOrder, optional(string())], }); req.query('cursor', mapped.cursor); req.query('limit', mapped.limit); req.query('sort_field', mapped.sortField); req.query('sort_order', mapped.sortOrder); return req.callAsJson(listCustomersResponseSchema, requestOptions); } /** * Creates a new customer for a business. * * You must provide at least one of the following values in your request to this * endpoint: * * - `given_name` * - `family_name` * - `company_name` * - `email_address` * - `phone_number` * * @param body An object containing the fields to POST for the request. See the * corresponding object definition for field details. * @return Response from the API call */ async createCustomer( body: CreateCustomerRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<CreateCustomerResponse>> { const req = this.createRequest('POST', '/v2/customers'); const mapped = req.prepareArgs({ body: [body, createCustomerRequestSchema], }); req.json(mapped.body); return req.callAsJson(createCustomerResponseSchema, requestOptions); } /** * Searches the customer profiles associated with a Square account using a supported query filter. * * Calling `SearchCustomers` without any explicit query filter returns all * customer profiles ordered alphabetically based on `given_name` and * `family_name`. * * Under normal operating conditions, newly created or updated customer profiles become available * for the search operation in well under 30 seconds. Occasionally, propagation of the new or updated * profiles can take closer to one minute or longer, especially during network incidents and outages. * * @param body An object containing the fields to POST for the request. See the * corresponding object definition for field details. * @return Response from the API call */ async searchCustomers( body: SearchCustomersRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<SearchCustomersResponse>> { const req = this.createRequest('POST', '/v2/customers/search'); const mapped = req.prepareArgs({ body: [body, searchCustomersRequestSchema], }); req.json(mapped.body); return req.callAsJson(searchCustomersResponseSchema, requestOptions); } /** * Deletes a customer profile from a business. This operation also unlinks any associated cards on file. * * * As a best practice, you should include the `version` field in the request to enable [optimistic * concurrency](https://developer.squareup.com/docs/working-with-apis/optimistic-concurrency) control. * The value must be set to the current version of the customer profile. * * To delete a customer profile that was created by merging existing profiles, you must use the ID of * the newly created profile. * * @param customerId The ID of the customer to delete. * @param version The current version of the customer profile. As a best practice, you should include * this parameter to enable [optimistic concurrency](https://developer.squareup. * com/docs/working-with-apis/optimistic-concurrency) control. For more information, * see [Delete a customer profile](https://developer.squareup.com/docs/customers-api/use- * the-api/keep-records#delete-customer-profile). * @return Response from the API call */ async deleteCustomer( customerId: string, version?: bigint, requestOptions?: RequestOptions ): Promise<ApiResponse<DeleteCustomerResponse>> { const req = this.createRequest('DELETE'); const mapped = req.prepareArgs({ customerId: [customerId, string()], version: [version, optional(bigint())], }); req.query('version', mapped.version); req.appendTemplatePath`/v2/customers/${mapped.customerId}`; return req.callAsJson(deleteCustomerResponseSchema, requestOptions); } /** * Returns details for a single customer. * * @param customerId The ID of the customer to retrieve. * @return Response from the API call */ async retrieveCustomer( customerId: string, requestOptions?: RequestOptions ): Promise<ApiResponse<RetrieveCustomerResponse>> { const req = this.createRequest('GET'); const mapped = req.prepareArgs({ customerId: [customerId, string()] }); req.appendTemplatePath`/v2/customers/${mapped.customerId}`; return req.callAsJson(retrieveCustomerResponseSchema, requestOptions); } /** * Updates a customer profile. To change an attribute, specify the new value. To remove an attribute, * specify the value as an empty string or empty object. * * As a best practice, you should include the `version` field in the request to enable [optimistic * concurrency](https://developer.squareup.com/docs/working-with-apis/optimistic-concurrency) control. * The value must be set to the current version of the customer profile. * * To update a customer profile that was created by merging existing profiles, you must use the ID of * the newly created profile. * * You cannot use this endpoint to change cards on file. To make changes, use the [Cards API]($e/Cards) * or [Gift Cards API]($e/GiftCards). * * @param customerId The ID of the customer to update. * @param body An object containing the fields to POST for the request. See * the corresponding object definition for field details. * @return Response from the API call */ async updateCustomer( customerId: string, body: UpdateCustomerRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<UpdateCustomerResponse>> { const req = this.createRequest('PUT'); const mapped = req.prepareArgs({ customerId: [customerId, string()], body: [body, updateCustomerRequestSchema], }); req.json(mapped.body); req.appendTemplatePath`/v2/customers/${mapped.customerId}`; return req.callAsJson(updateCustomerResponseSchema, requestOptions); } /** * Adds a card on file to an existing customer. * * As with charges, calls to `CreateCustomerCard` are idempotent. Multiple * calls with the same card nonce return the same card record that was created * with the provided nonce during the _first_ call. * * @param customerId The Square ID of the customer profile the card is linked * to. * @param body An object containing the fields to POST for the request. * See the corresponding object definition for field details. * @return Response from the API call * @deprecated */ async createCustomerCard( customerId: string, body: CreateCustomerCardRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<CreateCustomerCardResponse>> { const req = this.createRequest('POST'); const mapped = req.prepareArgs({ customerId: [customerId, string()], body: [body, createCustomerCardRequestSchema], }); req.json(mapped.body); req.appendTemplatePath`/v2/customers/${mapped.customerId}/cards`; req.deprecated('CustomersApi.createCustomerCard'); return req.callAsJson(createCustomerCardResponseSchema, requestOptions); } /** * Removes a card on file from a customer. * * @param customerId The ID of the customer that the card on file belongs to. * @param cardId The ID of the card on file to delete. * @return Response from the API call * @deprecated */ async deleteCustomerCard( customerId: string, cardId: string, requestOptions?: RequestOptions ): Promise<ApiResponse<DeleteCustomerCardResponse>> { const req = this.createRequest('DELETE'); const mapped = req.prepareArgs({ customerId: [customerId, string()], cardId: [cardId, string()], }); req.appendTemplatePath`/v2/customers/${mapped.customerId}/cards/${mapped.cardId}`; req.deprecated('CustomersApi.deleteCustomerCard'); return req.callAsJson(deleteCustomerCardResponseSchema, requestOptions); } /** * Removes a group membership from a customer. * * The customer is identified by the `customer_id` value * and the customer group is identified by the `group_id` value. * * @param customerId The ID of the customer to remove from the group. * @param groupId The ID of the customer group to remove the customer from. * @return Response from the API call */ async removeGroupFromCustomer( customerId: string, groupId: string, requestOptions?: RequestOptions ): Promise<ApiResponse<RemoveGroupFromCustomerResponse>> { const req = this.createRequest('DELETE'); const mapped = req.prepareArgs({ customerId: [customerId, string()], groupId: [groupId, string()], }); req.appendTemplatePath`/v2/customers/${mapped.customerId}/groups/${mapped.groupId}`; return req.callAsJson( removeGroupFromCustomerResponseSchema, requestOptions ); } /** * Adds a group membership to a customer. * * The customer is identified by the `customer_id` value * and the customer group is identified by the `group_id` value. * * @param customerId The ID of the customer to add to a group. * @param groupId The ID of the customer group to add the customer to. * @return Response from the API call */ async addGroupToCustomer( customerId: string, groupId: string, requestOptions?: RequestOptions ): Promise<ApiResponse<AddGroupToCustomerResponse>> { const req = this.createRequest('PUT'); const mapped = req.prepareArgs({ customerId: [customerId, string()], groupId: [groupId, string()], }); req.appendTemplatePath`/v2/customers/${mapped.customerId}/groups/${mapped.groupId}`; return req.callAsJson(addGroupToCustomerResponseSchema, requestOptions); } }
the_stack
import Interceptor from '../network/Interceptor' import { Browser } from './Browser' import { EmptyReporter, IReporter, Status, StepResult } from '@flood/element-report' import { ObjectTrace } from '../utils/ObjectTrace' import { TestObserver, NullTestObserver, LifecycleObserver, ErrorObserver, InnerObserver, TimingObserver, Context, NetworkRecordingTestObserver, } from './test-observers' import { AnyErrorData, EmptyErrorData, AssertionErrorData } from './errors/Types' import { Step, StepRecoveryObject } from './Step' import { Looper } from '../Looper' import { CancellationToken } from '../utils/CancellationToken' import { TestSettings, ConcreteTestSettings, DEFAULT_STEP_WAIT_MILLISECONDS, normalizeSettings, DEFAULT_SETTINGS, } from './Settings' import { ITest } from '../interface/ITest' import { EvaluatedScriptLike } from './EvaluatedScriptLike' import { PlaywrightClientLike } from '../driver/Playwright' import { ScreenshotOptions } from '../page/types' import { Hook, HookBase, HookType } from './StepLifeCycle' import StepIterator from './StepIterator' import { getNumberWithOrdinal } from '../utils/numerical' import { StructuredError } from '../utils/StructuredError' import termImg from 'term-img' import chalk from 'chalk' import { basename } from 'path' // eslint-disable-next-line @typescript-eslint/no-var-requires const debug = require('debug')('element:runtime:test') export default class Test implements ITest { public settings: ConcreteTestSettings public steps: Step[] public hook: Hook public recoverySteps: StepRecoveryObject public runningBrowser: Browser<Step> | null public requestInterceptor: Interceptor public iteration = 0 public failed: boolean public stepCount: number public summaryStep: StepResult[] = [] private hookMode = false private testCancel: () => Promise<void> = async () => { return } get skipping(): boolean { return this.failed } constructor( public client: PlaywrightClientLike, public script: EvaluatedScriptLike, public reporter: IReporter = new EmptyReporter(), settingsFromConfig: TestSettings, settingsOverride: TestSettings, public testObserverFactory: (t: TestObserver) => TestObserver = (x) => x ) { this.script = script try { const { settings, steps, recoverySteps, hook } = script this.settings = normalizeSettings({ ...DEFAULT_SETTINGS, ...settingsFromConfig, ...settings, ...settingsOverride, }) as ConcreteTestSettings this.steps = steps this.recoverySteps = recoverySteps this.hook = hook // Adds output for console in script script.bindTest(this) } catch (err) { // XXX parsing errors. Lift to StructuredError? throw this.script.maybeLiftError(err) } this.requestInterceptor = new Interceptor(this.settings.blockedDomains || []) } public async cancel() { this.failed = true await this.testCancel() } public async beforeRun(): Promise<void> { debug('beforeRun()') await this.script.beforeTestRun() } public summarizeStep(): StepResult[] { return this.summaryStep } public resetSummarizeStep(): void { this.summaryStep = [] } /** * Runs the group of steps * @return {Promise<void|Error>} */ public async run(iteration?: number): Promise<void> | never { await this.runWithCancellation( iteration || 0, new CancellationToken(), new Looper(this.settings) ) } public async runWithCancellation( iteration: number, cancelToken: CancellationToken, looper: Looper ): Promise<void> { console.assert(this.client, `client is not configured in Test`) const ctx = new Context() const testObserver = new ErrorObserver( new LifecycleObserver( this.testObserverFactory( new TimingObserver( ctx, new NetworkRecordingTestObserver(ctx, new InnerObserver(new NullTestObserver())) ) ) ) ) await this.requestInterceptor.attach(this.client.page) this.testCancel = async () => { await testObserver.after(this) } this.failed = false this.runningBrowser = null this.reporter.worker?.setIteration(iteration) debug('run() start') const { testData } = this.script const stepIterator = new StepIterator(this.steps) const browser = new Browser<Step>(this.script.runEnv.workRoot, this.client, this.settings) let testDataRecord: any try { this.runningBrowser = browser if (this.settings.clearCache) await browser.clearBrowserCache() if (this.settings.clearCookies) await browser.clearBrowserCookies() if (this.settings.device) await browser.emulateDevice(this.settings.device) if (this.settings.userAgent) { await browser.setUserAgent(this.settings.userAgent) } else { await this.client.reopenPage(this.settings.incognito) } if (this.settings.disableCache) await browser.setCacheDisabled(true) if (this.settings.extraHTTPHeaders) await browser.setExtraHTTPHeaders(this.settings.extraHTTPHeaders) browser.beforeFunc = this.willRunCommand.bind(this, testObserver) browser.afterFunc = this.didRunCommand.bind(this, testObserver) browser.setMultipleUser(!!this.reporter.worker) debug('running this.before(browser)') await testObserver.before(this) debug('Feeding data') testDataRecord = testData ? testData.feed() : {} const invalidName: string[] = [] const validTestData = () => { if (testDataRecord === null) return false if (testData && testData.multiple) { for (const key in testDataRecord) { if (testDataRecord[key] === null) { invalidName.push(key) } } } return invalidName.length === 0 } if (!validTestData()) { console.log( chalk.red( `${ !invalidName.length ? 'Test data exhausted' : `Test data '${invalidName.join(',')}' exhausted` }, consider making it circular?` ) ) } else { debug(JSON.stringify(testDataRecord)) } debug('running hook function: beforeAll') let hookResult = await this.runHookFn( this.hook.beforeAll, browser, testDataRecord, testObserver ) if (!hookResult) { stepIterator.stop() } debug('running steps') await stepIterator.run(async (step: Step) => { debug('running hook function: beforeEach') hookResult = await this.runHookFn( this.hook.beforeEach, browser, testDataRecord, testObserver ) if (!hookResult) { stepIterator.stop() return } const condition = await stepIterator.callCondition(step, iteration, browser) if (!condition) { await this.summarizeStepBeforeRunStep(step, testObserver) return } browser.customContext = step await Promise.race([ this.runStep(testObserver, browser, step, testDataRecord), cancelToken.promise, ]) this.summarizeStepAfterRunStep(step) if (cancelToken.isCancellationRequested) return if (this.failed) { const result = await stepIterator.callRecovery( step, looper, browser, this.recoverySteps, (this.settings.tries = 0) ) if (result) { this.failed = false } else { await this.afterRunSteps(stepIterator) stepIterator.stop() } } debug('running hook function: afterEach') hookResult = await this.runHookFn( this.hook.afterEach, browser, testDataRecord, testObserver ) if (!hookResult) { stepIterator.stop() return } }) await this.afterRunSteps(stepIterator) if (this.settings.showScreenshot && process.env.TERM_PROGRAM === 'iTerm.app') { for (const path of browser.fetchScreenshots()) { console.log(basename(path)) termImg(path, { width: '40%' }) } } } catch (err) { this.failed = true console.error(chalk.red(err.message)) } finally { await testObserver.after(this) debug('running hook function: afterAll') await this.runHookFn(this.hook.afterAll, browser, testDataRecord, testObserver) } } async afterRunSteps(stepIterator: StepIterator): Promise<void> { await this.requestInterceptor.detach(this.client.page) this.summarizeStepAfterStopRunning(stepIterator) } async summarizeStepBeforeRunStep(step: Step, testObserver: TestObserver): Promise<void> { if (step.prop?.unexecuted) { await testObserver.onStepUnexecuted(this, step) this.summaryStep.push({ name: step.name, status: Status.UNEXECUTED, }) return } if (step.prop?.skipped) { await testObserver.onStepSkipped(this, step) this.summaryStep.push({ name: step.name, status: Status.SKIPPED }) return } } summarizeStepAfterRunStep(step: Step): void { this.summaryStep.push({ name: step.name, status: step.prop?.passed ? Status.PASSED : Status.FAILED, subTitle: step.subTitle, duration: step.duration, error: step.prop?.error, }) step.duration = 0 } summarizeStepAfterStopRunning(stepIterator: StepIterator): void { const countRepeatStep = (step: Step): boolean => { const { repeat } = step.options if (repeat) { if (repeat.iteration > 0) { do { repeat.iteration += 1 this.summaryStep.push({ name: step.name, status: Status.UNEXECUTED, subTitle: `${getNumberWithOrdinal(repeat.iteration)} loop`, }) } while (repeat.iteration < repeat.count) } repeat.iteration = 0 return true } return false } const summarizedUnexecutedStep = (step: Step): void => { const countRepeatStepDone = countRepeatStep(step) if (countRepeatStepDone) return this.summaryStep.push({ name: step.name, status: Status.UNEXECUTED, }) } stepIterator.loopUnexecutedSteps(summarizedUnexecutedStep) } getStepSubtitle(step: Step): string { const { repeat } = step.options const recoveryTries = step.prop?.recoveryTries let subTitle = '' if (recoveryTries && recoveryTries > 0) { subTitle = `${getNumberWithOrdinal(recoveryTries)} recovery` this.summaryStep.pop() } if (repeat) { let tempTitle = '' const { iteration, count } = repeat if (iteration >= count || iteration === 0) { tempTitle = `${getNumberWithOrdinal(repeat.count)} loop` } else { tempTitle = `${getNumberWithOrdinal(repeat.iteration)} loop` } subTitle = subTitle ? `${tempTitle} - ${subTitle}` : tempTitle } return subTitle } get currentURL(): string { return (this.runningBrowser && this.runningBrowser.url) || '' } async runStep( testObserver: TestObserver, browser: Browser<Step>, step: Step, testDataRecord: any ) { let error: Error | null = null step.subTitle = this.getStepSubtitle(step) await testObserver.beforeStep(this, step) const originalBrowserSettings = { ...browser.settings } try { debug(`Run step: ${step.name}`) // ${step.fn.toString()}`) browser.settings = { ...this.settings, ...step.options } await step.fn.call(null, browser, testDataRecord) } catch (err) { error = err } finally { browser.settings = originalBrowserSettings } if (error !== null) { debug('step error') this.failed = true await testObserver.onStepError(this, step, this.liftToStructuredError(error)) step.prop = { passed: false, error: error.message } } else { await testObserver.onStepPassed(this, step) step.prop = { passed: true } } await testObserver.afterStep(this, step) if (error === null) { await this.doStepDelay() } debug('step done') } liftToStructuredError(error: Error): StructuredError<AnyErrorData> { if (error.name.startsWith('AssertionError')) { return new StructuredError<AssertionErrorData>( error.message, { _kind: 'assertion' }, error ).copyStackFromOriginalError() } else if ((error as StructuredError<AnyErrorData>)._structured === 'yes') { return error as StructuredError<AnyErrorData> } else { // catchall - this should trigger a documentation request further up the chain return StructuredError.wrapBareError<EmptyErrorData>(error, { _kind: 'empty' }, 'test') } } public get stepNames(): string[] { return this.steps.map((s) => s.name) } public async doStepDelay() { if (this.skipping || this.settings.stepDelay <= 0) { return } await new Promise<void>((resolve) => { if (!this.settings.stepDelay) { resolve() return } setTimeout(resolve, Number(this.settings.stepDelay) || DEFAULT_STEP_WAIT_MILLISECONDS) }) } public async willRunCommand( testObserver: TestObserver, browser: Browser<Step>, command: string, args: string ): Promise<void> { if (this.hookMode) { await testObserver.beforeHookAction(this, command, args) } else { await testObserver.beforeStepAction(this, browser.customContext, command, args) } } async didRunCommand( testObserver: TestObserver, browser: Browser<Step>, command: string, args: string ): Promise<void> { if (this.hookMode) { await testObserver.afterHookAction(this, command, args) } else { await testObserver.afterStepAction(this, browser.customContext, command, args) } } public async takeScreenshot(options?: ScreenshotOptions) { if (this.runningBrowser === null) return await this.runningBrowser.takeScreenshot(options) } public async fetchScreenshots(): Promise<string[]> { if (this.runningBrowser === null) return [] return this.runningBrowser.fetchScreenshots() } /* @deprecated */ newTrace(step: Step): ObjectTrace { return new ObjectTrace(this.script.runEnv.workRoot, step.name) } private async runHookFn( hooks: HookBase[], browser: Browser<Step>, testDataRecord: any, testObserver: TestObserver ): Promise<boolean> { this.hookMode = true let currentHook: HookBase = hooks[0] try { for (const hook of hooks) { currentHook = hook await this.prepareHookFuncObserver(hook.type, testObserver) browser.settings = { ...this.settings } browser.settings.waitTimeout = Math.max( Number(browser.settings.waitTimeout), Number(hook.waitTimeout) ) const hookFn = hook.fn.bind(null, browser, testDataRecord) await this.doHookFnWithTimeout(hookFn, Number(hook.waitTimeout)) await this.finishedHookFuncObserver(hook.type, testObserver) } return true } catch (err) { console.log(err.message) await this.finishedHookFuncObserver(currentHook.type, testObserver) return false } finally { this.hookMode = false } } private async doHookFnWithTimeout(fn: any, timeout: number): Promise<any> { // Create a promise that rejects in <ms> milliseconds const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject() }, timeout) }) // Returns a race between our timeout and the passed in promise return Promise.race([fn(), timeoutPromise]) } private async prepareHookFuncObserver(type: HookType, testObserver: TestObserver): Promise<void> { switch (type) { case HookType.beforeAll: await testObserver.beforeAllStep(this) break case HookType.beforeEach: await testObserver.beforeEachStep(this) break case HookType.afterEach: await testObserver.afterEachStep(this) break case HookType.afterAll: await testObserver.afterAllStep(this) break } } private async finishedHookFuncObserver( type: HookType, testObserver: TestObserver ): Promise<void> { switch (type) { case HookType.beforeAll: await testObserver.onBeforeAllStepFinished(this) break case HookType.beforeEach: await testObserver.onBeforeEachStepFinished(this) break case HookType.afterEach: await testObserver.onAfterEachStepFinished(this) break case HookType.afterAll: await testObserver.onAfterAllStepFinished(this) break } } }
the_stack
import './setup'; import { PLATFORM } from 'aurelia-pal'; import { validateScrolledState, waitForFrames } from './utilities'; import { VirtualRepeat } from '../src/virtual-repeat'; import { StageComponent, ComponentTester } from 'aurelia-testing'; import { bootstrap } from 'aurelia-bootstrapper'; import { ITestAppInterface } from './interfaces'; import { eachCartesianJoin } from './lib'; import { ElementEvents } from 'aurelia-framework'; import { IdentityValueConverter, CloneArrayValueConverter } from './value-converters'; PLATFORM.moduleName('src/virtual-repeat'); PLATFORM.moduleName('test/noop-value-converter'); PLATFORM.moduleName('src/infinite-scroll-next'); describe('vr-integration.resizing.spec.ts', () => { const SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION = 3; let component: ComponentTester<VirtualRepeat>; beforeEach(() => { component = undefined; }); afterEach(() => { try { if (component) { component.dispose(); } } catch (ex) { console.log('Error disposing component'); console.error(ex); } }); const testGroups: ITestCaseGroup[] = [ { desc: 'div > div', sizes: { ct_h: 500, ct_w: 400, item_h: 45, item_w: 0 }, title: (repeatExpression, scrollNextAttr, sizes) => `div > div[repeat ${repeatExpression}][${scrollNextAttr}]`, createView: (repeatExpression, scrollNextAttr, {ct_h, ct_w, item_h, item_w}) => `<div style="height: ${ct_h}px; overflow-y: scroll"> <div virtual-repeat.for="item of items ${repeatExpression}" ${scrollNextAttr} class="v-repeat-item" style="height: ${item_h}px;">\${item}</div> </div>` }, { desc: 'ul > li', sizes: { ct_h: 500, ct_w: 400, item_h: 45, item_w: 0 }, title: (repeatExpression, scrollNextAttr) => `ul > li[repeat ${repeatExpression}][${scrollNextAttr}]`, createView: (repeatExpression, scrollNextAttr, {ct_h, ct_w, item_h, item_w}) => `<ul style="height: ${ct_h}px; overflow-y: scroll; padding: 0; margin: 0; list-style: none;"> <li virtual-repeat.for="item of items ${repeatExpression}" ${scrollNextAttr} style="height: ${item_h}px;">\${item}</li> </ul>` }, { desc: 'ol > li', sizes: { ct_h: 500, ct_w: 400, item_h: 45, item_w: 0 }, title: (repeatExpression, scrollNextAttr) => `ol > li[repeat ${repeatExpression}][${scrollNextAttr}]`, createView: (repeatExpression, scrollnextAttr, {ct_h, ct_w, item_h, item_w}) => `<ol style="height: ${ct_h}px; overflow-y: scroll; padding: 0; margin: 0; list-style: none;"> <li virtual-repeat.for="item of items ${repeatExpression}" ${scrollnextAttr} style="height: ${item_h}px;">\${item}</li> </ol>` }, { desc: 'div > table > tr', sizes: { ct_h: 500, ct_w: 400, item_h: 45, item_w: 0 }, title: (repeatExpression: string, scrollNextAttr: string): string => { return `div > table > tr[repeat ${repeatExpression}][${scrollNextAttr}]`; }, createView: (repeatExpression: string, scrollNextAttr: string, {ct_h, ct_w, item_h, item_w}): string => { return `<div style="height: ${ct_h}px; overflow-y: scroll; padding: 0; margin: 0;"> <table style="border-spacing: 0"> <tr virtual-repeat.for="item of items ${repeatExpression}" ${scrollNextAttr} style="height: ${item_h}px;"><td>\${item}</td></tr> </table> </div>`; } }, { desc: 'div > table > tbody', sizes: { ct_h: 500, ct_w: 400, item_h: 45, item_w: 0 }, title: (repeatExpression: string, scrollNextAttr: string): string => { return `div > table > tbody[repeat${repeatExpression}][${scrollNextAttr}]`; }, createView: (repeatExpression: string, scrollNextAttr: string, {ct_h, ct_w, item_h, item_w}): string => { return `<div style="height: ${ct_h}px; overflow-y: scroll; padding: 0; margin: 0;"> <table style="border-spacing: 0"> <tbody virtual-repeat.for="item of items ${repeatExpression}" ${scrollNextAttr}> <tr style="height: ${item_h}px;"> <td>\${item}</td> </tr> </tbody> </table> </div>`; } } ]; const repeatResizingCombos: IRepeatSizingCombo[] = [ ['', 'infinite-scroll-next="getNextPage"'], ['', 'infinite-scroll-next.call="getNextPage($scrollContext)"'], [' & toView', 'infinite-scroll-next="getNextPage"'], [' & twoWay', 'infinite-scroll-next="getNextPage"'], [' & twoWay', 'infinite-scroll-next.call="getNextPage($scrollContext)"'], [' | cloneArray', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]], [' | cloneArray', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [CloneArrayValueConverter]], [' | identity | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [IdentityValueConverter, CloneArrayValueConverter]], [' | identity | cloneArray & toView', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [IdentityValueConverter, CloneArrayValueConverter]], [' | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]] // cloneArray and two way creates infinite loop // [' | cloneArray & twoWay', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]] ]; eachCartesianJoin( [repeatResizingCombos, testGroups], ([repeatExpression, scrollNextAttr, extraResources], { sizes, title, createView }, callIndex) => { runSizingTestGroup( title(repeatExpression, scrollNextAttr, sizes), createView(repeatExpression, scrollNextAttr, sizes), sizes, extraResources ); } ); type IRepeatSizingCombo = [ /*repeat extra expression*/string, /*infinite-scroll-next attr*/string, /*extraResources*/ any[]? ]; interface IRepeatSizingSizeVariables { ct_w: number; ct_h: number; item_w: number; item_h: number; } interface ITestCaseGroup { desc?: string; sizes: IRepeatSizingSizeVariables; title: ( repeatExpression: string, scrollNextAttr: string, sizes: IRepeatSizingSizeVariables ) => string; createView: ( repeatExpression: string, scrollNextAttr: string, sizes: IRepeatSizingSizeVariables ) => string; } function runSizingTestGroup( title: string, $view: string, { ct_h, ct_w, item_w, item_h}: IRepeatSizingSizeVariables, extraResources: any[] = [] ) { it([ title, `100 items`, ` 1. item: [h: ${item_h}], ct: [w: ${ct_w}, h: ${ct_h}]`, ` 2. resize ct [w: ${ct_w}, h: ${ct_h / 2}]`, ` 3. wait + assert`, ` 4. resize ct [w: ${ct_w / 2}, h: ${ct_h / 2}]`, ` 5. wait + assert`, ` 6. restore ct [w: ${ct_w}, h: ${ct_h}]`, ` 7. wait + assert`, '' ].join('\n\t'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent( { items: createItems(100), getNextPage: PLATFORM.noop as any }, $view, extraResources ); const scroller = virtualRepeat.getScroller(); assertElementsInView(virtualRepeat, ct_h, item_h); scroller.style.height = `${ct_h / 2}px`; await waitForFrames(SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION); expect(scroller).toBe(virtualRepeat.getScroller(), 'repeat.getScroller() unchanged'); assertElementsInView(virtualRepeat, ct_h / 2, item_h, 'Step 3. '); validateScrolledState(virtualRepeat, viewModel, item_h, `resize: [w: ${ct_w}, h: ${ct_h / 2}]`); scroller.style.width = `${ct_w / 2}px`; await waitForFrames(SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION); expect(scroller).toBe(virtualRepeat.getScroller(), 'repeat.getScroller() unchanged'); assertElementsInView(virtualRepeat, ct_h / 2, item_h, 'Step 5. '); validateScrolledState(virtualRepeat, viewModel, item_h, `resize: [w: ${ct_w / 2}, h: ${ct_h / 2}]`); scroller.style.height = `${ct_h}px`; scroller.style.width = `${ct_w}px`; await waitForFrames(SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION); expect(scroller).toBe(virtualRepeat.getScroller(), 'repeat.getScroller() unchanged'); assertElementsInView(virtualRepeat, ct_h, item_h, 'Step 7. '); validateScrolledState(virtualRepeat, viewModel, item_h, `resize: [w: ${ct_w}, h: ${ct_h}]`); }); it([ title, `100 items + (resize + mutation)`, ` 1. item: [h: ${item_h}], ct: [w: ${ct_w}, h: ${ct_h}]`, ` 2. resize ct [w: ${ct_w}, h: ${ct_h / 2}]`, ` 3. splice to 30`, ` 4. wait() and assert`, ` 5. resize ct [w: ${ct_w / 2}, h: ${ct_h / 2}]`, ` 6. splice to 0`, ` 7. wait() and assert`, ` 8. restore ct [w: ${ct_w}, h: ${ct_h}]`, ` 9. wait() and assert`, `` ].join('\n\t'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent( { items: createItems(100), getNextPage: PLATFORM.noop as any }, $view, extraResources ); const scroller = virtualRepeat.getScroller(); assertElementsInView(virtualRepeat, ct_h, item_h); scroller.style.height = `${ct_h / 2}px`; viewModel.items.splice(0, Math.max(viewModel.items.length - 30, 0)); await waitForFrames(SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION ); expect(scroller).toBe(virtualRepeat.getScroller(), 'repeat.getScroller() unchanged'); assertElementsInView(virtualRepeat, ct_h / 2, item_h, 'Step 4. '); validateScrolledState(virtualRepeat, viewModel, item_h, `resize: [w: ${ct_w}, h: ${ct_h / 2}]`); // step 5. scroller.style.height = `${ct_h / 2}px`; scroller.style.width = `${ct_w / 2}px`; // step 6. viewModel.items.splice(0, Infinity); await waitForFrames(SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION); expect(scroller).toBe(virtualRepeat.getScroller(), 'repeat.getScroller() unchanged'); assertElementsInView(virtualRepeat, ct_h / 2, item_h, 'Step 7. '); validateScrolledState(virtualRepeat, viewModel, item_h, `resize: [w: ${ct_w / 2}, h: ${ct_h / 2}]`); // step 8. scroller.style.height = `${ct_h}px`; scroller.style.width = `${ct_w}px`; await waitForFrames(SAFE_FRAME_COUNT_FOR_CHANGE_PROPAGATION); expect(scroller).toBe(virtualRepeat.getScroller(), 'repeat.getScroller() unchanged'); assertElementsInView(virtualRepeat, ct_h, item_h, 'Step 9. '); validateScrolledState(virtualRepeat, viewModel, item_h, `resize: [w: ${ct_w}, h: ${ct_h}]`); }); // xit([ // title, // `100 items`, // ` -- item: [h: ${item_h}], ct: [w: ${ct_w}, h: ${ct_h}]`, // ` -- resize ct [w: ${ct_w}, h: ${ct_h / 2}]`, // ` -- resize ct [w: ${ct_w / 2}, h: ${ct_h / 2}]`, // ` -- restore ct [w: ${ct_w}, h: ${ct_h}]`, // '' // ].join('\n\t'), async () => { // // empty // }); // it([ // '100 items', // '\t[rows] <-- h:30 each', // '\t[ct resized] <-- h:60 each', // '\t-- scroll range synced' // ].join('\n'), async () => { // const { viewModel, virtualRepeat } = await bootstrapComponent({ items: createItems(100) }); // const scrollCtEl = document.querySelector('#scrollCtEl'); // expect(scrollCtEl.scrollHeight).toEqual(100 * 50 + 30, 'scrollCtEl.scrollHeight'); // for (let i = 0; 79 > i; ++i) { // scrollCtEl.scrollTop = i; // await waitForNextFrame(); // expect(virtualRepeat.view(0).bindingContext.item).toEqual('item0'); // // todo: more validation of scrolled state here // } // for (let i = 80; 80 + 49 > i; ++i) { // scrollCtEl.scrollTop = i; // await waitForNextFrame(); // expect(virtualRepeat.view(0).bindingContext.item).toEqual('item1'); // // todo: more validation of scrolled state here // } // }); } async function bootstrapComponent<T>($viewModel: ITestAppInterface<T>, $view: string, extraResources?: any[]) { component = StageComponent .withResources([ 'src/virtual-repeat', ...extraResources ]) .inView($view) .boundTo($viewModel); await component.create(bootstrap); expect(document.body.contains(component.element)).toBe(true, 'repeat is setup in document'); const virtualRepeat = component.viewModel; assertBasicSetup(virtualRepeat); return { virtualRepeat: virtualRepeat, viewModel: $viewModel, component: component }; } function assertBasicSetup(repeat: VirtualRepeat): void { const items = repeat.items; const scroller = repeat.getScroller(); if (document.body.contains(scroller) && scroller !== document.body) { expect(repeat._calcDistanceToTopInterval).toBe(undefined, 'repeat._calcTopDistance === undefined ✔'); } if (items) { expect(repeat._scrollerEvents instanceof ElementEvents) .toBe(true, 'repeat._scrollerEvents ✔'); expect(repeat._scrollerResizeObserver instanceof PLATFORM.global.ResizeObserver) .toBe(true, 'repeat._scrollerResizeObserver ✔'); } else { expect(repeat._scrollerEvents).toBe(undefined, 'repeat._scrollerEvents === undefined ✔'); expect(repeat._scrollerResizeObserver).toBe(undefined, 'repeat._scrollerResizeObserver === undefined ✔'); } } function assertElementsInView(repeat: VirtualRepeat, ctHeight: number, itemHeight: number, extraTitle: string = ''): void { const itemsCount = Array.isArray(repeat.items) ? repeat.items.length : 0; const elementsInView = itemsCount === 0 ? 0 : repeat.minViewsRequired; const viewsLength = itemsCount === 0 ? 0 : repeat.minViewsRequired * 2; const expectedElementsInView = itemsCount === 0 ? 0 : itemHeight === 0 ? 1 : Math.floor(ctHeight / itemHeight) + 1; expect(elementsInView).toBe( expectedElementsInView, `${extraTitle}repeat.elementsInView === ${expectedElementsInView} ? (1)` ); expect(viewsLength).toBe( expectedElementsInView * 2, `${extraTitle}repeat._viewsLength === ${expectedElementsInView * 2} (2)` ); if (repeat.items) { const realViewCount = repeat.viewCount(); if (repeat.items.length >= expectedElementsInView * 2) { expect(realViewCount).toBe( expectedElementsInView * 2, `${extraTitle}repeat.viewCount() === ${expectedElementsInView * 2} (3)` ); } else { expect(realViewCount).toBe( repeat.items.length, `${extraTitle}repeat.viewCount() === repeat.items.length (4)` ); } } } function createItems(amount: number, name: string = 'item') { return Array.from({ length: amount }, (_, index) => name + index); } });
the_stack
import { IAction } from './actions/action.interface'; import { ConsoleLogger } from './common/console.logger'; import { ActionLogger } from './middlewares/action.logger'; import { composeWithDevTools } from 'redux-devtools-extension'; import { AbstractLogger as ILogger } from './common/abstract.logger'; import { IGlobalStore } from './common/interfaces/global.store.interface'; import { Store, Reducer, Middleware, createStore, applyMiddleware } from 'redux'; /** * Summary Global store for all Apps and container shell (Platform) in Micro-Frontend application. * Description Singleton class to be used all all Apps for registering the isolated App States. The platform-level and global-level store can be accessed from this class. */ export class GlobalStore implements IGlobalStore { public static readonly Platform: string = "Platform"; public static readonly AllowAll: string = "*"; public static readonly InstanceName: string = "GlobalStoreInstance"; public static DebugMode: boolean = false; private _stores: { [key: string]: Store }; private _globalActions: { [key: string]: Array<string> }; private _globalListeners: Array<(state: any) => void>; private _eagerPartnerStoreSubscribers: { [key: string]: { [key: string]: (state) => void } } private _eagerUnsubscribers: { [key: string]: { [key: string]: () => void } } private _actionLogger: ActionLogger = null; private constructor(private _logger: ILogger = null) { this._stores = {}; this._globalActions = {}; this._globalListeners = []; this._eagerPartnerStoreSubscribers = {}; this._eagerUnsubscribers = {}; this._actionLogger = new ActionLogger(_logger); } /** * Summary Gets the singleton instance of the Global Store. * * @param {ILogger} logger Logger service. */ public static Get(debugMode: boolean = false, logger: ILogger = null): IGlobalStore { if (debugMode) { this.DebugMode = debugMode; } if (debugMode && (logger === undefined || logger === null)) { logger = new ConsoleLogger(debugMode); } let globalGlobalStoreInstance: IGlobalStore = window[GlobalStore.InstanceName] || null; if (globalGlobalStoreInstance === undefined || globalGlobalStoreInstance === null) { globalGlobalStoreInstance = new GlobalStore(logger); window[GlobalStore.InstanceName] = globalGlobalStoreInstance; } return globalGlobalStoreInstance; } /** * Summary: Creates and registers a new store * * @access public * * @param {string} appName Name of the App for whom the store is getting creating. * @param {Reducer} appReducer The root reducer of the App. If partner app is using multiple reducers, then partner App must use combineReducer and pass the root reducer * @param {Array<Middleware>} middlewares List of redux middlewares that the partner app needs. * @param {boolean} shouldReplaceStore Flag to indicate if the Partner App wants to replace an already created/registered store with the new store. * @param {boolean} shouldReplaceReducer Flag to indicate if the Partner App wants to replace the existing root Reducer with the given reducer. Note, that the previous root Reducer will be replaced and not updated. If the existing Reducer needs to be used, then partner app must do the append the new reducer and pass the combined root reducer. * * @returns {Store<any, any>} The new Store */ CreateStore(appName: string, appReducer: Reducer, middlewares?: Array<Middleware>, globalActions?: Array<string>, shouldReplaceStore: boolean = false, shouldReplaceReducer: boolean = false): Store<any, any> { let existingStore = this._stores[appName]; if (existingStore === null || existingStore === undefined || shouldReplaceStore) { if (middlewares === undefined || middlewares === null) middlewares = []; let appStore = createStore(appReducer, GlobalStore.DebugMode ? composeWithDevTools(applyMiddleware(...middlewares)) : applyMiddleware(...middlewares)); this.RegisterStore(appName, appStore, globalActions, shouldReplaceStore); return appStore; } if (shouldReplaceReducer) { console.warn(`The reducer for ${appName} is getting replaced`); existingStore.replaceReducer(appReducer); this.RegisterStore(appName, existingStore, globalActions, true); } return existingStore; } /** * Summary: Registers an isolated app store * * @access public * * @param {string} appName Name of the App. * @param {Store} store Instance of the store. * @param {boolean} shouldReplace Flag to indicate if the an already registered store needs to be replaced. */ RegisterStore(appName: string, store: Store, globalActions?: Array<string>, shouldReplaceExistingStore: boolean = false): void { let existingStore = this._stores[appName]; if (existingStore !== undefined && existingStore !== null && shouldReplaceExistingStore === false) return; this._stores[appName] = store; store.subscribe(this.InvokeGlobalListeners.bind(this)); this.RegisterGlobalActions(appName, globalActions); this.RegisterEagerSubscriptions(appName); this.LogRegistration(appName, (existingStore !== undefined && existingStore !== null)); } /** * Summary: Registers a list of actions for an App that will be made Global. * Description: Global actions can be dispatched on the App Store by any Partner Apps. If partner needs to make all actions as Global, then pass "*" in the list. If no global actions are registered then other partners won't be able to dispatch any action on the App Store. * * @access public * * @param {string} appName Name of the app. * @param {Array<string>} actions List of global action names. */ RegisterGlobalActions(appName: string, actions?: Array<string>): void { if (actions === undefined || actions === null || actions.length === 0) { return; } let registeredActions = this._globalActions[appName]; if (registeredActions === undefined || registeredActions === null) { registeredActions = []; this._globalActions[appName] = []; } let uniqueActions = actions.filter(action => registeredActions.find(registeredAction => action === registeredAction) === undefined); uniqueActions = [...new Set(uniqueActions)]; // Removing any duplicates this._globalActions[appName] = [...this._globalActions[appName], ...uniqueActions]; } /** * Summary: Gets the current state of the Platform * * @access public * * @returns Current Platform State (App with name Platform) */ GetPlatformState(): any { let platformStore = this.GetPlatformStore(); if (platformStore === undefined || platformStore === null) return null; return this.CopyState(platformStore.getState()); } /** * Summary: Gets the current state of the given Partner. * Description: A read-only copy of the Partner state is returned. The state cannot be mutated using this method. For mutation dispatch actions. In case the partner hasn't been registered or the partner code hasn't loaded, the method will return null. * * @param partnerName Name of the partner whose state is needed * * @returns {any} Current partner state. */ GetPartnerState(partnerName: string): any { let partnerStore = this.GetPartnerStore(partnerName); if (partnerStore === undefined || partnerStore === null) return null; let partnerState = partnerStore.getState(); return this.CopyState(partnerState); } /** * Summary: Gets the global store. * Description: The global store comprises of the states of all registered partner's state. * Format * { * Platform: { ...Platform_State }, * Partner_Name_1: { ...Partner_1_State }, * Partner_Name_2: { ...Partner_2_State } * } * * @access public * * @returns {any} Global State. */ GetGlobalState(): any { let globalState = {}; for (let partner in this._stores) { let state = this._stores[partner].getState(); globalState[partner] = state; }; return this.CopyState(globalState); } /** * Summary: Dispatches an action on all the Registered Store (including Platform level store). * Description: The action will be dispatched only if the Partner App has declated the action to be global at it's store level. * * @access public * * @param {string} source Name of app dispatching the Actions * @param {IAction<any>} action Action to be dispatched */ DispatchGlobalAction(source: string, action: IAction<any>): void { for (let partner in this._stores) { let isActionRegisteredByPartner = this.IsActionRegisteredAsGlobal(partner, action); if (isActionRegisteredByPartner) { this._stores[partner].dispatch(action); } } } /** * Summary: Dispatched an action of the local store * * @access public * * @param {string} source Name of app dispatching the Actions * @param {IAction<any>} action Action to be dispatched */ DispatchLocalAction(source: string, action: IAction<any>): void { let localStore = this._stores[source]; if (localStore === undefined || localStore === null) { let error = new Error(`Store is not registered`); if (this._logger !== undefined && this._logger !== null) this._logger.LogException(source, error, {}); throw error; } localStore.dispatch(action); } /** * Summary: Dispatches an action at a local as well global level * * @access public * * @param {string} source Name of app dispatching the Actions * @param {IAction<any>} action Action to be dispatched */ DispatchAction(source: string, action: IAction<any>): void { this.DispatchGlobalAction(source, action); let isActionGlobal = this.IsActionRegisteredAsGlobal(source, action); if (!isActionGlobal) this.DispatchLocalAction(source, action); } /** * Summary: Subscribe to current store's state changes * * @param {string} source Name of the application * @param {(state: any) => void} callback Callback method to be invoked when state changes */ Subscribe(source: string, callback: (state: any) => void): () => void { let store = this.GetPartnerStore(source); if (store === undefined || store === null) { throw new Error(`ERROR: Store for ${source} hasn't been registered`); } return store.subscribe(() => callback(store.getState())); } /** * Summary: Subscribe to any change in the Platform's state. * * @param {string} source Name of application subscribing to the state changes. * @param {(state: any) => void} callback Callback method to be called for every platform's state change. * * @returns {() => void} Unsubscribe method. Call this method to unsubscribe to the changes. */ SubscribeToPlatformState(source: string, callback: (state: any) => void): () => void { let platformStore = this.GetPlatformStore(); return platformStore.subscribe(() => callback(platformStore.getState())); } /** * Summary: Subscribe to any change in the Partner App's state. * * @access public * * * @param {string} source Name of the application subscribing to the state changes. * @param {string} partner Name of the Partner application to whose store is getting subscribed to. * @param {(state: any) => void} callback Callback method to be called for every partner's state change. * @param {boolean} eager Allows subscription to store that's yet to registered * * @throws Error when the partner is yet to be registered/loaded or partner doesn't exist. * * @returns {() => void} Unsubscribe method. Call this method to unsubscribe to the changes. */ SubscribeToPartnerState(source: string, partner: string, callback: (state: any) => void, eager: boolean = true): () => void { let partnerStore = this.GetPartnerStore(partner); if (partnerStore === undefined || partnerStore === null) { if (!eager) { throw new Error(`ERROR: ${source} is trying to subscribe to partner ${partner}. Either ${partner} doesn't exist or hasn't been loaded yet`); } if (this._eagerPartnerStoreSubscribers[partner]) { this._eagerPartnerStoreSubscribers[partner].source = callback; } else { this._eagerPartnerStoreSubscribers[partner] = { source: callback } } return () => { this.UnsubscribeEagerSubscription(source, partner); } } return partnerStore.subscribe(() => callback(partnerStore.getState())); } /** * Summary: Subscribe to any change in the Global State, including Platform-level and Partner-level changes. * * @access public * * @param {string} source Name of the application subscribing to the state change. * @param {(state: any) => void} callback Callback method to be called for every any change in the global state. * * @returns {() => void} Unsubscribe method. Call this method to unsubscribe to the changes. */ SubscribeToGlobalState(source: string, callback: (state: any) => void): () => void { this._globalListeners.push(callback) return () => { this._globalListeners = this._globalListeners.filter(globalListener => globalListener !== callback); } } UnsubscribeEagerSubscription(source: string, partnerName: string) { if (!partnerName || !source) return; if (!this._eagerUnsubscribers[partnerName]) return; let unsubscriber = this._eagerUnsubscribers[partnerName].source; if (unsubscriber) unsubscriber(); } SetLogger(logger: ILogger) { if (this._logger === undefined || this._logger === null) this._logger = logger; else this._logger.SetNextLogger(logger); this._actionLogger.SetLogger(logger); } private RegisterEagerSubscriptions(appName: string) { let eagerCallbacksRegistrations = this._eagerPartnerStoreSubscribers[appName]; if (eagerCallbacksRegistrations === undefined || eagerCallbacksRegistrations === undefined) return; let registeredApps = Object.keys(eagerCallbacksRegistrations); registeredApps.forEach(sourceApp => { let callback = eagerCallbacksRegistrations[sourceApp]; if (callback) { let unregistrationCallback = this.SubscribeToPartnerState(sourceApp, appName, callback, false); if (this._eagerPartnerStoreSubscribers[appName]) { this._eagerPartnerStoreSubscribers[appName].sourceApp = unregistrationCallback; } else { this._eagerPartnerStoreSubscribers[appName] = { sourceApp: unregistrationCallback }; } } }); } private InvokeGlobalListeners(): void { let globalState = this.GetGlobalState(); this._globalListeners.forEach(globalListener => { globalListener(globalState); }); } private GetPlatformStore(): Store<any, any> { return this.GetPartnerStore(GlobalStore.Platform); } private GetPartnerStore(partnerName: string): Store<any, any> { return this._stores[partnerName]; } private GetGlobalMiddlewares(): Array<Middleware> { let actionLoggerMiddleware = this._actionLogger.CreateMiddleware(); return [actionLoggerMiddleware]; } private IsActionRegisteredAsGlobal(appName: string, action: IAction<any>): boolean { let registeredGlobalActions = this._globalActions[appName]; if (registeredGlobalActions === undefined || registeredGlobalActions === null) { return false; } return registeredGlobalActions.some(registeredAction => registeredAction === action.type || registeredAction === GlobalStore.AllowAll); } private LogRegistration(appName: string, isReplaced: boolean) { try { let properties = { "AppName": appName, "IsReplaced": isReplaced.toString() }; if (this._logger) this._logger.LogEvent("Store.GlobalStore", "StoreRegistered", properties); } catch (error) { // Gulp the error console.error(`ERROR: There was an error while logging registration for ${appName}`); console.error(error); } } private CopyState(state: any) { if (state === undefined || state === null || typeof state !== 'object') { return state; } else { return { ...state } } } }
the_stack