text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Provides an RDS DB proxy endpoint resource. For additional information, see the [RDS User Guide](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy.html#rds-proxy-endpoints). * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.rds.ProxyEndpoint("example", { * dbProxyName: aws_db_proxy.test.name, * dbProxyEndpointName: "example", * vpcSubnetIds: aws_subnet.test.map(__item => __item.id), * targetRole: "READ_ONLY", * }); * ``` * * ## Import * * DB proxy endpoints can be imported using the `DB-PROXY-NAME/DB-PROXY-ENDPOINT-NAME`, e.g. * * ```sh * $ pulumi import aws:rds/proxyEndpoint:ProxyEndpoint example example/example * ``` */ export class ProxyEndpoint extends pulumi.CustomResource { /** * Get an existing ProxyEndpoint 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?: ProxyEndpointState, opts?: pulumi.CustomResourceOptions): ProxyEndpoint { return new ProxyEndpoint(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:rds/proxyEndpoint:ProxyEndpoint'; /** * Returns true if the given object is an instance of ProxyEndpoint. 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 ProxyEndpoint { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ProxyEndpoint.__pulumiType; } /** * The Amazon Resource Name (ARN) for the proxy endpoint. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * The identifier for the proxy endpoint. An identifier must begin with a letter and must contain only ASCII letters, digits, and hyphens; it can't end with a hyphen or contain two consecutive hyphens. */ public readonly dbProxyEndpointName!: pulumi.Output<string>; /** * The name of the DB proxy associated with the DB proxy endpoint that you create. */ public readonly dbProxyName!: pulumi.Output<string>; /** * The endpoint that you can use to connect to the proxy. You include the endpoint value in the connection string for a database client application. */ public /*out*/ readonly endpoint!: pulumi.Output<string>; /** * Indicates whether this endpoint is the default endpoint for the associated DB proxy. */ public /*out*/ readonly isDefault!: pulumi.Output<boolean>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Indicates whether the DB proxy endpoint can be used for read/write or read-only operations. The default is `READ_WRITE`. Valid values are `READ_WRITE` and `READ_ONLY`. */ public readonly targetRole!: pulumi.Output<string | undefined>; /** * The VPC ID of the DB proxy endpoint. */ public /*out*/ readonly vpcId!: pulumi.Output<string>; /** * One or more VPC security group IDs to associate with the new proxy. */ public readonly vpcSecurityGroupIds!: pulumi.Output<string[]>; /** * One or more VPC subnet IDs to associate with the new proxy. */ public readonly vpcSubnetIds!: pulumi.Output<string[]>; /** * Create a ProxyEndpoint 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: ProxyEndpointArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ProxyEndpointArgs | ProxyEndpointState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ProxyEndpointState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["dbProxyEndpointName"] = state ? state.dbProxyEndpointName : undefined; inputs["dbProxyName"] = state ? state.dbProxyName : undefined; inputs["endpoint"] = state ? state.endpoint : undefined; inputs["isDefault"] = state ? state.isDefault : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["targetRole"] = state ? state.targetRole : undefined; inputs["vpcId"] = state ? state.vpcId : undefined; inputs["vpcSecurityGroupIds"] = state ? state.vpcSecurityGroupIds : undefined; inputs["vpcSubnetIds"] = state ? state.vpcSubnetIds : undefined; } else { const args = argsOrState as ProxyEndpointArgs | undefined; if ((!args || args.dbProxyEndpointName === undefined) && !opts.urn) { throw new Error("Missing required property 'dbProxyEndpointName'"); } if ((!args || args.dbProxyName === undefined) && !opts.urn) { throw new Error("Missing required property 'dbProxyName'"); } if ((!args || args.vpcSubnetIds === undefined) && !opts.urn) { throw new Error("Missing required property 'vpcSubnetIds'"); } inputs["dbProxyEndpointName"] = args ? args.dbProxyEndpointName : undefined; inputs["dbProxyName"] = args ? args.dbProxyName : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["targetRole"] = args ? args.targetRole : undefined; inputs["vpcSecurityGroupIds"] = args ? args.vpcSecurityGroupIds : undefined; inputs["vpcSubnetIds"] = args ? args.vpcSubnetIds : undefined; inputs["arn"] = undefined /*out*/; inputs["endpoint"] = undefined /*out*/; inputs["isDefault"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; inputs["vpcId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ProxyEndpoint.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ProxyEndpoint resources. */ export interface ProxyEndpointState { /** * The Amazon Resource Name (ARN) for the proxy endpoint. */ arn?: pulumi.Input<string>; /** * The identifier for the proxy endpoint. An identifier must begin with a letter and must contain only ASCII letters, digits, and hyphens; it can't end with a hyphen or contain two consecutive hyphens. */ dbProxyEndpointName?: pulumi.Input<string>; /** * The name of the DB proxy associated with the DB proxy endpoint that you create. */ dbProxyName?: pulumi.Input<string>; /** * The endpoint that you can use to connect to the proxy. You include the endpoint value in the connection string for a database client application. */ endpoint?: pulumi.Input<string>; /** * Indicates whether this endpoint is the default endpoint for the associated DB proxy. */ isDefault?: pulumi.Input<boolean>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Indicates whether the DB proxy endpoint can be used for read/write or read-only operations. The default is `READ_WRITE`. Valid values are `READ_WRITE` and `READ_ONLY`. */ targetRole?: pulumi.Input<string>; /** * The VPC ID of the DB proxy endpoint. */ vpcId?: pulumi.Input<string>; /** * One or more VPC security group IDs to associate with the new proxy. */ vpcSecurityGroupIds?: pulumi.Input<pulumi.Input<string>[]>; /** * One or more VPC subnet IDs to associate with the new proxy. */ vpcSubnetIds?: pulumi.Input<pulumi.Input<string>[]>; } /** * The set of arguments for constructing a ProxyEndpoint resource. */ export interface ProxyEndpointArgs { /** * The identifier for the proxy endpoint. An identifier must begin with a letter and must contain only ASCII letters, digits, and hyphens; it can't end with a hyphen or contain two consecutive hyphens. */ dbProxyEndpointName: pulumi.Input<string>; /** * The name of the DB proxy associated with the DB proxy endpoint that you create. */ dbProxyName: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Indicates whether the DB proxy endpoint can be used for read/write or read-only operations. The default is `READ_WRITE`. Valid values are `READ_WRITE` and `READ_ONLY`. */ targetRole?: pulumi.Input<string>; /** * One or more VPC security group IDs to associate with the new proxy. */ vpcSecurityGroupIds?: pulumi.Input<pulumi.Input<string>[]>; /** * One or more VPC subnet IDs to associate with the new proxy. */ vpcSubnetIds: pulumi.Input<pulumi.Input<string>[]>; }
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { Http, Headers, URLSearchParams } from '@angular/http'; import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; import { Response, ResponseContentType } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import '../rxjs-operators'; import { Attendance } from '../model/attendance'; import { InlineResponse200 } from '../model/inlineResponse200'; import { InlineResponse2001 } from '../model/inlineResponse2001'; import { InlineResponse2002 } from '../model/inlineResponse2002'; import { InlineResponse2003 } from '../model/inlineResponse2003'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @Injectable() export class AttendanceService { protected basePath = 'http://localhost:3000/api'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (basePath) { this.basePath = basePath; } if (configuration) { this.configuration = configuration; this.basePath = basePath || configuration.basePath || this.basePath; } } /** * * Extends object by coping non-existing properties. * @param objA object to be extended * @param objB source object */ private extendObj<T1,T2>(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ (objA as any)[key] = (objB as any)[key]; } } return <T1&T2>objA; } /** * @param consumes string[] mime-types * @return true: consumes contains 'multipart/form-data', false: otherwise */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; for (let consume of consumes) { if (form === consume) { return true; } } return false; } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public attendanceCount(where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> { return this.attendanceCountWithHttpInfo(where, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public attendanceCreate(data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a change stream. * * @param options */ public attendanceCreateChangeStreamGetAttendancesChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.attendanceCreateChangeStreamGetAttendancesChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Create a change stream. * * @param options */ public attendanceCreateChangeStreamPostAttendancesChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.attendanceCreateChangeStreamPostAttendancesChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Deletes all data. * */ public attendanceDeleteAllAttendances(extraHttpRequestParams?: any): Observable<InlineResponse2003> { return this.attendanceDeleteAllAttendancesWithHttpInfo(extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public attendanceDeleteById(id: string, extraHttpRequestParams?: any): Observable<any> { return this.attendanceDeleteByIdWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public attendanceExistsGetAttendancesidExists(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.attendanceExistsGetAttendancesidExistsWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public attendanceExistsHeadAttendancesid(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.attendanceExistsHeadAttendancesidWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public attendanceFind(filter?: string, extraHttpRequestParams?: any): Observable<Array<Attendance>> { return this.attendanceFindWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public attendanceFindById(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceFindByIdWithHttpInfo(id, filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public attendanceFindOne(filter?: string, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceFindOneWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Generates random attendances for all past events. * */ public attendanceGenerateRandomAttendances(extraHttpRequestParams?: any): Observable<Array<any>> { return this.attendanceGenerateRandomAttendancesWithHttpInfo(extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public attendancePatchOrCreate(data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendancePatchOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Attendance id * @param data An object of model property name/value pairs */ public attendancePrototypePatchAttributes(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendancePrototypePatchAttributesWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public attendanceReplaceByIdPostAttendancesidReplace(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceReplaceByIdPostAttendancesidReplaceWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public attendanceReplaceByIdPutAttendancesid(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceReplaceByIdPutAttendancesidWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public attendanceReplaceOrCreatePostAttendancesReplaceOrCreate(data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceReplaceOrCreatePostAttendancesReplaceOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public attendanceReplaceOrCreatePutAttendances(data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceReplaceOrCreatePutAttendancesWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public attendanceUpdateAll(where?: string, data?: Attendance, extraHttpRequestParams?: any): Observable<InlineResponse2002> { return this.attendanceUpdateAllWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public attendanceUpsertWithWhere(where?: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Attendance> { return this.attendanceUpsertWithWhereWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public attendanceCountWithHttpInfo(where?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/count'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public attendanceCreateWithHttpInfo(data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public attendanceCreateChangeStreamGetAttendancesChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (options !== undefined) { queryParameters.set('options', <any>options); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public attendanceCreateChangeStreamPostAttendancesChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header let consumes: string[] = [ 'application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml' ]; let canConsumeForm = this.canConsumeForm(consumes); let useForm = false; let formParams = new (useForm ? FormData : URLSearchParams as any)() as { set(param: string, value: any): void; }; // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; if (options !== undefined) { formParams.set('options', <any>options); } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: formParams, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Deletes all data. * */ public attendanceDeleteAllAttendancesWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/deleteAll'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public attendanceDeleteByIdWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendanceDeleteById.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public attendanceExistsGetAttendancesidExistsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}/exists' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendanceExistsGetAttendancesidExists.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public attendanceExistsHeadAttendancesidWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendanceExistsHeadAttendancesid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Head, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public attendanceFindWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public attendanceFindByIdWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendanceFindById.'); } if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public attendanceFindOneWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/findOne'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Generates random attendances for all past events. * */ public attendanceGenerateRandomAttendancesWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/generateRandomAttendances'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public attendancePatchOrCreateWithHttpInfo(data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Attendance id * @param data An object of model property name/value pairs */ public attendancePrototypePatchAttributesWithHttpInfo(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendancePrototypePatchAttributes.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public attendanceReplaceByIdPostAttendancesidReplaceWithHttpInfo(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}/replace' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendanceReplaceByIdPostAttendancesidReplace.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public attendanceReplaceByIdPutAttendancesidWithHttpInfo(id: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling attendanceReplaceByIdPutAttendancesid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public attendanceReplaceOrCreatePostAttendancesReplaceOrCreateWithHttpInfo(data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/replaceOrCreate'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public attendanceReplaceOrCreatePutAttendancesWithHttpInfo(data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public attendanceUpdateAllWithHttpInfo(where?: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/update'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public attendanceUpsertWithWhereWithHttpInfo(where?: string, data?: Attendance, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Attendances/upsertWithWhere'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } }
the_stack
import { Ticker24 } from "./core/Ticker24"; import { Ease24 } from "./Ease24"; export declare class Tween24 { static readonly VERSION: string; private static readonly _TYPE_TWEEN; private static readonly _TYPE_TWEEN_VELOCITY; private static readonly _TYPE_TWEEN_TEXT; private static readonly _TYPE_TWEEN_TEXT_VELOCITY; private static readonly _TYPE_PROP; private static readonly _TYPE_PROP_TEXT; private static readonly _TYPE_WAIT; private static readonly _TYPE_WAIT_EVENT; private static readonly _TYPE_WAIT_EVENT_AND_FUNC; private static readonly _TYPE_SERIAL; private static readonly _TYPE_PARALLEL; private static readonly _TYPE_LAG; private static readonly _TYPE_LOOP; private static readonly _TYPE_FUNC; private static readonly _TYPE_IF_CASE; private static readonly _TYPE_IF_CASE_BY_FUNC; static ticker: Ticker24; static ease: Ease24; private static _playingTweens; private static _manualPlayingTweens; private static _playingTweensByTarget; private static _tweensById; private static _tweensByGroupId; private static _defaultEasing; private static _debugMode; private static _numCreateTween; private _singleTarget; private _multiTarget; private _easing; private _type; private _time; private _velocity; private _delayTime; private _startTime; private _progress; private _debugMode; private _numLayers; private _serialNumber; private _tweenId; private _tweenGroupId; private _targetString; private _targetQuery; private _useWillChange; private _objectUpdater; private _objectMultiUpdater; private _transformUpdater; private _transformMultiUpdater; private _styleUpdater; private _styleMultiUpdater; private _allUpdaters; private _root; private _parent; private _next; private _isDOM; private _isRoot; private _isManual; private _isTrigger; private _inited; private _played; private _paused; private _skiped; private _eventWaiting; private _firstUpdated; private _isContainerTween; private _createdBasicUpdater; private _functionExecuters; private _firstTween; private _childTween; private _playingChildTween; private _originalChildTween; private _numChildren; private _numCompleteChildren; private _lagTime; private _totalLagTime; private _lagSort; private _lagEasing; private _numLoops; private _currentLoops; private _ifFunc; private _trueTween; private _falseTween; private _dispatchEventTarget; private _dispatchEventType; private _triggered; private _jumped; private _jumpProg; __fps: number; __beforeTime: number; constructor(); /** * トゥイーンを再生します。 * @memberof Tween24 */ play: () => void; /** * トゥイーンを手動アップデート式で再生します。 * 関数 manualUpdate() を実行すると更新されます。 * @memberof Tween24 */ manualPlay: () => void; private _commonRootPlay; private _play; private _resume; /** * トゥイーンを一時停止します。 * @memberof Tween24 */ pause: () => void; /** * トゥイーンを終点までスキップします。 * @memberof Tween24 */ skip: () => void; private _skip; /** * トゥイーンを停止します。 * @memberof Tween24 */ stop: () => void; private _stop; private _initParam; private _overwrite; private _setIfCaseTween; manualUpdate: () => void; __update(nowTime: number): void; private _complete; private _tweenStop; private _completeChildTween; private _playNextTween; private _updateProgress; /** * 目標とするX座標を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * また、パーセント値で指定された場合は、囲みボックスの寸法に対する相対値が設定されます。 * @param {number|string} value X座標 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ x(value: number | string): Tween24; /** * 目標とするY座標を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * また、パーセント値で指定された場合は、囲みボックスの寸法に対する相対値が設定されます。 * @param {number|string} value Y座標 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ y(value: number | string): Tween24; /** * 目標とするXとY座標を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * また、パーセント値で指定された場合は、囲みボックスの寸法に対する相対値が設定されます。 * @param {number|string} x X座標 * @param {number|string} y Y座標 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ xy(x: number | string, y: number | string): Tween24; /** * 目標とする透明度を設定します。 * 対象が HTMLElement の場合は、CSS:opacity が適用されます。 * @param {number} value 透明度 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ alpha(value: number): Tween24; /** * 目標とする透明度を設定します。 * @param {number} value 透明度 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ opacity(value: number): Tween24; /** * 目標とする水平スケールを設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 水平方向のスケール * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ scaleX(value: number): Tween24; /** * 目標とする垂直スケールを設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 垂直方向のスケール * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ scaleY(value: number): Tween24; /** * 目標とするスケールを設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 水平&垂直方向のスケール * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ scale(value: number): Tween24; /** * 目標とする水平・垂直スケールを設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} scaleX 水平方向のスケール * @param {number} scaleY 垂直方向のスケール * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ scaleXY(scaleX: number, scaleY: number): Tween24; /** * 目標とする水平傾斜を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 水平方向の傾斜 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ skewX(value: number): Tween24; /** * 目標とする垂直傾斜を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 垂直方向の傾斜 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ skewY(value: number): Tween24; /** * 目標とする水平&垂直傾斜を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 水平&垂直方向の傾斜 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ skew(value: number): Tween24; /** * 目標とする水平・垂直傾斜を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} skewX 水平方向の傾斜 * @param {number} skewY 垂直方向の傾斜 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ skewXY(skewX: number, skewY: number): Tween24; /** * 目標とする回転角度を設定します。 * 対象が HTMLElement の場合は、CSS:Transform が適用されます。 * @param {number} value 回転角度 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ rotation(value: number): Tween24; /** * 目標とする角度を設定します。 * @param {number} value 角度 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ angle(value: number): Tween24; /** * CSS:top を設定します。 * @param {number|string} 上からの配置位置(距離) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ top(value: number | string): Tween24; /** * CSS:right を設定します。 * @param {number|string} 右からの配置位置(距離) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ right(value: number | string): Tween24; /** * CSS:bottom を設定します。 * @param {number|string} value 下からの配置位置(距離) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ bottom(value: number | string): Tween24; /** * CSS:left を設定します。 * @param {number|string} value 左からの配置位置(距離) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ left(value: number | string): Tween24; /** * 目標とする幅を設定します。 * 対象が HTMLElement の場合は、CSS:width が適用されます。 * @param {number|string} value 要素の幅 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ width(value: number | string): Tween24; /** * 目標とする高さを設定します。 * 対象が HTMLElement の場合は、CSS:height が適用されます。 * @param {number|string} value 要素の高さ * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ height(value: number | string): Tween24; /** * CSS:color を設定します。 * @param {string} colorCode 「#」「rgb()」フォーマットのカラー値 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ color(colorCode: string): Tween24; /** * CSS:background-color(背景色)を設定します。 * @param {string} colorCode 「#」「rgb()」フォーマットのカラー値 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ backgroundColor(colorCode: string): Tween24; /** * CSS:border-width(枠の太さ)を設定します。 * @param {number|string} value 枠の太さ * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ borderWidth(value: number | string): Tween24; /** * CSS:border-color(枠の色)を設定します。 * @param {number} colorCode 「#」「rgb()」フォーマットのカラー値 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ borderColor(colorCode: string): Tween24; /** * CSS:border-radius(角丸)を設定します。 * @param {number|string} value 角丸の値 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ borderRadius(value: number | string): Tween24; /** * CSS:letter-spacing(字間)を設定します。 * @param {number|string} value 字間 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ letterSpacing(value: number | string): Tween24; /** * トゥイーンの遅延時間を設定します。 * @param {number} value 遅延時間(秒数) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ delay(value: number): Tween24; /** * 目標とするスタイルシートの値を設定します。 * 対象が HTMLElement の場合にのみ適用されます。 * @param {string} name プロパティ名 * @param {(number|string)} value 目標の値(数値指定の場合は、基本的にpx単位で計算されます) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ style(name: string, value: number | string): Tween24; /** * トゥイーン実行時に willChange を有効にするか設定します。 * 有効にすると強力な最適化をブラウザーが行い、アニメーションが滑らかになります。 * 対象が HTMLElement の場合にのみ適用されます。 * @param {boolean} [use=true] * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ willChange(use?: boolean): Tween24; /** * 子トゥイーンの完了トリガーに設定します。 * 設定したトゥイーンが完了したら、親トゥイーンが次のトゥイーンへ移行します。 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ trigger(): Tween24; /** * トゥイーンの途中で、次のトゥイーンへ移行します。 * @param {number} progress 移行させる進捗率 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ jump(progress: number): Tween24; /** * トゥイーン毎のFPS(1秒間の更新回数)を設定します。 * デフォルトでは0が設定され、ブラウザのリフレッシュレートに合わせて描画更新されます。 * (※ 子以下のトゥイーンには設定できません。) * @param {number} fps FPSの値 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ fps(fps: number): Tween24; /** * トゥイーンのデバッグモードを設定します。 * デバッグモードをONにすると、トゥイーンの動作状況がコンソールに表示されます。 * @param {boolean} flag デバッグモードを使用するか * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ debug(flag?: boolean): Tween24; private _setPropety; private _setPropetyStr; private _setStyle; private createBasicUpdater; /** * トゥイーン再生時に、実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onPlay(func: Function, ...args: any[]): Tween24; /** * トゥイーン開始時に、実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onInit(func: Function, ...args: any[]): Tween24; /** * トゥイーン実行中に、実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onUpdate(func: Function, ...args: any[]): Tween24; /** * トゥイーンが一時停止した時に、実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onPause(func: Function, ...args: any[]): Tween24; /** * トゥイーンが一時停止中から、再開した時に実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onResume(func: Function, ...args: any[]): Tween24; /** * トゥイーンが停止された時に、実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onStop(func: Function, ...args: any[]): Tween24; /** * トゥイーンが完了した時に、実行する関数を設定します。 * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ onComplete(func: Function, ...args: any[]): Tween24; private _setFunctionExecute; private _functionExecute; /** * トゥイーンを設定します。 * @static * @param {*} target 対象オブジェクト * @param {number} time 時間(秒) * @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear) * @param {({[key:string]:number}|null)} [params=null] トゥイーンさせるパラメータ(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static tween(target: any, time: number, easing?: Function | null, params?: { [key: string]: number; } | null): Tween24; /** * 速度を指定するトゥイーンを設定します。 * * このトゥイーンは、指定された速度とパラメータの変化量から時間を自動設定します。 * 複数パラメータを変化させる場合、変化量の一番大きい値を基準にします。 * x,y の座標系パラメータは、計算後の距離を変化量とします。 * @static * @param {*} target 対象オブジェクト * @param {number} velocity 1秒間の変化量(速度) * @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear) * @param {({ [key: string]: number } | null)} [params=null] トゥイーンさせるパラメータ(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static tweenVelocity(target: any, velocity: number, easing?: Function | null, params?: { [key: string]: number; } | null): Tween24; /** * プロパティを設定します。 * @static * @param {*} target 対象オブジェクト * @param {({[key:string]:number}|null)} [params=null] 設定するパラメータ(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static prop(target: any, params?: { [key: string]: number; } | null): Tween24; /** * クエリで指定した要素直下のテキストを1文字ずつに分解し、それぞれにプロパティを設定します。 * @static * @param {string} targetQuery 対象要素を指定するクエリ * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static propText(targetQuery: string): Tween24; /** * クエリで指定した要素直下のテキストを1文字ずつに分解し、それぞれにトゥイーンを設定します。 * @static * @param {string} targetQuery 対象要素を指定するクエリ * @param {number} time 時間(秒) * @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static tweenText(targetQuery: string, time: number, easing?: Function | null): Tween24; /** * 1文字ずつに分解したテキストを、元に戻します。 * @static * @param {string} targetQuery 対象要素を指定するクエリ * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static resetText(targetQuery: string): Tween24; /** * クエリで指定した要素直下のテキストを1文字ずつに分解し、それぞれに速度を指定するトゥイーンを設定します。 * * このトゥイーンは、指定された速度とパラメータの変化量から時間を自動設定します。 * 複数パラメータを変化させる場合、変化量の一番大きい値を基準にします。 * x,y の座標系パラメータは、計算後の距離を変化量とします。 * @static * @param {string} targetQuery 対象要素を指定するクエリ * @param {number} velocity 1秒間の変化量(速度) * @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static tweenTextVelocity(targetQuery: string, velocity: number, easing?: Function | null): Tween24; private static _tweenText; /** * トゥイーンを待機します。 * @static * @param {number} time 待機時間(秒) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static wait(time: number): Tween24; /** * 関数を実行します。 * @static * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static func(func: Function, ...args: any[]): Tween24; /** * イベントを受け取るまで、待機します。 * @static * @param {*} target イベントを受け取る対象 * @param {string} type 受け取るイベントタイプ * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static waitEvent(target: any, type: string): Tween24; /** * 指定した関数を実行し、イベントを受け取るまで待機します。 * @static * @param {*} target イベントを受け取る対象 * @param {string} type 受け取るイベントタイプ * @param {Function} func 実行する関数 * @param {...any[]} args 引数(省略可) * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static waitEventAndFunc(target: any, type: string, func: Function, ...args: any[]): Tween24; private _setWaitEvent; /** * console.log() を実行します。 * @static * @param {...any[]} message コンソールに出力する内容 * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static log(...message: any[]): Tween24; /** * 順番に実行するトゥイーンを設定します。 * @static * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static serial(...childTween: Tween24[]): Tween24; /** * 並列に実行するトゥイーンを設定します。 * @static * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static parallel(...childTween: Tween24[]): Tween24; /** * 子トゥイーンの対象が複数指定されていた場合、時差を設定します。 * @static * @param {number} lagTime 対象毎の時差(秒数) * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static lag(lagTime: number, ...childTween: Tween24[]): Tween24; /** * 子トゥイーンの対象が複数指定されていた場合、再生順をソートして時差を設定します。 * @static * @param {number} lagTime 対象毎の時差(秒数) * @param {Function} sort 再生順をソートする関数 * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static lagSort(lagTime: number, sort: Function, ...childTween: Tween24[]): Tween24; /** * 子トゥイーンの対象が複数指定されていた場合、トータル時間を元に時差を設定します。 * @static * @param {number} totalLagTime 時差のトータル時間(秒数) * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static lagTotal(totalLagTime: number, ...childTween: Tween24[]): Tween24; /** * 子トゥイーンの対象が複数指定されていた場合、トータル時間を元にイージングをかけながら時差を設定します。 * @static * @param {number} totalLagTime 時差のトータル時間(秒数) * @param {Function} easing 時差の時間量のイージング * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static lagTotalEase(totalLagTime: number, easing: Function, ...childTween: Tween24[]): Tween24; /** * 子トゥイーンの対象が複数指定されていた場合、再生順をソートして、トータル時間を元に時差を設定します。 * @static * @param {number} totalLagTime 時差のトータル時間(秒数) * @param {Function} sort 再生順をソートする関数 * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static lagTotalSort(totalLagTime: number, sort: Function, ...childTween: Tween24[]): Tween24; /** * 子トゥイーンの対象が複数指定されていた場合、再生順をソートして、トータル時間を元にイージングをかけながら時差を設定します。 * @static * @param {number} totalLagTime 時差のトータル時間(秒数) * @param {Function} sort 再生順をソートする関数 * @param {Function} easing 時差の時間量のイージング * @param {...Tween24[]} childTween 実行するトゥイーンたち * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static lagTotalSortEase(totalLagTime: number, sort: Function, easing: Function, ...childTween: Tween24[]): Tween24; /** * 繰り返し再生させるトゥイーンを設定します。 * ループ回数に「0」を指定すると、無制限に繰り返します。 * @static * @param {number} numLoops ループさせる回数 * @param {Tween24} tween ループさせるトゥイーン * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static loop(numLoops: number, tween: Tween24): Tween24; /** * フラグに応じて再生するトゥイーンを設定します。 * フラグにboolean値を渡した場合はトゥイーン作成時に判定し、boolean値を返す関数を渡した場合はトゥイーン実行毎に判定します。 * @static * @param {boolean|(()=>boolean)} flag boolean値か、boolean値を返す関数 * @param {Tween24} trueTween フラグが true の時に再生するトゥイーン * @param {(Tween24|null)} [falseTween=null] フラグが false の時に再生するトゥイーン * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ static ifCase(flag: boolean | (() => boolean), trueTween: Tween24, falseTween?: Tween24 | null): Tween24; /** * トゥイーン実行時に boolean 値を返す関数を実行し、再生するトゥイーンを設定します。 * @static * @param {()=>boolean} func boolean値を返す関数 * @param {Tween24} trueTween フラグが true の時に再生するトゥイーン * @param {(Tween24|null)} [falseTween=null] フラグが false の時に再生するトゥイーン * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ private _createChildTween; private _createContainerTween; private _createActionTween; private _commonProcess; /** * トゥイーンのIDを設定します。 * @param {string} id トゥイーンのID * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ id(id: string): Tween24; /** * 指定したIDのトゥイーンの play() を実行します。 * @static * @param {string} id トゥイーンのID * @memberof Tween24 */ static playById: (id: string) => void; /** * 指定したIDのトゥイーンの manualPlay() を実行します。 * @static * @param {string} id トゥイーンのID * @memberof Tween24 */ static manualPlayById: (id: string) => void; /** * 指定したIDのトゥイーンの pause() を実行します。 * @static * @param {string} id トゥイーンのID * @memberof Tween24 */ static pauseById: (id: string) => void; /** * 指定したIDのトゥイーンの skip() を実行します。 * @static * @param {string} id トゥイーンのID * @memberof Tween24 */ static skipById: (id: string) => void; /** * 指定したIDのトゥイーンの stop() を実行します。 * @static * @param {string} id トゥイーンのID * @memberof Tween24 */ static stopById: (id: string) => void; /** * トゥイーンのグループIDを設定します。 * @param {string} groupId トゥイーンのグループID * @return {Tween24} Tween24インスタンス * @memberof Tween24 */ groupId(groupId: string): Tween24; /** * 指定したグループIDのトゥイーンの play() を実行します。 * @static * @param {string} groupId トゥイーンのID * @memberof Tween24 */ static playByGroupId: (groupId: string) => void; /** * 指定したグループIDのトゥイーンの manualPlay() を実行します。 * @static * @param {string} groupId トゥイーンのID * @memberof Tween24 */ static manualPlayByGroupId: (groupId: string) => void; /** * 指定したグループIDのトゥイーンの pause() を実行します。 * @static * @param {string} groupId トゥイーンのID * @memberof Tween24 */ static pauseByGroupId: (groupId: string) => void; /** * 指定したグループIDのトゥイーンの skip() を実行します。 * @static * @param {string} groupId トゥイーンのID * @memberof Tween24 */ static skipByGroupId: (groupId: string) => void; /** * 指定したグループIDのトゥイーンの stop() を実行します。 * @static * @param {string} groupId トゥイーンのID * @memberof Tween24 */ static stopByGroupId: (groupId: string) => void; private _setTweenId; private _setTweenGroupId; private static _getTweensById; private static _getTweensByGroupId; private static _controlTweens; /** * トゥイーン全体のFPS(1秒間の更新回数)を設定します。 * デフォルトでは0が設定され、ブラウザのリフレッシュレートに合わせて描画更新されます。 * @static * @param {number} [fps=0] FPSの値 * @memberof Tween24 */ static setFPS: (fps?: number) => void; /** * デフォルトのイージングを設定します。 * @static * @param {Function} [easing=Ease24._Linear] デフォルトのイージング * @memberof Tween24 */ static setDefaultEasing: (easing?: Function) => void; /** * トゥイーン全体のデバッグモードを設定します。 * デバッグモードをONにすると、トゥイーンの動作状況がコンソールに表示されます。 * @static * @param {boolean} flag デバッグモードを使用するか * @memberof Tween24 */ static debugMode: (flag: boolean) => void; static manualAllUpdate: () => void; __clone(base: any, baseQuery: string | null): Tween24; toString(): string; private _debugLog; private _warningLog; private getTweenTypeString; private getTweenParamString; }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [wafv2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswafv2.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Wafv2 extends PolicyStatement { public servicePrefix = 'wafv2'; /** * Statement provider for service [wafv2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswafv2.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 associate a WebACL with a resource * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_AssociateWebACL.html */ public toAssociateWebACL() { return this.to('AssociateWebACL'); } /** * Grants permission to calculate web ACL capacity unit (WCU) requirements for a specified scope and set of rules * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/APIReference/API_CheckCapacity.html */ public toCheckCapacity() { return this.to('CheckCapacity'); } /** * Grants permission to create an IPSet * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_CreateIPSet.html */ public toCreateIPSet() { return this.to('CreateIPSet'); } /** * Grants permission to create a RegexPatternSet * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_CreateRegexPatternSet.html */ public toCreateRegexPatternSet() { return this.to('CreateRegexPatternSet'); } /** * Grants permission to create a RuleGroup * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_CreateRuleGroup.html */ public toCreateRuleGroup() { return this.to('CreateRuleGroup'); } /** * Grants permission to create a WebACL * * Access Level: Permissions management * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_CreateWebACL.html */ public toCreateWebACL() { return this.to('CreateWebACL'); } /** * Grants permission to delete FirewallManagedRulesGroups from a WebACL if not managed by Firewall Manager anymore * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteFirewallManagerRuleGroups.html */ public toDeleteFirewallManagerRuleGroups() { return this.to('DeleteFirewallManagerRuleGroups'); } /** * Grants permission to delete an IPSet * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteIPSet.html */ public toDeleteIPSet() { return this.to('DeleteIPSet'); } /** * Grants permission to delete the LoggingConfiguration from a WebACL * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteLoggingConfiguration.html */ public toDeleteLoggingConfiguration() { return this.to('DeleteLoggingConfiguration'); } /** * Grants permission to delete the PermissionPolicy on a RuleGroup * * Access Level: Permissions management * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeletePermissionPolicy.html */ public toDeletePermissionPolicy() { return this.to('DeletePermissionPolicy'); } /** * Grants permission to delete a RegexPatternSet * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteRegexPatternSet.html */ public toDeleteRegexPatternSet() { return this.to('DeleteRegexPatternSet'); } /** * Grants permission to delete a RuleGroup * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteRuleGroup.html */ public toDeleteRuleGroup() { return this.to('DeleteRuleGroup'); } /** * Grants permission to delete a WebACL * * Access Level: Permissions management * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteWebACL.html */ public toDeleteWebACL() { return this.to('DeleteWebACL'); } /** * Grants permission to retrieve high-level information for a managed rule group * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DescribeManagedRuleGroup.html */ public toDescribeManagedRuleGroup() { return this.to('DescribeManagedRuleGroup'); } /** * Grants permission to disassociate Firewall Manager from a WebACL * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DisassociateFirewallManager.html */ public toDisassociateFirewallManager() { return this.to('DisassociateFirewallManager'); } /** * Grants permission disassociate a WebACL from an application resource * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_DisassociateWebACL.html */ public toDisassociateWebACL() { return this.to('DisassociateWebACL'); } /** * Grants permission to retrieve details about an IPSet * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetIPSet.html */ public toGetIPSet() { return this.to('GetIPSet'); } /** * Grants permission to retrieve LoggingConfiguration for a WebACL * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetLoggingConfiguration.html */ public toGetLoggingConfiguration() { return this.to('GetLoggingConfiguration'); } /** * Grants permission to retrieve a PermissionPolicy for a RuleGroup * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetPermissionPolicy.html */ public toGetPermissionPolicy() { return this.to('GetPermissionPolicy'); } /** * Grants permission to retrieve the keys that are currently blocked by a rate-based rule * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetRateBasedStatementManagedKeys.html */ public toGetRateBasedStatementManagedKeys() { return this.to('GetRateBasedStatementManagedKeys'); } /** * Grants permission to retrieve details about a RegexPatternSet * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetRegexPatternSet.html */ public toGetRegexPatternSet() { return this.to('GetRegexPatternSet'); } /** * Grants permission to retrieve details about a RuleGroup * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetRuleGroup.html */ public toGetRuleGroup() { return this.to('GetRuleGroup'); } /** * Grants permission to retrieve detailed information about a sampling of web requests * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetSampledRequests.html */ public toGetSampledRequests() { return this.to('GetSampledRequests'); } /** * Grants permission to retrieve details about a WebACL * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetWebACL.html */ public toGetWebACL() { return this.to('GetWebACL'); } /** * Grants permission to retrieve the WebACL that's associated with a resource * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/APIReference/API_GetWebACLForResource.html */ public toGetWebACLForResource() { return this.to('GetWebACLForResource'); } /** * Grants permission to retrieve an array of managed rule groups that are available for you to use * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListAvailableManagedRuleGroups.html */ public toListAvailableManagedRuleGroups() { return this.to('ListAvailableManagedRuleGroups'); } /** * Grants permission to retrieve an array of IPSetSummary objects for the IP sets that you manage * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListIPSets.html */ public toListIPSets() { return this.to('ListIPSets'); } /** * Grants permission to retrieve an array of your LoggingConfiguration objects * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListLoggingConfigurations.html */ public toListLoggingConfigurations() { return this.to('ListLoggingConfigurations'); } /** * Grants permission to retrieve an array of RegexPatternSetSummary objects for the regex pattern sets that you manage * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListRegexPatternSets.html */ public toListRegexPatternSets() { return this.to('ListRegexPatternSets'); } /** * Grants permission to retrieve an array of the Amazon Resource Names (ARNs) for the resources that are associated with a web ACL * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListResourcesForWebACL.html */ public toListResourcesForWebACL() { return this.to('ListResourcesForWebACL'); } /** * Grants permission to retrieve an array of RuleGroupSummary objects for the rule groups that you manage * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListRuleGroups.html */ public toListRuleGroups() { return this.to('ListRuleGroups'); } /** * Grants permission to list tags for a resource * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to retrieve an array of WebACLSummary objects for the web ACLs that you manage * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/APIReference/API_ListWebACLs.html */ public toListWebACLs() { return this.to('ListWebACLs'); } /** * Grants permission to create FirewallManagedRulesGroups in a WebACL * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/APIReference/API_PutFirewallManagerRuleGroups.html */ public toPutFirewallManagerRuleGroups() { return this.to('PutFirewallManagerRuleGroups'); } /** * Grants permission to enable a LoggingConfiguration, to start logging for a web ACL * * Access Level: Write * * Dependent actions: * - iam:CreateServiceLinkedRole * * https://docs.aws.amazon.com/waf/latest/APIReference/API_PutLoggingConfiguration.html */ public toPutLoggingConfiguration() { return this.to('PutLoggingConfiguration'); } /** * Grants permission to attach an IAM policy to a resource, used to share rule groups between accounts * * Access Level: Permissions management * * https://docs.aws.amazon.com/waf/latest/APIReference/API_PutPermissionPolicy.html */ public toPutPermissionPolicy() { return this.to('PutPermissionPolicy'); } /** * Grants permission to associate tags with a AWS resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to disassociate tags from an AWS resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update an IPSet * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_UpdateIPSet.html */ public toUpdateIPSet() { return this.to('UpdateIPSet'); } /** * Grants permission to update a RegexPatternSet * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_UpdateRegexPatternSet.html */ public toUpdateRegexPatternSet() { return this.to('UpdateRegexPatternSet'); } /** * Grants permission to update a RuleGroup * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_UpdateRuleGroup.html */ public toUpdateRuleGroup() { return this.to('UpdateRuleGroup'); } /** * Grants permission to update a WebACL * * Access Level: Permissions management * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/APIReference/API_UpdateWebACL.html */ public toUpdateWebACL() { return this.to('UpdateWebACL'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateWebACL", "CreateIPSet", "CreateRegexPatternSet", "CreateRuleGroup", "DeleteFirewallManagerRuleGroups", "DeleteIPSet", "DeleteLoggingConfiguration", "DeleteRegexPatternSet", "DeleteRuleGroup", "DisassociateFirewallManager", "DisassociateWebACL", "PutFirewallManagerRuleGroups", "PutLoggingConfiguration", "UpdateIPSet", "UpdateRegexPatternSet", "UpdateRuleGroup" ], "Read": [ "CheckCapacity", "GetIPSet", "GetLoggingConfiguration", "GetPermissionPolicy", "GetRateBasedStatementManagedKeys", "GetRegexPatternSet", "GetRuleGroup", "GetSampledRequests", "GetWebACL", "GetWebACLForResource", "ListTagsForResource" ], "Permissions management": [ "CreateWebACL", "DeletePermissionPolicy", "DeleteWebACL", "PutPermissionPolicy", "UpdateWebACL" ], "List": [ "DescribeManagedRuleGroup", "ListAvailableManagedRuleGroups", "ListIPSets", "ListLoggingConfigurations", "ListRegexPatternSets", "ListResourcesForWebACL", "ListRuleGroups", "ListWebACLs" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type webacl to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_WebACL.html * * @param scope - Identifier for the scope. * @param name - Identifier for the name. * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onWebacl(scope: string, name: string, id: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}'; arn = arn.replace('${Scope}', scope); arn = arn.replace('${Name}', name); arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ipset to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_IPSet.html * * @param scope - Identifier for the scope. * @param name - Identifier for the name. * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onIpset(scope: string, name: string, id: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/ipset/${Name}/${Id}'; arn = arn.replace('${Scope}', scope); arn = arn.replace('${Name}', name); arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type rulegroup to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_RuleGroup.html * * @param scope - Identifier for the scope. * @param name - Identifier for the name. * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onRulegroup(scope: string, name: string, id: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/rulegroup/${Name}/${Id}'; arn = arn.replace('${Scope}', scope); arn = arn.replace('${Name}', name); arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type regexpatternset to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_RegexPatternSet.html * * @param scope - Identifier for the scope. * @param name - Identifier for the name. * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onRegexpatternset(scope: string, name: string, id: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/regexpatternset/${Name}/${Id}'; arn = arn.replace('${Scope}', scope); arn = arn.replace('${Name}', name); arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type loadbalancer/app/ to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_WebACL.html * * @param loadBalancerName - Identifier for the loadBalancerName. * @param loadBalancerId - Identifier for the loadBalancerId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onLoadbalancerApp(loadBalancerName: string, loadBalancerId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}'; arn = arn.replace('${LoadBalancerName}', loadBalancerName); arn = arn.replace('${LoadBalancerId}', loadBalancerId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type apigateway to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_WebACL.html * * @param apiId - Identifier for the apiId. * @param stageName - Identifier for the stageName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onApigateway(apiId: string, stageName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:apigateway:${Region}:${Account}:/restapis/${ApiId}/stages/${StageName}'; arn = arn.replace('${ApiId}', apiId); arn = arn.replace('${StageName}', stageName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type appsync to the statement * * https://docs.aws.amazon.com/waf/latest/APIReference/API_WebACL.html * * @param graphQLAPIId - Identifier for the graphQLAPIId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAppsync(graphQLAPIId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appsync:${Region}:${Account}:apis/${GraphQLAPIId}'; arn = arn.replace('${GraphQLAPIId}', graphQLAPIId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { ComputedParameter, ConstantParameter, Parameter, ParameterComputeType, ParsedVariablePredefineFunctions, TopicFactorParameter, VariablePredefineFunctions } from '@/services/data/tuples/factor-calculator-types'; import {isDateDiffConstant} from '@/services/data/tuples/factor-calculator-utils'; import {Factor} from '@/services/data/tuples/factor-types'; import {Topic} from '@/services/data/tuples/topic-types'; import {isXaNumber} from '@/services/utils'; import dayjs from 'dayjs'; import {DataRow} from '../../../types'; import {AllTopics} from '../types'; import {ParameterShouldBe} from './types'; export const readTopicFactorParameter = (options: { parameter: TopicFactorParameter, topics: AllTopics, validOrThrow: (topicId: String) => void }): { topic: Topic, factor: Factor } => { const {parameter, topics, validOrThrow} = options; const topicId = parameter.topicId; if (!topicId || topicId.trim().length === 0) { throw new Error(`Topic id of parameter[${JSON.stringify(parameter)}] cannot be blank.`); } validOrThrow(topicId); const topic = topics[topicId]; if (!topic) { throw new Error(`Topic[${topicId}] of parameter[${JSON.stringify(parameter)}] not found.`); } const factorId = parameter.factorId; if (!factorId || factorId.trim().length === 0) { throw new Error(`Factor id of parameter[${JSON.stringify(parameter)}] cannot be blank.`); } // eslint-disable-next-line const factor = topic.factors.find(factor => factor.factorId == factorId); if (!factor) { throw new Error(`Factor[${factorId}] of parameter[${JSON.stringify(parameter)}] not found.`); } return {topic, factor}; }; export const getValueFromSourceData = (factor: Factor, sourceData: DataRow): any => { const name = factor.name!; if (!name.includes('.')) { return sourceData[name]; } else { const parts = name.split('.'); let source: any = sourceData; return parts.reduce((obj, part) => { if (obj == null) { return null; } else if (Array.isArray(obj)) { return obj.map(item => { if (typeof item === 'object') { return item[part]; } else { throw new Error(`Cannot retrieve data from ${source} by [${part}].`); } }); } else if (typeof obj === 'object') { return obj[part]; } else { throw new Error(`Cannot retrieve data from ${source} by [${part}].`); } }, source); } }; const computeToCollection = (value?: any): Array<any> => { switch (true) { case value == null: return []; case Array.isArray(value): return value; case typeof value === 'string': return value.split(',').map((s: string) => s.trim()); default: return [value]; } }; const computeToNumeric = (parameter: Parameter, value?: any): number | null => { if (value == null) { return value; } else if (!isXaNumber(value)) { throw new Error(`Cannot cast given value[${value}] to numeric, which is computed by parameter[${JSON.stringify(parameter)}].`); } else { return Number(value.toString()); } }; export const computeToDate = (parameter: Parameter, date?: any): string | null => { if (date == null) { return null; } date = date.toString().split('').map((c: string) => ' -/:.TZ'.includes(c) ? '' : c).join(''); const casted = dayjs(date); if (casted.isValid()) { // remove time return casted.startOf('day').format('YYYYMMDD'); } else { throw new Error(`Cannot cast given value[${date}] to date, which is computed by parameter[${JSON.stringify(parameter)}].`); } }; export const castParameterValueType = (options: { value?: any, shouldBe: ParameterShouldBe, parameter: Parameter }) => { const {value, shouldBe, parameter} = options; switch (shouldBe) { case ParameterShouldBe.ANY: return value; case ParameterShouldBe.COLLECTION: return computeToCollection(value); case ParameterShouldBe.NUMBER: return computeToNumeric(parameter, value); case ParameterShouldBe.DATE: return computeToDate(parameter, value); } }; // use timestamp(13 digits) instead, just for simulator let currentSnowflakeId = new Date().getTime(); const computeVariable = (options: { variable: string, getFirstValue: (propertyName: string) => any, throws: () => void }): any => { const {variable, getFirstValue, throws} = options; if (variable.trim().length === 0) { return null; } const parsedFunction = [isDateDiffConstant].reduce((ret: { is: boolean, parsed?: ParsedVariablePredefineFunctions }, parse) => { if (!ret.is) { return parse(variable); } else { return ret; } }, {is: false}); if (parsedFunction.is) { const params = parsedFunction.parsed?.params.map(p => { return computeVariable({variable: p, getFirstValue, throws}); }) || []; switch (parsedFunction.parsed?.f) { case VariablePredefineFunctions.YEAR_DIFF: { const [p1, p2] = params; return dayjs(p2).diff(p1, 'year'); } case VariablePredefineFunctions.MONTH_DIFF: { const [p1, p2] = params; return dayjs(p2).diff(p1, 'month'); } case VariablePredefineFunctions.DAY_DIFF: { const [p1, p2] = params; return dayjs(p2).diff(p1, 'day'); } default: throws(); } } // eslint-disable-next-line return variable.split('.').map(x => x.trim()).reduce((value: any, part, index) => { if (index === 0 && part === VariablePredefineFunctions.NEXT_SEQ) { return currentSnowflakeId++; } else if (index === 0) { return getFirstValue(part); } else if (value == null) { return null; } else if (part === VariablePredefineFunctions.COUNT && Array.isArray(value)) { return value.length; } else if (part === VariablePredefineFunctions.COUNT && typeof value === 'object') { return Object.keys(value).length; } else if (part === VariablePredefineFunctions.SUM && Array.isArray(value)) { // eslint-disable-next-line return value.reduce((sum, v) => { if (v == null || v.toString().trim().length === 0) { return sum; } if (!isXaNumber(v)) { throws(); } else { return sum + (v * 1); } }, 0); } else if (part === VariablePredefineFunctions.LENGTH && typeof value === 'string') { return value.length; } else if (typeof value === 'object') { return value[part]; } else if (Array.isArray(value)) { // eslint-disable-next-line return value.map(item => { if (typeof item === 'object') { return item[part]; } else { throws(); } }).flat(); } else { throws(); } }, null as any); }; const computeStatement = (statement: string, getFirstValue: (propertyName: string) => any, throws: () => void): any => { const segments = statement.match(/([^{]*({[^}]+})?)/g); if (segments == null) { // no variable return statement; } const values = segments.filter(x => x).map(segment => { const braceStartIndex = segment.indexOf('{'); if (braceStartIndex === -1) { return segment; } else if (braceStartIndex === 0) { const variable = segment.substring(1, segment.length - 1).trim(); return computeVariable({variable, getFirstValue, throws}); } else { const prefix = segment.substring(0, braceStartIndex); const variable = segment.substring(braceStartIndex + 1, segment.length - 1).trim(); return `${prefix}${computeVariable({variable, getFirstValue, throws}) ?? ''}`; } }); if (values.length === 1) { return values[0]; } else { return values.filter(x => x != null).join(''); } }; export const computeConstantByStatement = (options: { statement: string, parameter: ConstantParameter, shouldBe: ParameterShouldBe, getValue: (propertyName: string) => any }): any => { const {statement, parameter, shouldBe, getValue} = options; const value = computeStatement(statement, getValue, () => { throw new Error(`Cannot retrieve value of variable[${statement}], which is defined by parameter[${JSON.stringify(parameter)}].`); }); return castParameterValueType({value, parameter, shouldBe}); }; const checkMinSubParameterCount = (parameter: ComputedParameter, count: number) => { const size = parameter.parameters.length; if (size < count) { throw new Error(`At least ${count} sub parameter(s) in [${JSON.stringify(parameter)}], but only [${size}] now.`); } }; const checkMaxSubParameterCount = (parameter: ComputedParameter, count: number) => { const size = parameter.parameters.length; if (size > count) { throw new Error(`At most ${count} sub parameter(s) in [${JSON.stringify(parameter)}], but [${size}] now.`); } }; export const checkSubParameters = (parameter: ComputedParameter) => { switch (parameter.type) { case ParameterComputeType.NONE: break; case ParameterComputeType.ADD: case ParameterComputeType.SUBTRACT: case ParameterComputeType.MULTIPLY: case ParameterComputeType.DIVIDE: checkMinSubParameterCount(parameter, 2); break; case ParameterComputeType.MODULUS: checkMinSubParameterCount(parameter, 2); checkMaxSubParameterCount(parameter, 2); break; case ParameterComputeType.YEAR_OF: case ParameterComputeType.HALF_YEAR_OF: case ParameterComputeType.QUARTER_OF: case ParameterComputeType.MONTH_OF: case ParameterComputeType.WEEK_OF_YEAR: case ParameterComputeType.WEEK_OF_MONTH: case ParameterComputeType.DAY_OF_MONTH: case ParameterComputeType.DAY_OF_WEEK: checkMaxSubParameterCount(parameter, 1); break; case ParameterComputeType.CASE_THEN: checkMinSubParameterCount(parameter, 1); if (parameter.parameters.filter(sub => !sub.on).length > 1) { throw new Error(`Multiple anyway routes in case-then expression of [${JSON.stringify(parameter)}] is not allowed.`); } } }; export const checkShouldBe = (parameter: ComputedParameter, shouldBe: ParameterShouldBe) => { const type = parameter.type; if (type === ParameterComputeType.NONE) { } else if (type === ParameterComputeType.CASE_THEN) { } else if (shouldBe === ParameterShouldBe.ANY) { } else if (shouldBe === ParameterShouldBe.COLLECTION) { // anything can be cast to collection, // collection is collection itself, // non-collection is the only element of collection } else if (shouldBe === ParameterShouldBe.DATE) { // cannot get date by computing except case-then throw new Error(`Cannot get date result on parameter[${JSON.stringify(parameter)}].`); } else if (shouldBe === ParameterShouldBe.NUMBER) { } };
the_stack
module CorsicaTests { "use strict"; var global: any = window; global.MyCustomInitializer1 = WinJS.Binding.initializer(function (s, sp, d, dp) { return WinJS.Binding.defaultBind(s, sp, d, dp); }); global.MyCustomInitializer2 = WinJS.Binding.initializer(function (s, sp, d, dp) { return WinJS.Binding.defaultBind(s, sp, d, dp); }); global.MyCustomInitializer2.delayable = true; global.MyCustomDoNothingInitializer = WinJS.Binding.initializer(function () { // do nothing }); class MyCustomControlDeclarativeControlContainer { element; _delayedProcessing: any[]; _delayedProcessed: boolean; constructor(element, options) { this.element = element || document.createElement("div"); this.element.winControl = this; this.element.classList.add("mycustomcontroldeclarativecontrolcontainer"); } get delayedProcessorCount() { return (this._delayedProcessing && this._delayedProcessing.length) || 0; } runDelayedProcessing() { if (this.delayedProcessorCount) { var children = this.element.children; this._delayedProcessing.forEach(function (processor) { for (var i = 0; i < children.length; i++) { processor(children[i]); } }); this._delayedProcessing = null; this._delayedProcessed = true; } } static isDeclarativeControlContainer(control, callback) { control._delayedProcessing = control._delayedProcessing || []; control._delayedProcessing.push(callback); if (control._delayedProcessed) { control.runDelayedProcessing(); } } static supportedForProcessing = true; } MyCustomControlDeclarativeControlContainer.isDeclarativeControlContainer = WinJS.Utilities.markSupportedForProcessing(MyCustomControlDeclarativeControlContainer.isDeclarativeControlContainer); global.MyCustomControlDeclarativeControlContainer = MyCustomControlDeclarativeControlContainer; // Random control used by tests that need a control. Give it whatever surface area you // desire for testing purposes. // class MyCustomControl { element; userRating: number; maxRating: number; _disposed: boolean; constructor(element, options) { this.element = element || document.createElement("div"); this.element.winControl = this; this.element.classList.add("mycustomcontrol"); this.element.classList.add("win-disposable"); this.userRating = 0; this.maxRating = 5; WinJS.UI.setOptions(this, options || {}); this._disposed = false; } dispose() { if (this._disposed) { return; } this._disposed = true; } static supportedForProcessing = true; } global.MyCustomControl = MyCustomControl; var as = WinJS.Binding.as; var Promise = WinJS.Promise; var Template = <typeof WinJS.Binding.PrivateTemplate>WinJS.Binding.Template; function async(test) { return function (complete) { var p = test.call(this); if (p) { p .then(null, function (msg) { try { LiveUnit.Assert.fail('There was an unhandled error in your test: ' + msg); } catch (ex) { // purposefully empty } }) .then(function () { complete(); }); } else { complete(); } }; } function timeout(n) { return function (v) { return WinJS.Promise.timeout(n).then(function () { return v; }); }; } WinJS.Namespace.define("AsyncTemplate", { AsyncControl: WinJS.Class.define(function (element, options, complete) { element.winControl = this; // Note that for teste purposes this guy expects to always get an empty options record LiveUnit.Assert.isNotNull(options); LiveUnit.Assert.areEqual("object", typeof options); LiveUnit.Assert.areEqual(0, Object.keys(options).length); this.completeMe = complete; }) }); // This is not a test fixture export class TemplatesTestBase { "use strict"; testTemplateExists = function () { LiveUnit.Assert.isTrue("Template" in WinJS.Binding); } testObTemplateStyleBindDeepNested = async(function () { var holder = document.createElement("div"); holder.id = "testObTemplateStyleBindDeepNested"; holder.innerHTML = "<div>" + "<div id='testObTemplateStyleBindDeepNested2' data-win-control='WinJS.Binding.Template'><div data-win-bind='child:q testObTemplateStyleBindDeepNested2Child'></div></div>" + "<div id='testObTemplateStyleBindDeepNested2Child' data-win-control='WinJS.Binding.Template'><div data-win-bind='style.backgroundColor: x; textContent: y'></div></div>" + "</div>"; var data = as({ q: as({ x: "blue", y: 2 }) }); return WinJS.UI.processAll(holder).then(function () { global.testObTemplateStyleBindDeepNested2Child = holder.querySelector("#testObTemplateStyleBindDeepNested2Child"); var template = holder.querySelector("#testObTemplateStyleBindDeepNested2").winControl; return template.render(data); }).then(timeout(32)).then(function (d) { LiveUnit.Assert.areEqual("2", d.textContent.trim()); LiveUnit.Assert.areEqual("blue", d.firstChild.firstChild.style.backgroundColor); }); }); testObTemplateStyleBindDeepNestedWithControl = async(function () { var holder = document.createElement("div"); holder.id = "testObTemplateStyleBindDeepNested"; holder.innerHTML = "<div>" + "<div id='testObTemplateStyleBindDeepNested2' data-win-control='WinJS.Binding.Template'><div data-win-bind='child:q testObTemplateStyleBindDeepNested2Child'></div><div data-win-control='MyCustomControl' data-win-control='{ maxRating: 1 }' data-win-bind='winControl.userRating: y'></div></div>" + "<div id='testObTemplateStyleBindDeepNested2Child' data-win-control='WinJS.Binding.Template'><div data-win-bind='style.backgroundColor: x; textContent: y'></div></div>" + "</div>"; var data = as({ q: as({ x: "blue", y: 2 }) }); return WinJS.UI.processAll(holder).then(function () { global.testObTemplateStyleBindDeepNested2Child = holder.querySelector("#testObTemplateStyleBindDeepNested2Child"); var template = holder.querySelector("#testObTemplateStyleBindDeepNested2").winControl; return template.render(data); }).then(timeout(32)).then(function (d) { LiveUnit.Assert.areEqual("2", d.textContent.trim()); LiveUnit.Assert.areEqual("blue", d.firstChild.firstChild.style.backgroundColor); }); }); testObTemplateStyleBind = async(function () { var holder = document.createElement("div"); holder.id = "testObTemplateStyleBind"; holder.innerHTML = "<div id='testObTemplateStyleBind2'><div data-win-bind='style.backgroundColor: x; textContent: y'></div></div>"; var data = as({ x: "blue", y: 2 }); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual("2", d.textContent.trim()); LiveUnit.Assert.areEqual("blue", d.firstChild.firstChild.style.backgroundColor); }); }); testObTemplateStyleBindDeep = async(function () { var holder = document.createElement("div"); holder.id = "testObTemplateStyleBindDeep"; holder.innerHTML = "<div id='testObTemplateStyleBindDeep2'><div data-win-bind='style.backgroundColor: q.x; textContent: q.y'></div></div>"; var data = as({ q: as({ x: "blue", y: 2 }) }); var template = new Template(holder); return this._render(template, data).then(timeout(32)).then(function (d) { LiveUnit.Assert.areEqual("2", d.textContent.trim()); LiveUnit.Assert.areEqual("blue", d.firstChild.firstChild.style.backgroundColor); }); }); testTemplateStyleBind = async(function () { var holder = document.createElement("div"); holder.id = "testTemplateStyleBind"; holder.innerHTML = "<div id='testTemplateStyleBind2'><div data-win-bind='style.backgroundColor: x; textContent: y'></div></div>"; var data = { x: "blue", y: 2 }; var template = new Template(holder); return this._render(template, data).then(function (d) { LiveUnit.Assert.areEqual("2", d.textContent.trim()); LiveUnit.Assert.areEqual("blue", d.firstChild.firstChild.style.backgroundColor); }); }); testTemplateStyleBindDeep = async(function () { var holder = document.createElement("div"); holder.id = "testTemplateStyleBindDeep"; holder.innerHTML = "<div id='testTemplateStyleBindDeep2'><div data-win-bind='style.backgroundColor: q.x; textContent: q.y'></div></div>"; var data = { q: { x: "blue", y: 2 } }; var template = new Template(holder); return this._render(template, data).then(function (d) { LiveUnit.Assert.areEqual("2", d.textContent.trim()); LiveUnit.Assert.areEqual("blue", d.firstChild.firstChild.style.backgroundColor); }); }); testLargeTemplate = async(function () { var template = document.createElement("div"); template.id = "testLargeTemplate"; var contents = []; var data = []; var numbers = []; for (var i = 0; i < 4; i++) { contents.push("<span data-win-bind='textContent:x" + i + "'></span>"); data["x" + i] = i; numbers.push(i); } template.innerHTML = contents.join("<span>,</span>"); var it = new Template(template); return it.render(data).then(function (d) { LiveUnit.Assert.areEqual(numbers.join(","), d.textContent); }); }); testTemplateFromFragment = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testTemplateFromFragment'><span data-win-bind='textContent: x'></span>, <span data-win-bind='textContent:y'></span></div>"; WinJS.UI.Fragments.clearCache(holder); var frag: any = document.createElement("div"); return WinJS.UI.Fragments.renderCopy(holder).then(function (docfrag) { frag.appendChild(docfrag); WinJS.UI.Fragments.clearCache(holder); var data = { x: 1, y: 2 }; // purposefully leave this going through the static path return Template.render(frag, data).then(function (d) { LiveUnit.Assert.areEqual("1, 2", d.textContent); }); }); }); testDeclarativeTemplate = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testDeclarativeTemplate' data-win-control='WinJS.Binding.Template'><div data-win-bind='textContent:x'></div></div>"; return WinJS.UI.process(<Element>holder.firstChild).then(function (control) { var control = (<Element>holder.firstChild).winControl; return control.render({ x: 42 }).then(function (d) { LiveUnit.Assert.areEqual("42", d.textContent); LiveUnit.Assert.isFalse(d.hasAttribute("data-win-control")); }); }); }); testImperativeTemplate = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testImperativeTemplate'><div data-win-bind='textContent:x'></div></div>"; return this._render(new Template(<HTMLElement>holder.firstChild), { x: 42 }).then(function (d) { LiveUnit.Assert.areEqual("42", d.textContent); }); }); testTemplateWithControl = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testImperativeTemplate'>\ <div data-win-control='MyCustomControl' data-win-options='{ maxRating: 10 }' data-win-bind='winControl.userRating: rating'></div></div>"; return this._render(new Template(<HTMLElement>holder.firstChild), { rating: 3 }).then(function (d) { LiveUnit.Assert.isTrue(d.firstElementChild.winControl instanceof global.MyCustomControl); LiveUnit.Assert.areEqual(3, d.firstElementChild.winControl.userRating); LiveUnit.Assert.areEqual(10, d.firstElementChild.winControl.maxRating); }); }); testTemplateWithControlAsyncControl = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testImperativeTemplate'>\ <div><div data-win-control='MyCustomControl' data-win-options='{ maxRating: 10 }' data-win-bind='winControl.userRating: rating'></div></div>\ <div data-win-control='AsyncTemplate.AsyncControl' data-win-options='{}'></div>\ </div>"; var d: any = document.createElement("div"); // Passes a container, purposefully leave this going through render path var templatePromise = Template.render(<any>holder.firstChild, { rating: 3 }, d); var rating = d.children[0].children[0].winControl; LiveUnit.Assert.isTrue(rating instanceof global.MyCustomControl); LiveUnit.Assert.areEqual(0, rating.userRating); LiveUnit.Assert.areEqual(10, rating.maxRating); var async = d.children[1].winControl; LiveUnit.Assert.isTrue(async instanceof global.AsyncTemplate.AsyncControl); // bindings should not run until async controls are done being constructed // async.completeMe(); LiveUnit.Assert.areEqual(3, rating.userRating); return templatePromise; }); testBooleanAttributes = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testObTemplateStyleBind2'>\ <input class='one' type='checkbox' data-win-bind='checked: y; checked: x'>\ <input class='two' type='checkbox' data-win-bind='checked: y'>\ </div>"; var data = as({ x: true, y: false }); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual(true, d.querySelector(".one").checked); LiveUnit.Assert.areEqual(false, d.querySelector(".two").checked); }); }); testInlineStyleBindings = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x'></div>\ </div>"; var data = as({ x: "red" }); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); }); }); testSlowData = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x'></div>\ </div>"; var data = WinJS.Promise.timeout().then(function () { return as({ x: "red" }); }); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); }); }); testOneTimeBindings = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x WinJS.Binding.oneTime'></div>\ <div class='two' data-win-bind='tabIndex: y WinJS.Binding.setAttributeOneTime'></div>\ <div class='three' data-win-bind='mythis: this WinJS.Binding.oneTime'></div>\ </div>"; var data = as({ x: "red", y: 100 }); 5 return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); LiveUnit.Assert.areEqual(100, d.querySelector(".two").tabIndex); LiveUnit.Assert.areEqual(data, d.querySelector(".three").mythis); }); }); testVSTemplate = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div class='item'>\ <img class='item-image' src='#' data-win-bind='src: backgroundImage; alt: title' />\ <div class='item-overlay'>\ <h4 class='item-title' data-win-bind='textContent: title'></h4>\ <h6 class='item-subtitle win-type-ellipsis' data-win-bind='textContent: subtitle'></h6>\ </div>\ </div>"; var data = as({ backgroundImage: "#", title: "some title", subtitle: "some subtitle" }); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual("#", d.querySelector(".item-image").src.substr(-1)[0]); LiveUnit.Assert.areEqual("some title", d.querySelector(".item-title").textContent); LiveUnit.Assert.areEqual("some subtitle", d.querySelector(".item-subtitle").textContent); }); }); testBindingAgainstEmptyObject = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div class='content' data-win-bind='textContent: a.b.d'>some text</div>"; var data = as({ a: null }); return this._render(new Template(holder), data).then(function (d) { var content = d.querySelector(".content").textContent; // Firefox has a bug where undefined gets coerced to empty string if (content !== "undefined" && content !== "") { LiveUnit.Assert.fail("Binding to an empty object should set textContent to undefined."); } }); }); testDeadCodeElimination = async(function () { var holder = document.createElement("div"); holder.innerHTML = '<div data-win-bind="textContent:foo">\ <div>\ <div data-win-control="MyCustomControl" data-win-bind="winControl.userRating: y">some text</div>\ <div class="two" data-win-bind="alt: f"></div>\ </div>\ </div>\ <div class="other">some other content</div>'; var data = as({ x: 1, y: 2, foo: "foo text" }); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual(null, d.querySelector(".mycustomcontrol")); LiveUnit.Assert.areEqual(null, d.querySelector(".two")); }); }); testSelectors = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div class='one' data-win-control='MyCustomControl' data-win-options='{ userRating: 3 }'></div>\ <div class='two' data-win-control='MyCustomControl' data-win-options='{ userRating: select(\".one\").winControl.userRating }'></div>"; var data = as({}); return this._render(new Template(holder), data).then(function (d) { LiveUnit.Assert.areEqual(3, d.querySelector(".one").winControl.userRating); LiveUnit.Assert.areEqual(3, d.querySelector(".two").winControl.userRating); }); }); testErrorInBindingExpression = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div class='one' data-win-control='MyCustomControl' data-win-options='{ userRating: 3 }' data-win-bind='a: b c d e'></div>\ <div class='two' data-win-control='MyCustomControl' data-win-options='{ userRating: select(\".one\").winControl.userRating }'></div>"; var data = as({}); return this._render(new Template(holder), data).then( function () { LiveUnit.Assert.fail("Should not complete successfully"); }, function () { // should get here } ); }); testErrorInOptionsRecord = async(function () { var holder = document.createElement("div"); holder.innerHTML = "<div class='one' data-win-control='MyCustomControl' data-win-options='{ userRating: 3, a b c d }'></div>\ <div class='two' data-win-control='MyCustomControl' data-win-options='{ userRating: select(\".one\").winControl.userRating }'></div>"; var data = as({}); return this._render(new Template(holder), data).then( function () { LiveUnit.Assert.fail("Should not complete successfully"); }, function () { // should get here } ); }); testCustomInitializers = async(function () { var holder = document.createElement("div"); holder.innerHTML = "\ <div class='one' data-win-bind='textContent: text1 MyCustomInitializer1'></div>\ <div class='two' data-win-bind='textContent: text2 MyCustomInitializer2'></div>\ <div class='three' data-win-bind='textContent: text2 MyCustomInitializer2; textContent: text1 MyCustomInitializer1'></div>\ "; var data = as({ text1: "text1", text2: "text2" }); var template = new Template(holder); var that = this; return this._render(template, data).then(function (d) { LiveUnit.Assert.areEqual("text1", d.querySelector(".one").textContent); LiveUnit.Assert.areEqual("text2", d.querySelector(".two").textContent); // The gotcha with .delayable is that it only delays for the renderItem pipe with compiled templates. // if (that._isRenderItem && template._shouldCompile) { LiveUnit.Assert.areEqual("text2", d.querySelector(".three").textContent); } else { LiveUnit.Assert.areEqual("text1", d.querySelector(".three").textContent); } }); }); testExtractFirst = async(function () { var holder = document.createElement("div"); holder.innerHTML = "\ <div class='one' data-win-bind='textContent: text1'></div>\ <div class='two' data-win-bind='textContent: text2'></div>\ "; var data = as({ text1: "text1", text2: "text2" }); var template = new Template(holder, { extractChild: true }); return this._render(template, data).then(function (d) { LiveUnit.Assert.isTrue(WinJS.Utilities._matchesSelector(d, ".one")); LiveUnit.Assert.areEqual("text1", d.textContent); }); }); testDisposingRenderedItemBeforeAsyncDataWasFetched = async(function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div><div data-win-control='MyCustomControl'></div><div class='testclass' data-win-bind='textContent: data'></div></div>"; // Mimic an async data source by return an async item promise var itemPromise = WinJS.Promise.timeout().then(function () { return WinJS.Promise.wrap({ data: "testValue" }); }); var div1 = document.createElement("div"); var div2 = document.createElement("div"); var template = new WinJS.Binding.Template(templateDiv); var item1 = template.render(itemPromise, div1); var item2 = template.render(itemPromise, div2); // No bindings should be processed at this point LiveUnit.Assert.areEqual("", div1.querySelector('.testclass').textContent); LiveUnit.Assert.areEqual("", div2.querySelector('.testclass').textContent); // Dispose the first rendered item before bindings were processed item1.cancel(); return item1.then(() => { LiveUnit.Assert.fail("Should not complete"); }, function () { return item2.then(function (e) { // The first item should have no value and its ratings control is disposed LiveUnit.Assert.isTrue(div1.querySelector(".mycustomcontrol").winControl._disposed); LiveUnit.Assert.areEqual("", div1.querySelector('.testclass').textContent); // The second item should have a value bound to it and an intact rating control LiveUnit.Assert.isFalse(div2.querySelector(".mycustomcontrol").winControl._disposed); LiveUnit.Assert.areEqual("testValue", div2.querySelector('.testclass').textContent); }, LiveUnit.Assert.fail); }); }); testAddClassOneTimeSimple = async(function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testAddClassOneTime'>\ <div class='one' data-win-bind='foo: x WinJS.Binding.addClassOneTime'></div>\ </div>"; var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ defaultInitializer: WinJS.Binding.oneTime, target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); return template.render({ x: "two" }).then(function (d) { LiveUnit.Assert.areEqual("one two", (<HTMLElement>d.querySelector(".one")).className); }); }); testAddClassOneTimeOverriding = async(function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testAddClassOneTime'>\ <div id='meta' class='zero' data-win-bind='foo: one WinJS.Binding.addClassOneTime; className: two; foo: three WinJS.Binding.addClassOneTime'></div>\ </div>"; var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ defaultInitializer: WinJS.Binding.oneTime, target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); return template.render({ one: "one", two: "two", three: "three" }).then(function (d) { LiveUnit.Assert.areEqual("two three", (<HTMLElement>d.querySelector("#meta")).className); }); }); testDoNothingInitializerNoSecurityCheck = async(function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testAddClassOneTime'>\ <div class='one' data-win-bind='foo: x.y.z MyCustomDoNothingInitializer'></div>\ </div>"; var template = new WinJS.Binding.Template(templateDiv); var data: any = { x: function () { }, }; data.x.y = function () { }; data.x.y.z = 12; // should not error with security check return template.render(data).then(function (d) { LiveUnit.Assert.areEqual(undefined, (<any>d.querySelector(".one")).foo); }, function () { LiveUnit.Assert.fail("should not be here"); }); }); testControlWhichIsDeclarativeControlContainer = async(function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div data-win-control='MyCustomControlDeclarativeControlContainer'>\ <div class='one' data-win-control='MyCustomControl'></div>\ <div class='two' data-win-bind='textContent: text1'>default text</div>\ </div>"; var data = as({ text1: "text1", text2: "text2" }); var template = new WinJS.Binding.Template(templateDiv); return this._render(template, data).then(function (d) { var control = d.querySelector(".mycustomcontroldeclarativecontrolcontainer").winControl; LiveUnit.Assert.isNotNull(control); LiveUnit.Assert.areEqual(2, control.delayedProcessorCount); var one = d.querySelector(".one"); var two = d.querySelector(".two"); LiveUnit.Assert.isFalse(one.winControl); LiveUnit.Assert.areEqual("default text", two.textContent); control.runDelayedProcessing(); LiveUnit.Assert.isTrue(one.winControl); LiveUnit.Assert.isTrue(one.winControl instanceof global.MyCustomControl); LiveUnit.Assert.areEqual("text1", two.textContent); }); }); testInvalidBindings = async(function () { // add this, id, and multi attribute var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div>\ <div class='one' data-win-bind='id: text1; this: text2; foo: text3; bar.baz: text4 WinJS.Binding.setAttributeOneTime'></div>\ </div>"; var data = as({ text1: "text1", text2: "text2", text3: "text3", text4: "text4" }); var template = new WinJS.Binding.Template(templateDiv); var temp = WinJS.log; var messages = [] WinJS.log = function (m) { messages.push(m); }; return this._render(template, data).then(function (d) { var one = d.querySelector(".one"); LiveUnit.Assert.isTrue(messages.length >= 3); LiveUnit.Assert.areEqual("text3", one.foo); LiveUnit.Assert.areNotEqual("text1", one.id); LiveUnit.Assert.areEqual(null, one.getAttribute("bar")); }).then( function () { WinJS.log = temp; }, function (e) { WinJS.log = temp; return WinJS.Promise.wrapError(e); } ); }); }; export class Templates_Interpreted extends TemplatesTestBase { _interpretAllSetting; _isRenderItem = false; constructor() { super(); } setUp() { this._interpretAllSetting = Template._interpretAll; Template._interpretAll = true; } tearDown() { Template._interpretAll = this._interpretAllSetting; } _render(template, data) { return template.render(data); } }; // Test fixture to run all the tests using .renderItem instead of .render on the template // export class Templates_Interpreted_renderItem extends TemplatesTestBase { _interpretAllSetting; _isRenderItem = true; constructor() { super(); } setUp() { this._interpretAllSetting = Template._interpretAll; Template._interpretAll = true; } tearDown() { Template._interpretAll = this._interpretAllSetting; } // replace _render method with use of .renderItem instead of .render // _render(template, data) { var item = { key: "key", data: data, ready: WinJS.Promise.timeout().then(function () { return item; }), isImageCached: function () { return false; }, isOnScreen: function () { return true; }, loadImage: function (srcUrl, image) { image.src = srcUrl; }, }; var itemPromise = WinJS.Promise.as(item); var result = template.renderItem(itemPromise); return result.renderComplete.then(function () { return result.element; }); } } // Test fixture to run all the old template tests in compiled mode // export class Templates_Compiled extends Templates_Interpreted { constructor() { super(); } // Make templates run in compiled mode // setUp() { this._interpretAllSetting = Template._interpretAll; Template._interpretAll = false; } tearDown() { Template._interpretAll = this._interpretAllSetting; } } // Test fixture to run all the old templates tests in compiled mode using .renderItem instead of .render on the template // export class Templates_Compiled_renderItem extends Templates_Interpreted_renderItem { constructor() { super(); } // Make templates run in compiled mode // setUp() { this._interpretAllSetting = Template._interpretAll; Template._interpretAll = false; } tearDown() { Template._interpretAll = this._interpretAllSetting; } } // New test fixture targeting compiled templates. // export class TemplateCompilerTests { testDebugBreak = function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div>content</div>"; var templateWithBreakpoint = new Template(templateDiv); templateWithBreakpoint.debugBreakOnRender = true; templateWithBreakpoint._renderImpl = templateWithBreakpoint._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof templateWithBreakpoint._renderImpl); LiveUnit.Assert.areNotEqual(-1, templateWithBreakpoint._renderImpl.toString().indexOf("debugger;")); var templateWithoutBreakpoint = new Template(templateDiv); templateWithoutBreakpoint.debugBreakOnRender = false; templateWithoutBreakpoint._renderImpl = templateWithoutBreakpoint._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof templateWithoutBreakpoint._renderImpl); LiveUnit.Assert.areEqual(-1, templateWithoutBreakpoint._renderImpl.toString().indexOf("debugger;")); var templateWithoutBreakpointWithoutSpecifying = new Template(templateDiv); templateWithoutBreakpointWithoutSpecifying._renderImpl = templateWithoutBreakpointWithoutSpecifying._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof templateWithoutBreakpointWithoutSpecifying._renderImpl); LiveUnit.Assert.areEqual(-1, templateWithoutBreakpointWithoutSpecifying._renderImpl.toString().indexOf("debugger;")); } testDisableOptimizedProcessing = function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div>content</div>"; var template = new Template(templateDiv, { disableOptimizedProcessing: true }); LiveUnit.Assert.isFalse(template._shouldCompile); template.disableOptimizedProcessing = false; LiveUnit.Assert.isTrue(template._shouldCompile); } testStyleOptimizations = async(function () { var userSelect = WinJS.Utilities._browserStyleEquivalents["user-select"]; var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div>\ <div class='target' data-win-bind='style.backgroundColor: color; style." + userSelect.scriptName + ": userSelect; style.background: background; style.purplePeopleEater: something;'></div>\ </div>"; var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Assert that the supported style properties get turned into CSS style named properties // LiveUnit.Assert.areNotEqual(-1, string.indexOf("background-color:")); LiveUnit.Assert.areNotEqual(-1, string.indexOf(userSelect.cssName + ":")); LiveUnit.Assert.areEqual(0, userSelect.cssName.indexOf('-')); LiveUnit.Assert.areNotEqual(-1, string.indexOf("background:")); // Assert that my new property doesn't get turned into a text replacement because it isn't part of the // style object. // LiveUnit.Assert.areEqual(-1, string.indexOf("purplePeopleEater:")); // Assert that cssText doesn't get turned into a text replacement because we don't support that. // LiveUnit.Assert.areEqual(-1, string.indexOf("css-text:")); LiveUnit.Assert.areEqual(-1, string.indexOf("cssText:")); return template.render({ color: "red", userSelect: "none", background: "purple" }).then(function (d) { var target = <HTMLElement>d.querySelector('.target'); LiveUnit.Assert.areEqual("purple", target.style.backgroundColor); LiveUnit.Assert.areEqual("none", target.style[userSelect.scriptName]); }); }); testUnsupportedStyleProperty = function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div>\ <div data-win-bind='style.purplePeopleEater: something; style.cssText: text'></div>\ </div>"; var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Assert that my new property doesn't get turned into a text replacement because it isn't part of the // style object. // LiveUnit.Assert.areEqual(-1, string.indexOf("purplePeopleEater:")); // Assert that cssText doesn't get turned into a text replacement because we don't support that. // LiveUnit.Assert.areEqual(-1, string.indexOf("css-text:")); LiveUnit.Assert.areEqual(-1, string.indexOf("cssText:")); }; testBindings = async(function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x'></div>\ <div class='two' data-win-bind='tabIndex: y WinJS.Binding.setAttribute'></div>\ </div>"; var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Because these need to setup reoccurant bindings we should find evidence in the form of // the parsed binding expressions. // LiveUnit.Assert.areNotEqual(-1, string.indexOf('["style","backgroundColor"]')); LiveUnit.Assert.areNotEqual(-1, string.indexOf('["tabIndex"]')); return template.render({ x: "red", y: 100 }).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); LiveUnit.Assert.areEqual(100, d.querySelector(".two").tabIndex); }); }); testOneTimeBindings = function () { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x WinJS.Binding.oneTime'></div>\ <div class='two' data-win-bind='tabIndex: y WinJS.Binding.setAttributeOneTime'></div>\ </div>"; var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Because these are one-time bindings we should find no evidence of the binding // initializers being called... // LiveUnit.Assert.areEqual(-1, string.indexOf('["style","backgroundColor"]')); LiveUnit.Assert.areEqual(-1, string.indexOf('["tabIndex"]')); return template.render({ x: "red", y: 100 }).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); LiveUnit.Assert.areEqual(100, d.querySelector(".two").tabIndex); }); }; testDefaultInitializerOneTime = function (complete) { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x'></div>\ </div>"; var template = new Template(templateDiv, { bindingInitializer: WinJS.Binding.oneTime }); template._renderImpl = template._compileTemplate({ target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Because these are one-time bindings we should find no evidence of the binding // initializers being called... // LiveUnit.Assert.areEqual(-1, string.indexOf('["style","backgroundColor"]')); var data = WinJS.Binding.as({ x: "red", y: 100 }); return template.render(data).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); data.x = "green"; return WinJS.Promise.timeout().then(function () { return d; }); }).then(function (d) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); complete(); }); }; // In order to support blend we need to support changing the template and recompiling // testResetOnFragmentTreeChange = function (complete) { var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x'></div>\ </div>"; var metaOne: any = templateDiv.querySelector(".one"); var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ defaultInitializer: WinJS.Binding.oneTime, resetOnFragmentChange: true, target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Because these are one-time bindings we should find no evidence of the binding // initializers being called... // LiveUnit.Assert.areEqual(-1, string.indexOf('["style","backgroundColor"]')); template.render({ x: "red", y: 100 }).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); }).then(function () { metaOne.innerHTML = "<div class='two' data-win-bind='textContent: y'></div>"; return WinJS.Promise.timeout(); }).then(function () { // @TODO, once mutation observers for DOM elements come online we can remove this whole block template._reset(); }).then(function () { LiveUnit.Assert.areEqual(Template.prototype._renderImpl, template._renderImpl); // recompile template._renderImpl = template._compileTemplate({ defaultInitializer: WinJS.Binding.oneTime, resetOnFragmentChange: true, target: "render", }); LiveUnit.Assert.areNotEqual(Template.prototype._renderImpl, template._renderImpl); return template.render({ x: "red", y: 100 }); }).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); LiveUnit.Assert.areEqual("100", d.querySelector(".two").textContent); complete(); }); }; testResetOnFragmentAttributeChange = function (complete) { if (WinJS.Utilities._MutationObserver._isShim) { // The Template Compiler will not automatically regenerate // when the raw DOM is modified on platforms without // MutationObserver support. return complete(); } var templateDiv = document.createElement("div"); templateDiv.innerHTML = "<div id='testObTemplateStyleBind2'>\ <div class='one' data-win-bind='style.backgroundColor: x'></div>\ </div>"; var metaOne = templateDiv.querySelector(".one"); var template = new Template(templateDiv); template._renderImpl = template._compileTemplate({ defaultInitializer: WinJS.Binding.oneTime, resetOnFragmentChange: true, target: "render", }); LiveUnit.Assert.areEqual("function", typeof template._renderImpl); var string = template._renderImpl.toString(); // Because these are one-time bindings we should find no evidence of the binding // initializers being called... // LiveUnit.Assert.areEqual(-1, string.indexOf('["style","backgroundColor"]')); template.render({ x: "red", y: 100 }).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); }).then(function () { // go change an attribute value and verify that the template reset itself. WinJS.Utilities.data(template.element).docFragment.querySelector(".one").setAttribute("aria-label", "something"); return WinJS.Promise.timeout(); }).then(function () { LiveUnit.Assert.areEqual(Template.prototype._renderImpl, template._renderImpl); // recompile template._renderImpl = template._compileTemplate({ defaultInitializer: WinJS.Binding.oneTime, resetOnFragmentChange: true, target: "render", }); LiveUnit.Assert.areNotEqual(Template.prototype._renderImpl, template._renderImpl); return template.render({ x: "red", y: 100 }); }).then(function (d: any) { LiveUnit.Assert.areEqual("red", d.querySelector(".one").style.backgroundColor); LiveUnit.Assert.areEqual("something", d.querySelector(".one").getAttribute("aria-label")); complete(); }); }; testCSETreeWithNormalAccessGenerator = function () { var compiler = { _instanceVariables: {}, _instanceVariablesCount: {}, defineInstance: WinJS.Binding._TemplateCompiler.prototype.defineInstance, formatCode: WinJS.Binding._TemplateCompiler.prototype.formatCode, nullableIdentifierAccessTemporary: "t0", }; var cse = new WinJS.Binding._TemplateCompiler._TreeCSE(compiler, "root", "data", WinJS.Binding._TemplateCompiler.prototype.generateNormalAccess.bind(compiler)); cse.createPathExpression(["data", "moreData", "detail1"], "data_moreData_detail1"); cse.createPathExpression(["data", "moreData", "detail2"], "data_moreData_detail2"); cse.createPathExpression(["data", "moreData", "detail2", "evenMoreDetail"], "data_moreData_detail2_evenMoreDetail"); cse.lower(); var definitions = cse.definitions(); // MoreData should have been aliased LiveUnit.Assert.areEqual(definitions[0], "d3_data_moreData = (t0 = root) && (t0 = (t0.data)) && (t0.moreData)"); // Detail1 and Detail2 should reference off the aliased moreData LiveUnit.Assert.areEqual(definitions[1], "d0_data_moreData_detail1 = (t0 = d3_data_moreData) && (t0.detail1)"); LiveUnit.Assert.areEqual(definitions[2], "d1_data_moreData_detail2 = (t0 = d3_data_moreData) && (t0.detail2)"); // EvenMoreDetail should reference off detail2 LiveUnit.Assert.areEqual(definitions[3], "d2_data_moreData_detail2_evenMoreDetail = (t0 = d1_data_moreData_detail2) && (t0.evenMoreDetail)"); }; testCSETreeWithNormalElementCaptureAccessGenerator = function () { var compiler = { _instanceVariables: {}, _instanceVariablesCount: {}, defineInstance: WinJS.Binding._TemplateCompiler.prototype.defineInstance, formatCodeN: WinJS.Binding._TemplateCompiler.prototype.formatCodeN, nullableIdentifierAccessTemporary: "t0", }; var cse = new WinJS.Binding._TemplateCompiler._TreeCSE(compiler, "container", "capture", WinJS.Binding._TemplateCompiler.prototype.generateElementCaptureAccess.bind(compiler)); cse.createPathExpression(["0", "0"], "one_two"); cse.createPathExpression(["0", "1"], "one_two"); cse.createPathExpression(["0", "1", "0"], "one_two_three"); cse.lower(); var definitions = cse.definitions(); // 0_0 should have been aliased LiveUnit.Assert.areEqual(definitions[0], "c3_0 = container.children[startIndex]"); // Detail1 and Detail2 should reference off the aliased moreData LiveUnit.Assert.areEqual(definitions[1], "c0_one_two = c3_0.children[0]"); LiveUnit.Assert.areEqual(definitions[2], "c1_one_two = c3_0.children[1]"); // EvenMoreDetail should reference off detail2 LiveUnit.Assert.areEqual(definitions[3], "c2_one_two_three = c1_one_two.children[0]"); }; }; } LiveUnit.registerTestClass("CorsicaTests.Templates_Interpreted"); LiveUnit.registerTestClass("CorsicaTests.Templates_Interpreted_renderItem"); LiveUnit.registerTestClass("CorsicaTests.Templates_Compiled"); LiveUnit.registerTestClass("CorsicaTests.Templates_Compiled_renderItem"); LiveUnit.registerTestClass("CorsicaTests.TemplateCompilerTests");
the_stack
import "@lit-labs/virtualizer"; import { css, CSSResultGroup, html, LitElement, PropertyValues, TemplateResult, } from "lit"; import type { HassEntity } from "home-assistant-js-websocket"; import { customElement, eventOptions, property } from "lit/decorators"; import { classMap } from "lit/directives/class-map"; import { formatDate } from "../../common/datetime/format_date"; import { formatTimeWithSeconds } from "../../common/datetime/format_time"; import { restoreScroll } from "../../common/decorators/restore-scroll"; import { fireEvent } from "../../common/dom/fire_event"; import { computeDomain } from "../../common/entity/compute_domain"; import { isComponentLoaded } from "../../common/config/is_component_loaded"; import "../../components/entity/state-badge"; import "../../components/ha-circular-progress"; import "../../components/ha-relative-time"; import { createHistoricState, localizeTriggerSource, localizeStateMessage, LogbookEntry, } from "../../data/logbook"; import { TraceContexts } from "../../data/trace"; import { haStyle, haStyleScrollbar, buttonLinkStyle, } from "../../resources/styles"; import { HomeAssistant } from "../../types"; import { brandsUrl } from "../../util/brands-url"; const triggerDomains = ["script", "automation"]; const hasContext = (item: LogbookEntry) => item.context_event_type || item.context_state || item.context_message; const stripEntityId = (message: string, entityId?: string) => entityId ? message.replace(entityId, " ") : message; @customElement("ha-logbook-renderer") class HaLogbookRenderer extends LitElement { @property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public userIdToName = {}; @property({ attribute: false }) public traceContexts: TraceContexts = {}; @property({ attribute: false }) public entries: LogbookEntry[] = []; @property({ type: Boolean, attribute: "narrow" }) public narrow = false; @property({ type: Boolean, attribute: "virtualize", reflect: true }) public virtualize = false; @property({ type: Boolean, attribute: "no-icon" }) public noIcon = false; @property({ type: Boolean, attribute: "no-name" }) public noName = false; @property({ type: Boolean, attribute: "relative-time" }) public relativeTime = false; // @ts-ignore @restoreScroll(".container") private _savedScrollPos?: number; protected shouldUpdate(changedProps: PropertyValues<this>) { const oldHass = changedProps.get("hass") as HomeAssistant | undefined; const languageChanged = oldHass === undefined || oldHass.locale !== this.hass.locale; return ( changedProps.has("entries") || changedProps.has("traceContexts") || languageChanged ); } protected render(): TemplateResult { if (!this.entries?.length) { return html` <div class="container no-entries"> ${this.hass.localize("ui.components.logbook.entries_not_found")} </div> `; } return html` <div class="container ha-scrollbar ${classMap({ narrow: this.narrow, "no-name": this.noName, "no-icon": this.noIcon, })}" @scroll=${this._saveScrollPos} > ${this.virtualize ? html`<lit-virtualizer scroller class="ha-scrollbar" .items=${this.entries} .renderItem=${this._renderLogbookItem} > </lit-virtualizer>` : this.entries.map((item, index) => this._renderLogbookItem(item, index) )} </div> `; } private _renderLogbookItem = ( item: LogbookEntry, index: number ): TemplateResult => { if (!item || index === undefined) { return html``; } const previous = this.entries[index - 1]; const seenEntityIds: string[] = []; const currentStateObj = item.entity_id ? this.hass.states[item.entity_id] : undefined; const historicStateObj = currentStateObj ? createHistoricState(currentStateObj, item.state!) : undefined; const domain = item.entity_id ? computeDomain(item.entity_id) : // Domain is there if there is no entity ID. item.domain!; const overrideImage = !historicStateObj && !item.icon && !item.state && domain && isComponentLoaded(this.hass, domain) ? brandsUrl({ domain: domain!, type: "icon", useFallback: true, darkOptimized: this.hass.themes?.darkMode, }) : undefined; return html` <div class="entry-container"> ${index === 0 || (item?.when && previous?.when && new Date(item.when * 1000).toDateString() !== new Date(previous.when * 1000).toDateString()) ? html` <h4 class="date"> ${formatDate(new Date(item.when * 1000), this.hass.locale)} </h4> ` : html``} <div class="entry ${classMap({ "no-entity": !item.entity_id })}"> <div class="icon-message"> ${!this.noIcon ? html` <state-badge .hass=${this.hass} .overrideIcon=${item.icon} .overrideImage=${overrideImage} .stateObj=${item.icon ? undefined : historicStateObj} .stateColor=${false} ></state-badge> ` : ""} <div class="message-relative_time"> <div class="message"> ${!this.noName // Used for more-info panel (single entity case) ? this._renderEntity(item.entity_id, item.name) : ""} ${this._renderMessage( item, seenEntityIds, domain, historicStateObj )} ${this._renderContextMessage(item, seenEntityIds)} </div> <div class="secondary"> <span >${formatTimeWithSeconds( new Date(item.when * 1000), this.hass.locale )}</span > - <ha-relative-time .hass=${this.hass} .datetime=${item.when * 1000} capitalize ></ha-relative-time> ${item.context_user_id ? html`${this._renderUser(item)}` : ""} ${triggerDomains.includes(item.domain!) && item.context_id! in this.traceContexts ? html` - <a href=${`/config/${ this.traceContexts[item.context_id!].domain }/trace/${ this.traceContexts[item.context_id!].domain === "script" ? `script.${ this.traceContexts[item.context_id!].item_id }` : this.traceContexts[item.context_id!].item_id }?run_id=${ this.traceContexts[item.context_id!].run_id }`} @click=${this._close} >${this.hass.localize( "ui.components.logbook.show_trace" )}</a > ` : ""} </div> </div> </div> </div> </div> `; }; @eventOptions({ passive: true }) private _saveScrollPos(e: Event) { this._savedScrollPos = (e.target as HTMLDivElement).scrollTop; } private _renderMessage( item: LogbookEntry, seenEntityIds: string[], domain?: string, historicStateObj?: HassEntity ) { if (item.entity_id) { if (item.state) { return historicStateObj ? localizeStateMessage( this.hass, this.hass.localize, item.state, historicStateObj, domain! ) : item.state; } } const itemHasContext = hasContext(item); let message = item.message; if (triggerDomains.includes(domain!) && item.source) { if (itemHasContext) { // These domains include the trigger source in the message // but if we have the context we want to display that instead // as otherwise we display duplicate triggers return ""; } message = localizeTriggerSource(this.hass.localize, item.source); } return message ? this._formatMessageWithPossibleEntity( itemHasContext ? stripEntityId(message, item.context_entity_id) : message, seenEntityIds, undefined ) : ""; } private _renderUser(item: LogbookEntry) { const item_username = item.context_user_id && this.userIdToName[item.context_user_id]; if (item_username) { return `- ${item_username}`; } return ""; } private _renderUnseenContextSourceEntity( item: LogbookEntry, seenEntityIds: string[] ) { if ( !item.context_entity_id || seenEntityIds.includes(item.context_entity_id!) ) { return ""; } // We don't know what caused this entity // to be included since its an integration // described event. return html` (${this._renderEntity( item.context_entity_id, item.context_entity_id_name )})`; } private _renderContextMessage(item: LogbookEntry, seenEntityIds: string[]) { // State change if (item.context_state) { const historicStateObj = item.context_entity_id && item.context_entity_id in this.hass.states ? createHistoricState( this.hass.states[item.context_entity_id], item.context_state ) : undefined; return html`${this.hass.localize( "ui.components.logbook.triggered_by_state_of" )} ${this._renderEntity(item.context_entity_id, item.context_entity_id_name)} ${historicStateObj ? localizeStateMessage( this.hass, this.hass.localize, item.context_state, historicStateObj, computeDomain(item.context_entity_id!) ) : item.context_state}`; } // Service call if (item.context_event_type === "call_service") { return html`${this.hass.localize( "ui.components.logbook.triggered_by_service" )} ${item.context_domain}.${item.context_service}`; } if ( !item.context_message || seenEntityIds.includes(item.context_entity_id!) ) { return ""; } // Automation or script if ( item.context_event_type === "automation_triggered" || item.context_event_type === "script_started" ) { // context_source is available in 2022.6 and later const triggerMsg = item.context_source ? item.context_source : item.context_message.replace("triggered by ", ""); const contextTriggerSource = localizeTriggerSource( this.hass.localize, triggerMsg ); return html`${this.hass.localize( item.context_event_type === "automation_triggered" ? "ui.components.logbook.triggered_by_automation" : "ui.components.logbook.triggered_by_script" )} ${this._renderEntity(item.context_entity_id, item.context_entity_id_name)} ${item.context_message ? this._formatMessageWithPossibleEntity( contextTriggerSource, seenEntityIds ) : ""}`; } // Generic externally described logbook platform // These are not localizable return html` ${this.hass.localize("ui.components.logbook.triggered_by")} ${item.context_name} ${this._formatMessageWithPossibleEntity( item.context_message, seenEntityIds, item.context_entity_id )} ${this._renderUnseenContextSourceEntity(item, seenEntityIds)}`; } private _renderEntity( entityId: string | undefined, entityName: string | undefined ) { const hasState = entityId && entityId in this.hass.states; const displayName = entityName || (hasState ? this.hass.states[entityId].attributes.friendly_name || entityId : entityId); if (!hasState) { return displayName; } return html`<button class="link" @click=${this._entityClicked} .entityId=${entityId} > ${displayName} </button>`; } private _formatMessageWithPossibleEntity( message: string, seenEntities: string[], possibleEntity?: string ) { // // As we are looking at a log(book), we are doing entity_id // "highlighting"/"colorizing". The goal is to make it easy for // the user to access the entity that caused the event. // // If there is an entity_id in the message that is also in the // state machine, we search the message for the entity_id and // replace it with _renderEntity // if (message.indexOf(".") !== -1) { const messageParts = message.split(" "); for (let i = 0, size = messageParts.length; i < size; i++) { if (messageParts[i] in this.hass.states) { const entityId = messageParts[i]; if (seenEntities.includes(entityId)) { return ""; } seenEntities.push(entityId); const messageEnd = messageParts.splice(i); messageEnd.shift(); // remove the entity return html`${messageParts.join(" ")} ${this._renderEntity( entityId, this.hass.states[entityId].attributes.friendly_name )} ${messageEnd.join(" ")}`; } } } // // When we have a message has a specific entity_id attached to // it, and the entity_id is not in the message, we look // for the friendly name of the entity and replace that with // _renderEntity if its there so the user can quickly get to // that entity. // if (possibleEntity && possibleEntity in this.hass.states) { const possibleEntityName = this.hass.states[possibleEntity].attributes.friendly_name; if (possibleEntityName && message.endsWith(possibleEntityName)) { if (seenEntities.includes(possibleEntity)) { return ""; } seenEntities.push(possibleEntity); message = message.substring( 0, message.length - possibleEntityName.length ); return html`${message} ${this._renderEntity(possibleEntity, possibleEntityName)}`; } } return message; } private _entityClicked(ev: Event) { const entityId = (ev.currentTarget as any).entityId; if (!entityId) { return; } ev.preventDefault(); ev.stopPropagation(); fireEvent(this, "hass-more-info", { entityId: entityId, }); } private _close(): void { setTimeout(() => fireEvent(this, "closed"), 500); } static get styles(): CSSResultGroup { return [ haStyle, haStyleScrollbar, buttonLinkStyle, css` :host([virtualize]) { display: block; height: 100%; } .entry-container { width: 100%; } .entry { display: flex; width: 100%; line-height: 2em; padding: 8px 16px; box-sizing: border-box; border-top: 1px solid var(--divider-color); } .entry.no-entity, .no-name .entry { cursor: default; } .entry:hover { background-color: rgba(var(--rgb-primary-text-color), 0.04); } .narrow:not(.no-icon) .time { margin-left: 32px; margin-inline-start: 32px; margin-inline-end: initial; direction: var(--direction); } .message-relative_time { display: flex; flex-direction: column; } .secondary { font-size: 12px; line-height: 1.7; } .secondary a { color: var(--secondary-text-color); } .date { margin: 8px 0; padding: 0 16px; } .icon-message { display: flex; align-items: center; } .no-entries { text-align: center; color: var(--secondary-text-color); } state-badge { margin-right: 16px; margin-inline-start: initial; flex-shrink: 0; color: var(--state-icon-color); margin-inline-end: 16px; direction: var(--direction); } .message { color: var(--primary-text-color); } .no-name .message:first-letter { text-transform: capitalize; } a { color: var(--primary-color); text-decoration: none; } button.link { color: var(--paper-item-icon-color); text-decoration: none; } .container { max-height: var(--logbook-max-height); } .container, lit-virtualizer { height: 100%; } lit-virtualizer { contain: size layout !important; } .narrow .entry { line-height: 1.5; } .narrow .icon-message state-badge { margin-left: 0; margin-inline-start: 0; margin-inline-end: initial; direction: var(--direction); } `, ]; } } declare global { interface HTMLElementTagNameMap { "ha-logbook-renderer": HaLogbookRenderer; } }
the_stack
import React, { useEffect, useState } from 'react'; import produce from 'immer'; import { Form, Input, InputNumber, Button, Checkbox, Descriptions, Slider, Divider, Radio, DatePicker, Select, Switch, Modal, Tooltip, Collapse, } from 'antd'; import { QuestionOutlined, QuestionCircleOutlined, InfoCircleOutlined, } from '@ant-design/icons'; import './index.less'; import _ from 'lodash'; import moment from 'moment'; import fs from 'fs'; import http from '@/library/http'; import util from '@/library/util'; import querystring from 'query-string'; import packageConfig from '@/../../package.json'; import { TypeTaskConfig } from './task_type'; import * as TaskUtils from './utils'; let currentVersion = parseFloat(packageConfig.version); let TaskConfigType = TypeTaskConfig; const electron = require('electron'); const shell = electron.shell; const ipcRenderer = electron.ipcRenderer; const remote = electron.remote; let pathConfig = remote.getGlobal('pathConfig'); const { RangePicker } = DatePicker; const { Option } = Select; type TypeState = { isLogin: boolean; showLoginModel: boolean; showUpgradeInfo: boolean; remoteVersionConfig: { version: number; downloadUrl: string; releaseAt: string; releaseNote: string; }; }; type TypeDatabase = { taskConfig: TypeTaskConfig.Customer; currentUserInfo: { screen_name: string; statuses_count: number; total_page_count: number; followers_count: number; }; }; const Order: { 由旧到新: 'asc'; 由新到旧: 'desc'; } = { 由旧到新: 'asc', 由新到旧: 'desc', }; const ImageQuilty = { 无图: 'none', 默认: 'default', }; const PdfQuilty: { [key: string]: 50 | 60 | 70 | 90 | 100 } = { '50': 50, '60': 60, '70': 70, '90': 90, '100': 100, }; const Translate_Image_Quilty = { [TaskConfigType.CONST_Image_Quilty_默认]: '默认', [TaskConfigType.CONST_Image_Quilty_无图]: '无图', }; const defaultConfigItem = { uid: '', rawInputText: '', comment: '', }; const Const_Volume_Split_By: { [key: string]: string } = { ['不拆分']: 'single', ['年']: 'year', ['月']: 'month', ['微博条数']: 'count', }; let taskConfig: TypeTaskConfig.Customer = { configList: [_.clone(defaultConfigItem)], imageQuilty: TaskConfigType.CONST_Image_Quilty_默认, pdfQuilty: PdfQuilty['60'], maxBlogInBook: 100000, postAtOrderBy: TaskConfigType.CONST_Order_Asc, bookTitle: '', comment: '', volumeSplitBy: TaskConfigType.CONST_Volume_Split_By_不拆分, volumeSplitCount: 10000, fetchStartAtPageNo: 0, fetchEndAtPageNo: 100000, outputStartAtMs: moment('2010-01-01 00:00:00').unix() * 1000, outputEndAtMs: moment().add(1, 'year').unix() * 1000, isSkipFetch: false, isSkipGeneratePdf: false, isRegenerateHtml2PdfImage: false, isOnlyOriginal: false, isOnlyArticle: false, }; if (taskConfig.configList.length === 0) { // 如果没有数据, 就要手工补上一个, 确保数据完整 taskConfig.configList.push(_.clone(defaultConfigItem)); } // 基于配置文件作为初始值 let jsonContent = util.getFileContent(pathConfig.customerTaskConfigUri); try { taskConfig = JSON.parse(jsonContent); } catch (e) {} // 输出时间始终重置为次日 taskConfig.outputEndAtMs = moment().add(1, 'day').unix() * 1000; if (taskConfig.configList.length === 0) { taskConfig.configList.push(_.clone(defaultConfigItem)); } export default function IndexPage(props: { changeTabKey: Function }) { const [form] = Form.useForm(); const [$$status, set$$Status] = useState<TypeState>( produce( { isLogin: false, showLoginModel: false, showUpgradeInfo: false, remoteVersionConfig: { version: 1.0, downloadUrl: '', releaseAt: '', releaseNote: '', }, }, (e) => e, ), ); const [$$database, set$$Database] = useState<TypeDatabase>( produce( { taskConfig: taskConfig, currentUserInfo: { screen_name: '', statuses_count: 0, total_page_count: 0, followers_count: 0, }, }, (e) => e, ), ); // 每次database更新后, 重写 taskConfig 配置 useEffect(() => { TaskUtils.saveConfig($$database.taskConfig); }, [$$database]); // 初始化时检查是否已登录 useEffect(() => { let a = async () => { await asyncCheckIsLogin(); // 同步用户信息 await asyncSyncUserInfo(false); }; a(); }, []); async function asyncCheckIsLogin() { let isLogin = await TaskUtils.asyncCheckIsLogin(); if (isLogin !== true) { set$$Status( produce($$status, (raw) => { raw.isLogin = false; raw.showLoginModel = true; }), ); } else { set$$Status( produce($$status, (raw) => { raw.isLogin = true; raw.showLoginModel = false; }), ); } return isLogin; } async function asyncSyncUserInfo(updatePageRange = false) { // 先检查是否登录 let isLogin = await asyncCheckIsLogin(); if (isLogin !== true) { return false; } // 获取uid // let uid = $$database.taskConfig.configList[0].uid; let uid = await TaskUtils.asyncGetUid( $$database.taskConfig.configList[0].rawInputText, ); console.log('uid =>', uid); if (uid === '') { return; } // 然后更新用户信息 let userInfo = await TaskUtils.asyncGetUserInfo(uid); if (userInfo.screen_name === '') { // 说明请求失败 return; } set$$Database( produce($$database, (raw) => { raw.taskConfig.configList[0].uid = uid; raw.currentUserInfo = userInfo; if (updatePageRange) { // 当启动任务时, 不需要更新页面列表 raw.taskConfig.fetchStartAtPageNo = 0; raw.taskConfig.fetchEndAtPageNo = userInfo?.total_page_count || 1000; } form.setFieldsValue({ fetchEndAtPageNo: raw.taskConfig.fetchEndAtPageNo, fetchStartAtPageNo: 0, fetchPageNoRange: [0, raw.taskConfig.fetchEndAtPageNo], }); }), ); return true; } let initValue = { ...$$database.taskConfig, rawInputText: $$database.taskConfig.configList[0].rawInputText, fetchPageNoRange: [ $$database.taskConfig.fetchStartAtPageNo, $$database.taskConfig.fetchEndAtPageNo, ], outputTimeRange: [ moment.unix($$database.taskConfig.outputStartAtMs / 1000), moment.unix($$database.taskConfig.outputEndAtMs / 1000), ], }; console.log('initValue =>', initValue); // 总需要生成的微博数量 let needGenerateWeiboCount = $$database?.currentUserInfo?.statuses_count || 0; // 总需要备份的微博页数 let needBackupWeiboPageCount = $$database?.currentUserInfo?.statuses_count || 0; needBackupWeiboPageCount = $$database?.taskConfig.fetchEndAtPageNo - $$database?.taskConfig.fetchStartAtPageNo; if ($$database.taskConfig.isSkipFetch) { needBackupWeiboPageCount = 0; } if ($$database.taskConfig.isSkipGeneratePdf) { needGenerateWeiboCount = 0; } console.log('needBackupWeiboPageCount => ', needBackupWeiboPageCount); // 总需要等待的时长(秒) let needWaitSecond = needBackupWeiboPageCount * 30 + needGenerateWeiboCount * 2; let 备份微博耗时_分钟 = Math.floor((needBackupWeiboPageCount * 30) / 60); let 导出微博耗时_分钟 = Math.floor((needGenerateWeiboCount * 2) / 60); let needWaitMinute = Math.floor(needWaitSecond / 60); let needWaitHour = Math.round((needWaitSecond / 60 / 60) * 100) / 100; return ( <div className="customer-task"> <Modal title="发现新版本" visible={$$status.showUpgradeInfo} onOk={() => { set$$Status( produce($$status, (raw) => { raw.showUpgradeInfo = false; }), ); TaskUtils.jumpToUpgrade($$status.remoteVersionConfig.downloadUrl); }} okText="更新" onCancel={() => { set$$Status( produce($$status, (raw) => { raw.showUpgradeInfo = false; }), ); }} > <p>最新版本:{$$status.remoteVersionConfig.version}</p> <p>更新内容:{$$status.remoteVersionConfig.releaseNote}</p> <p>更新时间:{$$status.remoteVersionConfig.releaseAt}</p> </Modal> <Modal title="未登录" visible={$$status.showLoginModel} onOk={() => { set$$Status( produce($$status, (raw) => { raw.showLoginModel = false; }), ); props.changeTabKey('login'); }} onCancel={() => { set$$Status( produce($$status, (raw) => { raw.showLoginModel = false; }), ); }} okText="去登录" > <p>检查到尚未登录, 请先登录微博账号</p> </Modal> <Form labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} name="basic" form={form} onValuesChange={(changedValues, values) => { set$$Database( produce($$database, (raw: TypeDatabase) => { let updateKey = Object.keys(changedValues)[0]; switch (updateKey) { case 'rawInputText': let rawInput = changedValues['rawInputText']; // 先记录数据, 待点击同步按钮后再更新uid信息 raw.taskConfig.configList[0].rawInputText = rawInput; raw.taskConfig.configList[0].uid = ''; raw.taskConfig.configList[0].comment = ''; break; case 'fetchPageNoRange': raw.taskConfig['fetchStartAtPageNo'] = changedValues[updateKey][0]; raw.taskConfig['fetchEndAtPageNo'] = changedValues[updateKey][1]; break; case 'outputTimeRange': raw.taskConfig['outputStartAtMs'] = changedValues[updateKey][0].unix() * 1000; raw.taskConfig['outputEndAtMs'] = changedValues[updateKey][1].unix() * 1000; break; case 'volumeSplitBy': raw.taskConfig['volumeSplitBy'] = changedValues['volumeSplitBy']; break; default: raw.taskConfig[updateKey] = changedValues[updateKey]; } }), ); }} initialValues={initValue} > <Form.Item label={ <span> 个人主页&nbsp; <Tooltip title="在浏览器中进入用户首页, 将链接粘贴至此处. 主页地址类似于:https://weibo.com/u/5659598386 或 https://weibo.com/n/八大山债人 或 https://m.weibo.cn/u/5659598386 或 https://m.weibo.cn/profile/2291429207"> <QuestionCircleOutlined /> </Tooltip> </span> } > <div className="flex-container"> <Form.Item name="rawInputText" className="flex-container-item-w100"> <Input placeholder="请输入用户个人主页url.示例:https://weibo.com/u/5390490281" /> </Form.Item> <Button onClick={() => { asyncSyncUserInfo(true); }} > 同步用户信息 </Button> </div> </Form.Item> <Form.Item label="用户信息"> {$$database.currentUserInfo.screen_name === '' ? ( '数据待同步' ) : ( <Descriptions bordered column={1}> <Descriptions.Item label="用户名"> {$$database.currentUserInfo.screen_name} </Descriptions.Item> <Descriptions.Item label="微博总数"> {$$database.currentUserInfo.statuses_count} </Descriptions.Item> <Descriptions.Item label="微博总页面数"> {$$database.currentUserInfo.total_page_count} </Descriptions.Item> <Descriptions.Item label="待抓取页面范围[从0开始计数]"> 从{$$database.taskConfig.fetchStartAtPageNo}~ {$$database.taskConfig.fetchEndAtPageNo}页, 共 {$$database.taskConfig.fetchEndAtPageNo - $$database.taskConfig.fetchStartAtPageNo + 1} 页 </Descriptions.Item> <Descriptions.Item label={ <span> 预计耗时&nbsp; <Tooltip title="计算公式:总耗时=(待抓取微博总数/10 * 30 + 微博总数 * 2)秒. 每10条微博一页, 抓取一页微博数据需要间隔30s. 抓取完成, 生成pdf时, 每条微博需要用2s将其渲染为图片. 故有此公式"> <QuestionCircleOutlined /> </Tooltip> </span> } > 预计累计耗时{needWaitMinute}分钟 / {needWaitHour}小时 </Descriptions.Item> <Descriptions.Item label={<span>- 抓取耗时&nbsp;</span>}> {$$database.taskConfig.isSkipFetch ? `已勾选跳过抓取流程选项, 不需要执行抓取, 耗时为0` : `预计共需备份${needBackupWeiboPageCount}张页面, 耗时${备份微博耗时_分钟}分钟`} </Descriptions.Item> <Descriptions.Item label={<span>- 输出pdf耗时&nbsp;</span>}> {$$database.taskConfig.isSkipGeneratePdf ? '已勾选跳过pdf输出选项, 不需要渲染pdf, 耗时为0' : `预计共需渲染${needGenerateWeiboCount}条微博, 耗时${导出微博耗时_分钟}分钟`} </Descriptions.Item> <Descriptions.Item label="粉丝数"> {$$database.currentUserInfo.followers_count} </Descriptions.Item> </Descriptions> )} </Form.Item> <Divider>备份配置</Divider> <Form.Item label={ <span> 备份范围&nbsp; <Tooltip title="可通过配置备份页面范围, 实现断点续传/只备份指定范围内的微博"> <QuestionCircleOutlined /> </Tooltip> </span> } > <div className="flex-container"> <span>从第&nbsp;</span> <Form.Item name="fetchStartAtPageNo" noStyle> <InputNumber step={1} min={0} /> </Form.Item> <span>&nbsp;页备份到第&nbsp;</span> <Form.Item name="fetchEndAtPageNo" noStyle> <InputNumber step={1} max={$$database.currentUserInfo.total_page_count || 0} /> </Form.Item> <span>&nbsp;页&nbsp;</span> </div> </Form.Item> <Collapse> <Collapse.Panel header="[高级选项]输出规则" key="output-config"> <Form.Item label={ <span> 只导出原创微博&nbsp; <Tooltip title="只导出原创微博, 跳过转发的微博"> <QuestionCircleOutlined /> </Tooltip> </span> } name="isOnlyOriginal" valuePropName="checked" > <Switch></Switch> </Form.Item> <Form.Item label={ <span> 只导出微博文章&nbsp; <Tooltip title="只导出原创的微博文章"> <QuestionCircleOutlined /> </Tooltip> </span> } name="isOnlyArticle" valuePropName="checked" > <Switch></Switch> </Form.Item> <Form.Item label="微博排序" name="postAtOrderBy"> <Radio.Group buttonStyle="solid"> <Radio.Button value={Order.由旧到新}>由旧到新</Radio.Button> <Radio.Button value={Order.由新到旧}>由新到旧</Radio.Button> </Radio.Group> </Form.Item> <Form.Item label="图片配置" name="imageQuilty"> <Radio.Group buttonStyle="solid"> <Radio.Button value={ImageQuilty.无图}>无图</Radio.Button> <Radio.Button value={ImageQuilty.默认}>有图</Radio.Button> </Radio.Group> </Form.Item> <Form.Item label="时间范围"> <div className="flex-container"> <span>只输出从</span> &nbsp; <Form.Item name="outputTimeRange" noStyle> <RangePicker picker="date" /> </Form.Item> &nbsp; <span>间发布的微博</span> </div> </Form.Item> <Form.Item label="电子书拆分规则"> <div className="flex-container"> <Form.Item name="volumeSplitBy" noStyle> <Select labelInValue={false} style={{ width: 180 }}> <Option value={Const_Volume_Split_By.不拆分}>不拆分</Option> <Option value={Const_Volume_Split_By.年}>按年拆分</Option> <Option value={Const_Volume_Split_By.月}>按月拆分</Option> <Option value={Const_Volume_Split_By.微博条数}> 按微博条数拆分 </Option> </Select> </Form.Item> {$$database.taskConfig.volumeSplitBy === Const_Volume_Split_By.微博条数 ? ( <span>, 每&nbsp;</span> ) : null} {$$database.taskConfig.volumeSplitBy === Const_Volume_Split_By.微博条数 ? ( <Form.Item name="volumeSplitCount" noStyle> <InputNumber // placeholder="每n条微博拆分为一卷" min={1000} step={1000} // 每本电子书最多只能有10000条微博 max={10000} style={{ width: 120 }} ></InputNumber> </Form.Item> ) : null} {$$database.taskConfig.volumeSplitBy === Const_Volume_Split_By.微博条数 ? ( <span>&nbsp;条微博一卷</span> ) : null} </div> </Form.Item> </Collapse.Panel> </Collapse> <Collapse> <Collapse.Panel header="[高级选项]开发调试" key="develop-config"> <Form.Item label={ <span> 跳过抓取&nbsp; <Tooltip title="若之前已抓取, 数据库中已有记录, 可以跳过抓取流程, 直接输出"> <QuestionCircleOutlined /> </Tooltip> </span> } name="isSkipFetch" valuePropName="checked" > <Switch></Switch> </Form.Item> <Form.Item label={ <span> 跳过输出pdf&nbsp; <Tooltip title="pdf文件输出时需要将每一条微博渲染为图片, 速度较慢, 关闭该选项可以加快输出速度, 便于调试"> <QuestionCircleOutlined /> </Tooltip> </span> } name="isSkipGeneratePdf" valuePropName="checked" > <Switch></Switch> </Form.Item> <Form.Item label={ <span> 生成pdf时重新渲染&nbsp; <Tooltip title="生成pdf需要先将每条微博渲染为图片, 时间较慢(1s/条).因此启用了缓存.若微博之前被渲染过, 则会利用已经渲染好的图片, 以加快生成速度. 如果旧渲染图片有误, 可以直接删除缓存中的该张图片. 不建议勾选此项"> <QuestionCircleOutlined /> </Tooltip> </span> } name="isRegenerateHtml2PdfImage" valuePropName="checked" > <Switch></Switch> </Form.Item> <Collapse> <Collapse.Panel header="最终生成配置内容" key="config-content"> <div> <pre>{JSON.stringify($$database.taskConfig, null, 4)}</pre> </div> </Collapse.Panel> </Collapse> </Collapse.Panel> </Collapse> <p>&nbsp;</p> <Form.Item label={' '} colon={false}> <Button onClick={async () => { // 先同步信息(期间会检查登录状态) let isSyncSuccess = await asyncSyncUserInfo(false); if (isSyncSuccess !== true) { return false; } // 保存日志 TaskUtils.saveConfig($$database.taskConfig); // 然后将tab切换到日志栏 props.changeTabKey('log'); // 启动任务进程 TaskUtils.startBackupTask(); }} type="primary" > 开始备份 </Button> &nbsp; <Button onClick={TaskUtils.openOutputDir}>打开电子书所在目录</Button> &nbsp; <Button onClick={async () => { let remoteConfig = await TaskUtils.asyncCheckNeedUpdate(); if (remoteConfig === false) { return; } set$$Status( produce($$status, (raw) => { raw.showUpgradeInfo = true; raw.remoteVersionConfig = remoteConfig; }), ); }} > 检查更新 </Button> </Form.Item> </Form> </div> ); }
the_stack
import { DateTimeUtil } from './date-time.util'; import { DatePart, DatePartInfo } from '../../directives/date-time-editor/date-time-editor.common'; const reduceToDictionary = (parts: DatePartInfo[]) => parts.reduce((obj, x) => { obj[x.type] = x; return obj; }, {}); describe(`DateTimeUtil Unit tests`, () => { describe('Date Time Parsing', () => { it('should correctly parse all date time parts (base)', () => { const result = DateTimeUtil.parseDateTimeFormat('dd/MM/yyyy HH:mm:ss tt'); const expected = [ { start: 0, end: 2, type: DatePart.Date, format: 'dd' }, { start: 2, end: 3, type: DatePart.Literal, format: '/' }, { start: 3, end: 5, type: DatePart.Month, format: 'MM' }, { start: 5, end: 6, type: DatePart.Literal, format: '/' }, { start: 6, end: 10, type: DatePart.Year, format: 'yyyy' }, { start: 10, end: 11, type: DatePart.Literal, format: ' ' }, { start: 11, end: 13, type: DatePart.Hours, format: 'HH' }, { start: 13, end: 14, type: DatePart.Literal, format: ':' }, { start: 14, end: 16, type: DatePart.Minutes, format: 'mm' }, { start: 16, end: 17, type: DatePart.Literal, format: ':' }, { start: 17, end: 19, type: DatePart.Seconds, format: 'ss' }, { start: 19, end: 20, type: DatePart.Literal, format: ' ' }, { start: 20, end: 22, type: DatePart.AmPm, format: 'tt' } ]; expect(JSON.stringify(result)).toEqual(JSON.stringify(expected)); }); it('should correctly parse date parts of with short formats', () => { let result = DateTimeUtil.parseDateTimeFormat('MM/dd/yyyy'); let resDict = reduceToDictionary(result); expect(result.length).toEqual(5); expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 10 })); // M/d/yy should be 00/00/00 result = DateTimeUtil.parseDateTimeFormat('M/d/yy'); resDict = reduceToDictionary(result); expect(result.length).toEqual(5); expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 8 })); // d/M/y should be 00/00/0000 result = DateTimeUtil.parseDateTimeFormat('d/M/y'); resDict = reduceToDictionary(result); expect(result.length).toEqual(5); expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 10 })); // d/M/yyy should be 00/00/0000 result = DateTimeUtil.parseDateTimeFormat('d/M/yyy'); resDict = reduceToDictionary(result); expect(result.length).toEqual(5); expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 10 })); // d/M/yyyy should 00/00/0000 result = DateTimeUtil.parseDateTimeFormat('d/M/yyyy'); resDict = reduceToDictionary(result); expect(result.length).toEqual(5); expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 10 })); // H:m:s should be 00:00:00 result = DateTimeUtil.parseDateTimeFormat('H:m:s'); resDict = reduceToDictionary(result); expect(result.length).toEqual(5); expect(resDict[DatePart.Hours]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Minutes]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Seconds]).toEqual(jasmine.objectContaining({ start: 6, end: 8 })); result = DateTimeUtil.parseDateTimeFormat('dd.MM.yyyy г.'); resDict = reduceToDictionary(result); expect(result.length).toEqual(6); expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 10 })); // TODO // result = DateTimeUtil.parseDateTimeFormat('dd.MM.yyyyг'); // resDict = reduceToDictionary(result); // expect(result.length).toEqual(6); // expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 0, end: 2 })); // expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 3, end: 5 })); // expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 6, end: 10 })); // expect(result[5]?.format).toEqual('г'); // result = DateTimeUtil.parseDateTimeFormat('yyyy/MM/d'); // resDict = reduceToDictionary(result); // expect(result.length).toEqual(5); // expect(resDict[DatePart.Year]).toEqual(jasmine.objectContaining({ start: 0, end: 4 })); // expect(resDict[DatePart.Month]).toEqual(jasmine.objectContaining({ start: 5, end: 7 })); // expect(resDict[DatePart.Date]).toEqual(jasmine.objectContaining({ start: 8, end: 10 })); }); it('should correctly parse boundary dates', () => { const parts = DateTimeUtil.parseDateTimeFormat('MM/dd/yyyy'); let result = DateTimeUtil.parseValueFromMask('08/31/2020', parts); expect(result).toEqual(new Date(2020, 7, 31)); result = DateTimeUtil.parseValueFromMask('09/30/2020', parts); expect(result).toEqual(new Date(2020, 8, 30)); result = DateTimeUtil.parseValueFromMask('10/31/2020', parts); expect(result).toEqual(new Date(2020, 9, 31)); }); it('should correctly parse values in h:m:s tt format', () => { const verifyTime = (val: Date, hours = 0, minutes = 0, seconds = 0, milliseconds = 0) => { expect(val.getHours()).toEqual(hours); expect(val.getMinutes()).toEqual(minutes); expect(val.getSeconds()).toEqual(seconds); expect(val.getMilliseconds()).toEqual(milliseconds); }; const parts = DateTimeUtil.parseDateTimeFormat('h:m:s tt'); let result = DateTimeUtil.parseValueFromMask('11:34:12 AM', parts); verifyTime(result, 11, 34, 12); result = DateTimeUtil.parseValueFromMask('04:12:15 PM', parts); verifyTime(result, 16, 12, 15); result = DateTimeUtil.parseValueFromMask('11:00:00 AM', parts); verifyTime(result, 11, 0, 0); result = DateTimeUtil.parseValueFromMask('10:00:00 PM', parts); verifyTime(result, 22, 0, 0); result = DateTimeUtil.parseValueFromMask('12:00:00 PM', parts); verifyTime(result, 12, 0, 0); result = DateTimeUtil.parseValueFromMask('12:00:00 AM', parts); verifyTime(result, 0, 0, 0); }); }); it('should correctly parse a date value from input', () => { let input = '12/04/2012'; let dateParts = [ { start: 0, end: 2, type: DatePart.Date, format: 'dd' }, { start: 2, end: 3, type: DatePart.Literal, format: '/' }, { start: 3, end: 5, type: DatePart.Month, format: 'MM' }, { start: 5, end: 6, type: DatePart.Literal, format: '/' }, { start: 6, end: 10, type: DatePart.Year, format: 'yyyy' }, { start: 10, end: 11, type: DatePart.Literal, format: ' ' } ]; let expected = new Date(2012, 3, 12); let result = DateTimeUtil.parseValueFromMask(input, dateParts); expect(result.getTime()).toEqual(expected.getTime()); input = '04:12:23 PM'; dateParts = [ { start: 0, end: 2, type: DatePart.Hours, format: 'hh' }, { start: 2, end: 3, type: DatePart.Literal, format: ':' }, { start: 3, end: 5, type: DatePart.Minutes, format: 'mm' }, { start: 5, end: 6, type: DatePart.Literal, format: ':' }, { start: 6, end: 8, type: DatePart.Seconds, format: 'ss' }, { start: 8, end: 9, type: DatePart.Literal, format: ' ' }, { start: 9, end: 11, type: DatePart.AmPm, format: 'tt' } ]; result = DateTimeUtil.parseValueFromMask(input, dateParts); expect(result.getHours()).toEqual(16); expect(result.getMinutes()).toEqual(12); expect(result.getSeconds()).toEqual(23); input = '12/10/2012 14:06:03'; dateParts = [ { start: 0, end: 2, type: DatePart.Date, format: 'dd' }, { start: 2, end: 3, type: DatePart.Literal, format: '/' }, { start: 3, end: 5, type: DatePart.Month, format: 'MM' }, { start: 5, end: 6, type: DatePart.Literal, format: '/' }, { start: 6, end: 10, type: DatePart.Year, format: 'yyyy' }, { start: 10, end: 11, type: DatePart.Literal, format: ' ' }, { start: 11, end: 13, type: DatePart.Hours, format: 'HH' }, { start: 13, end: 14, type: DatePart.Literal, format: ':' }, { start: 14, end: 16, type: DatePart.Minutes, format: 'mm' }, { start: 16, end: 17, type: DatePart.Literal, format: ':' }, { start: 17, end: 19, type: DatePart.Seconds, format: 'ss' } ]; expected = new Date(2012, 9, 12, 14, 6, 3); result = DateTimeUtil.parseValueFromMask(input, dateParts); expect(result.getDate()).toEqual(12); expect(result.getMonth()).toEqual(9); expect(result.getFullYear()).toEqual(2012); expect(result.getHours()).toEqual(14); expect(result.getMinutes()).toEqual(6); expect(result.getSeconds()).toEqual(3); }); it('should properly build input formats based on locale', () => { spyOn(DateTimeUtil, 'getDefaultInputFormat').and.callThrough(); let result = DateTimeUtil.getDefaultInputFormat('en-US'); expect(result).toEqual('MM/dd/yyyy'); result = DateTimeUtil.getDefaultInputFormat('bg-BG'); expect(result).toEqual('dd.MM.yyyy г.'); expect(() => { result = DateTimeUtil.getDefaultInputFormat(null); }).not.toThrow(); expect(result).toEqual('MM/dd/yyyy'); expect(() => { result = DateTimeUtil.getDefaultInputFormat(''); }).not.toThrow(); expect(result).toEqual('MM/dd/yyyy'); expect(() => { result = DateTimeUtil.getDefaultInputFormat(undefined); }).not.toThrow(); expect(result).toEqual('MM/dd/yyyy'); }); it('should correctly distinguish date from time characters', () => { expect(DateTimeUtil.isDateOrTimeChar('d')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar('M')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar('y')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar('H')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar('h')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar('m')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar('s')).toBeTrue(); expect(DateTimeUtil.isDateOrTimeChar(':')).toBeFalse(); expect(DateTimeUtil.isDateOrTimeChar('/')).toBeFalse(); expect(DateTimeUtil.isDateOrTimeChar('.')).toBeFalse(); }); it('should spin date portions correctly', () => { // base let date = new Date(2015, 4, 20); DateTimeUtil.spinDate(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 21).getTime()); DateTimeUtil.spinDate(-1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20).getTime()); // delta !== 1 DateTimeUtil.spinDate(5, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 25).getTime()); DateTimeUtil.spinDate(-6, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 19).getTime()); // without looping over date = new Date(2015, 4, 31); DateTimeUtil.spinDate(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 31).getTime()); DateTimeUtil.spinDate(-50, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 1).getTime()); // with looping over DateTimeUtil.spinDate(31, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 1).getTime()); DateTimeUtil.spinDate(-5, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 27).getTime()); }); it('should spin month portions correctly', () => { // base let date = new Date(2015, 4, 20); DateTimeUtil.spinMonth(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 5, 20).getTime()); DateTimeUtil.spinMonth(-1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20).getTime()); // delta !== 1 DateTimeUtil.spinMonth(5, date, false); expect(date.getTime()).toEqual(new Date(2015, 9, 20).getTime()); DateTimeUtil.spinMonth(-6, date, false); expect(date.getTime()).toEqual(new Date(2015, 3, 20).getTime()); // without looping over date = new Date(2015, 11, 31); DateTimeUtil.spinMonth(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 11, 31).getTime()); DateTimeUtil.spinMonth(-50, date, false); expect(date.getTime()).toEqual(new Date(2015, 0, 31).getTime()); // with looping over date = new Date(2015, 11, 1); DateTimeUtil.spinMonth(2, date, true); expect(date.getTime()).toEqual(new Date(2015, 1, 1).getTime()); date = new Date(2015, 0, 1); DateTimeUtil.spinMonth(-1, date, true); expect(date.getTime()).toEqual(new Date(2015, 11, 1).getTime()); // coerces date portion to be no greater than max date of current month date = new Date(2020, 2, 31); DateTimeUtil.spinMonth(-1, date, false); expect(date.getTime()).toEqual(new Date(2020, 1, 29).getTime()); DateTimeUtil.spinMonth(1, date, false); expect(date.getTime()).toEqual(new Date(2020, 2, 29).getTime()); date = new Date(2020, 4, 31); DateTimeUtil.spinMonth(1, date, false); expect(date.getTime()).toEqual(new Date(2020, 5, 30).getTime()); }); it('should spin year portions correctly', () => { // base let date = new Date(2015, 4, 20); DateTimeUtil.spinYear(1, date); expect(date.getTime()).toEqual(new Date(2016, 4, 20).getTime()); DateTimeUtil.spinYear(-1, date); expect(date.getTime()).toEqual(new Date(2015, 4, 20).getTime()); // delta !== 1 DateTimeUtil.spinYear(5, date); expect(date.getTime()).toEqual(new Date(2020, 4, 20).getTime()); DateTimeUtil.spinYear(-6, date); expect(date.getTime()).toEqual(new Date(2014, 4, 20).getTime()); // coerces February to be 29 days on a leap year and 28 on a non leap year date = new Date(2020, 1, 29); DateTimeUtil.spinYear(1, date); expect(date.getTime()).toEqual(new Date(2021, 1, 28).getTime()); DateTimeUtil.spinYear(-1, date); expect(date.getTime()).toEqual(new Date(2020, 1, 28).getTime()); }); it('should spin hours portion correctly', () => { // base let date = new Date(2015, 4, 20, 6); DateTimeUtil.spinHours(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 7).getTime()); DateTimeUtil.spinHours(-1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6).getTime()); // delta !== 1 DateTimeUtil.spinHours(5, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 11).getTime()); DateTimeUtil.spinHours(-6, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 5).getTime()); // without looping over date = new Date(2015, 4, 20, 23); DateTimeUtil.spinHours(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 23).getTime()); DateTimeUtil.spinHours(-30, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 0).getTime()); // with looping over (date is not affected) DateTimeUtil.spinHours(25, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 1).getTime()); DateTimeUtil.spinHours(-2, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 23).getTime()); }); it('should spin minutes portion correctly', () => { // base let date = new Date(2015, 4, 20, 6, 10); DateTimeUtil.spinMinutes(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 11).getTime()); DateTimeUtil.spinMinutes(-1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 10).getTime()); // delta !== 1 DateTimeUtil.spinMinutes(5, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 15).getTime()); DateTimeUtil.spinMinutes(-6, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 9).getTime()); // without looping over date = new Date(2015, 4, 20, 12, 59); DateTimeUtil.spinMinutes(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 59).getTime()); DateTimeUtil.spinMinutes(-70, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 0).getTime()); // with looping over (hours are not affected) DateTimeUtil.spinMinutes(61, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 1).getTime()); DateTimeUtil.spinMinutes(-5, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 56).getTime()); }); it('should spin seconds portion correctly', () => { // base let date = new Date(2015, 4, 20, 6, 10, 5); DateTimeUtil.spinSeconds(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 10, 6).getTime()); DateTimeUtil.spinSeconds(-1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 10, 5).getTime()); // delta !== 1 DateTimeUtil.spinSeconds(5, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 10, 10).getTime()); DateTimeUtil.spinSeconds(-6, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 6, 10, 4).getTime()); // without looping over date = new Date(2015, 4, 20, 12, 59, 59); DateTimeUtil.spinSeconds(1, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 59, 59).getTime()); DateTimeUtil.spinSeconds(-70, date, false); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 59, 0).getTime()); // with looping over (minutes are not affected) DateTimeUtil.spinSeconds(62, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 59, 2).getTime()); DateTimeUtil.spinSeconds(-5, date, true); expect(date.getTime()).toEqual(new Date(2015, 4, 20, 12, 59, 57).getTime()); }); it('should spin AM/PM portion correctly', () => { const currentDate = new Date(2015, 4, 31, 4, 59, 59); const newDate = new Date(2015, 4, 31, 4, 59, 59); // spin from AM to PM DateTimeUtil.spinAmPm(currentDate, newDate, 'PM'); expect(currentDate.getHours()).toEqual(16); // spin from PM to AM DateTimeUtil.spinAmPm(currentDate, newDate, 'AM'); expect(currentDate.getHours()).toEqual(4); }); it('should compare dates correctly', () => { // base let minValue = new Date(2010, 3, 2); let maxValue = new Date(2010, 3, 7); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 3), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 1), minValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 7), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 6), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 8), maxValue)).toBeTrue(); // time variations minValue = new Date(2010, 3, 2, 11, 10, 10); maxValue = new Date(2010, 3, 2, 15, 15, 15); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 11), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 9), minValue)).toBeTrue(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 11, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 9, 10), minValue)).toBeTrue(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 12, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 10, 10, 10), minValue)).toBeTrue(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 3, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 1, 11, 10, 10), minValue)).toBeTrue(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 4, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 2, 2, 11, 10, 10), minValue)).toBeTrue(); expect(DateTimeUtil.lessThanMinValue(new Date(2011, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2010, 3, 2, 11, 10, 10), minValue)).toBeFalse(); expect(DateTimeUtil.lessThanMinValue(new Date(2009, 3, 2, 11, 10, 10), minValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 16), maxValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 14), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 16, 15), maxValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 14, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 16, 15, 15), maxValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 14, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 3, 15, 15, 15), maxValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 1, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 4, 2, 15, 15, 15), maxValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 2, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2011, 3, 2, 15, 15, 15), maxValue)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2010, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2009, 3, 2, 15, 15, 15), maxValue)).toBeFalse(); // date excluded expect(DateTimeUtil.lessThanMinValue(new Date(2030, 3, 2, 11, 10, 9), minValue, true, false)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2000, 3, 2, 15, 15, 16), minValue, true, false)).toBeTrue(); // time excluded expect(DateTimeUtil.lessThanMinValue(new Date(2009, 3, 2, 11, 10, 10), minValue, false, true)).toBeTrue(); expect(DateTimeUtil.greaterThanMaxValue(new Date(2011, 3, 2, 15, 15, 15), minValue, true, false)).toBeTrue(); }); it('should return ValidationErrors for minValue and maxValue', () => { let minValue = new Date(2010, 3, 2); let maxValue = new Date(2010, 3, 7); expect(DateTimeUtil.validateMinMax(new Date(2010, 3, 4), minValue, maxValue)).toEqual({}); expect(DateTimeUtil.validateMinMax(new Date(2010, 2, 7), minValue, maxValue)).toEqual({ minValue: true }); expect(DateTimeUtil.validateMinMax(new Date(2010, 4, 2), minValue, maxValue)).toEqual({ maxValue: true }); minValue = new Date(2010, 3, 2, 10, 10, 10); maxValue = new Date(2010, 3, 2, 15, 15, 15); expect(DateTimeUtil.validateMinMax(new Date(2010, 3, 2, 10, 10, 10), minValue, maxValue)).toEqual({}); expect(DateTimeUtil.validateMinMax(new Date(2010, 3, 2, 9, 11, 11), minValue, maxValue)).toEqual({ minValue: true }); expect(DateTimeUtil.validateMinMax(new Date(2010, 3, 2, 16, 11, 11), minValue, maxValue)).toEqual({ maxValue: true }); // ignore date portion expect(DateTimeUtil.validateMinMax(new Date(2000, 0, 1, 10, 10, 10), minValue, maxValue, true, false)).toEqual({}); expect(DateTimeUtil.validateMinMax( new Date(2020, 10, 10, 9, 10, 10), minValue, maxValue, true, false)).toEqual({ minValue: true }); expect(DateTimeUtil.validateMinMax( new Date(2000, 0, 1, 16, 0, 0), minValue, maxValue, true, false)).toEqual({ maxValue: true }); // ignore time portion expect(DateTimeUtil.validateMinMax(new Date(2010, 3, 2, 9, 0, 0), minValue, maxValue, false, true)).toEqual({}); expect(DateTimeUtil.validateMinMax( new Date(2009, 3, 2, 11, 11, 11), minValue, maxValue, false, true)).toEqual({ minValue: true }); expect(DateTimeUtil.validateMinMax( new Date(2020, 3, 2, 0, 0, 0), minValue, maxValue, false, true)).toEqual({ maxValue: true }); }); it('should parse dates correctly with parseIsoDate', () => { const updateDate = (dateValue: Date, stringValue: string): Date => { const [datePart] = dateValue.toISOString().split('T'); const newDate = new Date(`${datePart}T${stringValue}`); newDate.setMilliseconds(0); return newDate; }; let date = new Date(); date.setMilliseconds(0); // full iso string expect(DateTimeUtil.parseIsoDate(date.toISOString()).getTime()).toEqual(date.getTime()); // date only expect(DateTimeUtil.parseIsoDate('2012-12-10').getTime()).toEqual(new Date('2012-12-10T00:00:00').getTime()); expect(DateTimeUtil.parseIsoDate('2023-13-15').getTime()).toEqual(new Date('2023-13-15T00:00:00').getTime()); expect(DateTimeUtil.parseIsoDate('1524-01-02').getTime()).toEqual(new Date('1524-01-02T00:00:00').getTime()); expect(DateTimeUtil.parseIsoDate('2012').getTime()).toEqual(new Date('2012-01-01T00:00:00').getTime()); expect(DateTimeUtil.parseIsoDate('2012-02').getTime()).toEqual(new Date('2012-02-01T00:00:00').getTime()); // time only date = DateTimeUtil.parseIsoDate('12:14'); date.setMilliseconds(0); expect(date.getTime()).toEqual(updateDate(new Date(), '12:14').getTime()); date = DateTimeUtil.parseIsoDate('15:18'); date.setMilliseconds(0); expect(date.getTime()).toEqual(updateDate(new Date(), '15:18').getTime()); date = DateTimeUtil.parseIsoDate('06:03'); date.setMilliseconds(0); expect(date.getTime()).toEqual(updateDate(new Date(), '06:03').getTime()); date = DateTimeUtil.parseIsoDate('00:00'); date.setMilliseconds(0); expect(date.getTime()).toEqual(updateDate(new Date(), '00:00').getTime()); // falsy values expect(DateTimeUtil.parseIsoDate('')).toEqual(null); expect(DateTimeUtil.parseIsoDate('false')).toEqual(null); expect(DateTimeUtil.parseIsoDate('true')).toEqual(null); expect(DateTimeUtil.parseIsoDate('NaN')).toEqual(null); expect(DateTimeUtil.parseIsoDate(undefined)).toEqual(null); expect(DateTimeUtil.parseIsoDate(null)).toEqual(null); expect(DateTimeUtil.parseIsoDate(new Date().getTime().toString()).getTime()).toEqual(NaN); }); it('isValidDate should properly determine if a date is valid or not', () => { expect(DateTimeUtil.isValidDate(new Date())).toBeTrue(); expect(DateTimeUtil.isValidDate(new Date(NaN))).toBeFalse(); expect(DateTimeUtil.isValidDate(new Date().getTime())).toBeFalse(); expect(DateTimeUtil.isValidDate('')).toBeFalse(); expect(DateTimeUtil.isValidDate({})).toBeFalse(); expect(DateTimeUtil.isValidDate([])).toBeFalse(); expect(DateTimeUtil.isValidDate(null)).toBeFalse(); expect(DateTimeUtil.isValidDate(undefined)).toBeFalse(); expect(DateTimeUtil.isValidDate(false)).toBeFalse(); expect(DateTimeUtil.isValidDate(true)).toBeFalse(); }); });
the_stack
import { AST_NODE_TYPES, TSESTree, } from '@typescript-eslint/experimental-utils'; import { KnownCallExpression, ModifierName, createRule, getAccessorValue, getNodeName, isExpectCall, isFunction, isIdentifier, isSupportedAccessor, isTestCaseCall, parseExpectCall, } from './utils'; type PromiseChainCallExpression = KnownCallExpression< 'then' | 'catch' | 'finally' >; const isPromiseChainCall = ( node: TSESTree.Node, ): node is PromiseChainCallExpression => { if ( node.type === AST_NODE_TYPES.CallExpression && node.callee.type === AST_NODE_TYPES.MemberExpression && isSupportedAccessor(node.callee.property) ) { // promise methods should have at least 1 argument if (node.arguments.length === 0) { return false; } switch (getAccessorValue(node.callee.property)) { case 'then': return node.arguments.length < 3; case 'catch': case 'finally': return node.arguments.length < 2; } } return false; }; const findTopMostCallExpression = ( node: TSESTree.CallExpression, ): TSESTree.CallExpression => { let topMostCallExpression = node; let { parent } = node; while (parent) { if (parent.type === AST_NODE_TYPES.CallExpression) { topMostCallExpression = parent; parent = parent.parent; continue; } if (parent.type !== AST_NODE_TYPES.MemberExpression) { break; } parent = parent.parent; } return topMostCallExpression; }; const isTestCaseCallWithCallbackArg = ( node: TSESTree.CallExpression, ): boolean => { if (!isTestCaseCall(node)) { return false; } const isJestEach = getNodeName(node).endsWith('.each'); if ( isJestEach && node.callee.type !== AST_NODE_TYPES.TaggedTemplateExpression ) { // isJestEach but not a TaggedTemplateExpression, so this must be // the `jest.each([])()` syntax which this rule doesn't support due // to its complexity (see jest-community/eslint-plugin-jest#710) // so we return true to trigger bailout return true; } if (isJestEach || node.arguments.length >= 2) { const [, callback] = node.arguments; const callbackArgIndex = Number(isJestEach); return ( callback && isFunction(callback) && callback.params.length === 1 + callbackArgIndex ); } return false; }; const isPromiseMethodThatUsesValue = ( node: TSESTree.AwaitExpression | TSESTree.ReturnStatement, identifier: TSESTree.Identifier, ): boolean => { const { name } = identifier; if (node.argument === null) { return false; } if ( node.argument.type === AST_NODE_TYPES.CallExpression && node.argument.arguments.length > 0 ) { const nodeName = getNodeName(node.argument); if (['Promise.all', 'Promise.allSettled'].includes(nodeName as string)) { const [firstArg] = node.argument.arguments; if ( firstArg.type === AST_NODE_TYPES.ArrayExpression && firstArg.elements.some(nod => isIdentifier(nod, name)) ) { return true; } } if ( ['Promise.resolve', 'Promise.reject'].includes(nodeName as string) && node.argument.arguments.length === 1 ) { return isIdentifier(node.argument.arguments[0], name); } } return isIdentifier(node.argument, name); }; /** * Attempts to determine if the runtime value represented by the given `identifier` * is `await`ed within the given array of elements */ const isValueAwaitedInElements = ( name: string, elements: | TSESTree.ArrayExpression['elements'] | TSESTree.CallExpression['arguments'], ): boolean => { for (const element of elements) { if ( element.type === AST_NODE_TYPES.AwaitExpression && isIdentifier(element.argument, name) ) { return true; } if ( element.type === AST_NODE_TYPES.ArrayExpression && isValueAwaitedInElements(name, element.elements) ) { return true; } } return false; }; /** * Attempts to determine if the runtime value represented by the given `identifier` * is `await`ed as an argument along the given call expression */ const isValueAwaitedInArguments = ( name: string, call: TSESTree.CallExpression, ): boolean => { let node: TSESTree.Node = call; while (node) { if (node.type === AST_NODE_TYPES.CallExpression) { if (isValueAwaitedInElements(name, node.arguments)) { return true; } node = node.callee; } if (node.type !== AST_NODE_TYPES.MemberExpression) { break; } node = node.object; } return false; }; const getLeftMostCallExpression = ( call: TSESTree.CallExpression, ): TSESTree.CallExpression => { let leftMostCallExpression: TSESTree.CallExpression = call; let node: TSESTree.Node = call; while (node) { if (node.type === AST_NODE_TYPES.CallExpression) { leftMostCallExpression = node; node = node.callee; } if (node.type !== AST_NODE_TYPES.MemberExpression) { break; } node = node.object; } return leftMostCallExpression; }; /** * Attempts to determine if the runtime value represented by the given `identifier` * is `await`ed or `return`ed within the given `body` of statements */ const isValueAwaitedOrReturned = ( identifier: TSESTree.Identifier, body: TSESTree.Statement[], ): boolean => { const { name } = identifier; for (const node of body) { // skip all nodes that are before this identifier, because they'd probably // be affecting a different runtime value (e.g. due to reassignment) if (node.range[0] <= identifier.range[0]) { continue; } if (node.type === AST_NODE_TYPES.ReturnStatement) { return isPromiseMethodThatUsesValue(node, identifier); } if (node.type === AST_NODE_TYPES.ExpressionStatement) { // it's possible that we're awaiting the value as an argument if (node.expression.type === AST_NODE_TYPES.CallExpression) { if (isValueAwaitedInArguments(name, node.expression)) { return true; } const leftMostCall = getLeftMostCallExpression(node.expression); if ( isExpectCall(leftMostCall) && leftMostCall.arguments.length > 0 && isIdentifier(leftMostCall.arguments[0], name) ) { const { modifier } = parseExpectCall(leftMostCall); if ( modifier?.name === ModifierName.resolves || modifier?.name === ModifierName.rejects ) { return true; } } } if ( node.expression.type === AST_NODE_TYPES.AwaitExpression && isPromiseMethodThatUsesValue(node.expression, identifier) ) { return true; } // (re)assignment changes the runtime value, so if we've not found an // await or return already we act as if we've reached the end of the body if (node.expression.type === AST_NODE_TYPES.AssignmentExpression) { // unless we're assigning to the same identifier, in which case // we might be chaining off the existing promise value if ( isIdentifier(node.expression.left, name) && getNodeName(node.expression.right)?.startsWith(`${name}.`) && isPromiseChainCall(node.expression.right) ) { continue; } break; } } if ( node.type === AST_NODE_TYPES.BlockStatement && isValueAwaitedOrReturned(identifier, node.body) ) { return true; } } return false; }; const findFirstBlockBodyUp = ( node: TSESTree.Node, ): TSESTree.BlockStatement['body'] => { let parent: TSESTree.Node['parent'] = node; while (parent) { if (parent.type === AST_NODE_TYPES.BlockStatement) { return parent.body; } parent = parent.parent; } /* istanbul ignore next */ throw new Error( `Could not find BlockStatement - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`, ); }; const isDirectlyWithinTestCaseCall = (node: TSESTree.Node): boolean => { let parent: TSESTree.Node['parent'] = node; while (parent) { if (isFunction(parent)) { parent = parent.parent; return !!( parent?.type === AST_NODE_TYPES.CallExpression && isTestCaseCall(parent) ); } parent = parent.parent; } return false; }; const isVariableAwaitedOrReturned = ( variable: TSESTree.VariableDeclarator, ): boolean => { const body = findFirstBlockBodyUp(variable); // it's pretty much impossible for us to track destructuring assignments, // so we return true to bailout gracefully if (!isIdentifier(variable.id)) { return true; } return isValueAwaitedOrReturned(variable.id, body); }; export default createRule({ name: __filename, meta: { docs: { category: 'Best Practices', description: 'Ensure promises that have expectations in their chain are valid', recommended: 'error', }, messages: { expectInFloatingPromise: "This promise should either be returned or awaited to ensure the expects in it's chain are called", }, type: 'suggestion', schema: [], }, defaultOptions: [], create(context) { let inTestCaseWithDoneCallback = false; // an array of booleans representing each promise chain we enter, with the // boolean value representing if we think a given chain contains an expect // in it's body. // // since we only care about the inner-most chain, we represent the state in // reverse with the inner-most being the first item, as that makes it // slightly less code to assign to by not needing to know the length const chains: boolean[] = []; return { CallExpression(node: TSESTree.CallExpression) { // there are too many ways that the done argument could be used with // promises that contain expect that would make the promise safe for us if (isTestCaseCallWithCallbackArg(node)) { inTestCaseWithDoneCallback = true; return; } // if this call expression is a promise chain, add it to the stack with // value of "false", as we assume there are no expect calls initially if (isPromiseChainCall(node)) { chains.unshift(false); return; } // if we're within a promise chain, and this call expression looks like // an expect call, mark the deepest chain as having an expect call if (chains.length > 0 && isExpectCall(node)) { chains[0] = true; } }, 'CallExpression:exit'(node: TSESTree.CallExpression) { // there are too many ways that the "done" argument could be used to // make promises containing expects safe in a test for us to be able to // accurately check, so we just bail out completely if it's present if (inTestCaseWithDoneCallback) { if (isTestCaseCall(node)) { inTestCaseWithDoneCallback = false; } return; } if (!isPromiseChainCall(node)) { return; } // since we're exiting this call expression (which is a promise chain) // we remove it from the stack of chains, since we're unwinding const hasExpectCall = chains.shift(); // if the promise chain we're exiting doesn't contain an expect, // then we don't need to check it for anything if (!hasExpectCall) { return; } const { parent } = findTopMostCallExpression(node); // if we don't have a parent (which is technically impossible at runtime) // or our parent is not directly within the test case, we stop checking // because we're most likely in the body of a function being defined // within the test, which we can't track if (!parent || !isDirectlyWithinTestCaseCall(parent)) { return; } switch (parent.type) { case AST_NODE_TYPES.VariableDeclarator: { if (isVariableAwaitedOrReturned(parent)) { return; } break; } case AST_NODE_TYPES.AssignmentExpression: { if ( parent.left.type === AST_NODE_TYPES.Identifier && isValueAwaitedOrReturned( parent.left, findFirstBlockBodyUp(parent), ) ) { return; } break; } case AST_NODE_TYPES.ExpressionStatement: break; case AST_NODE_TYPES.ReturnStatement: case AST_NODE_TYPES.AwaitExpression: default: return; } context.report({ messageId: 'expectInFloatingPromise', node: parent, }); }, }; }, });
the_stack
import { $log } from '@tsed/logger'; import { BigNumber } from 'bignumber.js'; import moment from 'moment'; import { bootstrap, TestTz } from '../bootstrap-sandbox'; import { Contract, bytes, address } from '../../src/type-aliases'; import { InternalOperationResult } from '@taquito/rpc'; import { originateEnglishAuctionTez, MintNftParam, originateNftFaucet, } from '../../src/nft-contracts'; import { MichelsonMap } from '@taquito/taquito'; import { addOperator } from '../../src/fa2-interface'; import { Fa2_token, Tokens, sleep } from '../../src/auction-interface'; import { queryBalancesWithLambdaView, hasTokens, QueryBalances } from '../../test/fa2-balance-inspector'; jest.setTimeout(360000); // 6 minutes describe('test NFT auction', () => { let tezos: TestTz; let nftAuction: Contract; let nftAuctionBob : Contract; let nftAuctionAlice : Contract; let nftAuctionEve : Contract; let nftContract : Contract; let bobAddress : address; let aliceAddress : address; let startTime : Date; let endTime : Date; let tokenId : BigNumber; let empty_metadata_map : MichelsonMap<string, bytes>; let mintToken : MintNftParam; let queryBalances : QueryBalances; beforeAll(async () => { tezos = await bootstrap(); empty_metadata_map = new MichelsonMap(); tokenId = new BigNumber(0); bobAddress = await tezos.bob.signer.publicKeyHash(); aliceAddress = await tezos.alice.signer.publicKeyHash(); mintToken = { token_metadata: { token_id: tokenId, token_info: empty_metadata_map, }, owner: bobAddress, }; queryBalances = queryBalancesWithLambdaView(tezos.lambdaView); }); beforeEach(async() => { $log.info('originating nft auction...'); nftAuction = await originateEnglishAuctionTez(tezos.bob); nftAuctionBob = await tezos.bob.contract.at(nftAuction.address); nftAuctionAlice = await tezos.alice.contract.at(nftAuction.address); nftAuctionEve = await tezos.eve.contract.at(nftAuction.address); $log.info('originating nft faucets...'); nftContract = await originateNftFaucet(tezos.bob); $log.info('minting token'); const opMint = await nftContract.methods.mint([mintToken]).send(); await opMint.confirmation(); $log.info(`Minted tokens. Consumed gas: ${opMint.consumedGas}`); $log.info('adding auction contract as operator'); await addOperator(nftContract.address, tezos.bob, nftAuction.address, tokenId); $log.info('Auction contract added as operator'); const fa2_token : Fa2_token = { token_id : tokenId, amount : new BigNumber(1), }; const tokens : Tokens = { fa2_address : nftContract.address, fa2_batch : [fa2_token], }; startTime = moment.utc().add(7, 'seconds').toDate(); endTime = moment(startTime).add(90, 'seconds').toDate(); const opAuction = await nftAuctionBob.methods.configure( //opening price = 10 tz new BigNumber(10000000), //percent raise =10 new BigNumber(10), //min_raise = 10tz new BigNumber(10000000), //round_time = 1 hr new BigNumber(3600), //extend_time = 0 seconds new BigNumber(0), //assset [tokens], //start_time = now + 7seconds startTime, //end_time = start_time + 90 seconds, endTime, ).send({ amount : 0 }); await opAuction.confirmation(); $log.info(`Auction configured. Consumed gas: ${opAuction.consumedGas}`); await sleep(7000); //7 seconds }); test('NFT is held by the auction contract after configuration', async() => { const [auctionHasNft] = await hasTokens([ { owner: nftAuction.address, token_id: tokenId }, ], queryBalances, nftContract); expect(auctionHasNft).toBe(true); }); test('bid of less than asking price should fail', async() => { $log.info(`Alice bids 9tz expecting it to fail`); const failedOpeningBid = nftAuctionAlice.methods.bid(0).send({ amount : 9 }); //TODO: test contents of error message return expect(failedOpeningBid).rejects.toHaveProperty('errors'); }); test('place bid meeting opening price and then raise it by valid amount by min_raise_percent', async () => { $log.info(`Alice bids 10tz`); const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : 10 }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); $log.info(`Eve bids 11tz, a 10% raise of previous bid but less than a 10tz increase`); const opBid2 = await nftAuctionEve.methods.bid(0).send({ amount : 11 }); await opBid2.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid2.amount} mutez`); }); test('place bid meeting opening price and then raise it by valid amount by min_raise', async () => { $log.info(`Alice bids 200tz`); const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : 200 }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); $log.info(`Eve bids 210tz, a 10tz increase but less than a 10% raise of previous bid `); const opBid2 = await nftAuctionEve.methods.bid(0).send({ amount : 210 }); await opBid2.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid2.amount} mutez`); }); test('bid too small should fail', async () => { $log.info(`Alice bids 20tz`); const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : 20 }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount}`); $log.info(`Eve bids 21tz and we expect it to fail`); const smallBidPromise = nftAuctionEve.methods.bid(0).send({ amount : 21 }); return expect(smallBidPromise).rejects.toHaveProperty('errors' ); }); test('auction without bids that is cancelled should not result in transfer of any tez', async () => { $log.info("Cancelling auction"); const opCancel = await nftAuctionBob.methods.cancel(0).send({ amount : 0, mutez : true }); await opCancel.confirmation(); $log.info("Auction cancelled"); const internalOps = (opCancel.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]); expect(internalOps.length).toEqual(1); expect(internalOps[0].destination).toEqual(nftContract.address); $log.info("No amount in tez is sent as we expect"); }); test('auction with bids that is cancelled should return last bid', async () => { $log.info(`Alice bids 200tz`); const bidMutez = 200000000; const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : bidMutez, mutez : true }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); $log.info("Cancelling auction"); const opCancel = await nftAuctionBob.methods.cancel(0).send({ amount : 0 }); await opCancel.confirmation(); $log.info("Auction cancelled"); const feeOp = (opCancel.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]) [0]; const amountReturned = feeOp.amount; const feeDestination = feeOp.destination; expect(amountReturned).toEqual(bidMutez.toString()); expect(feeDestination).toEqual(aliceAddress); $log.info(`${bidMutez.toString()}mutez returned to seller as expected`); }); test('auction resolved before end time should fail', async () => { $log.info(`Alice bids 200tz`); const bidMutez = 200000000; const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : bidMutez, mutez : true }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); $log.info("Resolving auction"); const opResolve = nftAuctionBob.methods.resolve(0).send({ amount : 0 }); expect(opResolve).rejects.toHaveProperty('message', 'AUCTION_NOT_ENDED'); $log.info('Resolve operation failed as expected when called before end time'); }); test('auction without bids that is resolved after end time should only return asset to seller', async () => { await sleep(90000); //90 seconds $log.info("Resolving auction"); const opResolve = await nftAuctionBob.methods.resolve(0).send({ amount : 0 }); await opResolve.confirmation(); const [sellerHasNft] = await hasTokens([ { owner: bobAddress, token_id: tokenId }, ], queryBalances, nftContract); expect(sellerHasNft).toBe(true); $log.info(`NFT returned as expected`); const internalOps = opResolve.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]; expect(internalOps.length).toEqual(1); expect(internalOps[0].destination).toEqual(nftContract.address); }); test('auction cancelled after end time should fail', async () => { const bidMutez = new BigNumber(200000000); const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : bidMutez.toNumber(), mutez : true }); await opBid.confirmation(); $log.info(`Bid placed`); await sleep(90000); //90 seconds const opCancel = nftAuctionBob.methods.cancel(0).send({ amount : 0, mutez : true }); expect(opCancel).rejects.toHaveProperty('message', 'AUCTION_ENDED'); $log.info("Cancel after end time fails as expected"); }); test('resovled auction should send payment to seller and NFT to winning bidder', async () => { $log.info(`Alice bids 200tz`); const bidMutez = new BigNumber(200000000); const opBid = await nftAuctionAlice.methods.bid(0).send({ amount : bidMutez.toNumber(), mutez : true }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); await sleep(90000); //90 seconds $log.info("Resolving auction"); const opResolve = await nftAuctionBob.methods.resolve(0).send({ amount : 0 }); await opResolve.confirmation(); $log.info("Auction Resolve"); const feeOp = (opResolve.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]) [0]; const amountReturned = feeOp.amount; const feeDestination = feeOp.destination; expect(amountReturned).toEqual(bidMutez.toString()); expect(feeDestination).toEqual(bobAddress); $log.info(`${bidMutez.toString()}tez sent to seller as expected`); const aliceAddress = await tezos.alice.signer.publicKeyHash(); const [aliceHasNft] = await hasTokens([ { owner: aliceAddress, token_id: tokenId }, ], queryBalances, nftContract); expect(aliceHasNft).toBe(true); }); });
the_stack
import { CObject, CPrimitive } from "../constructions"; import { Collab, InitToken } from "../core"; import { CList, CListEventsRecord } from "./list"; export declare abstract class AbstractCList<T, InsertArgs extends unknown[]> extends Collab implements CList<T, InsertArgs> { abstract insert(index: number, ...args: InsertArgs): T | undefined; abstract delete(startIndex: number, count?: number): void; abstract get(index: number): T; abstract values(): IterableIterator<T>; abstract readonly length: number; /** * Calls delete on every value in the list, in * reverse order. * * Override this method if you want to optimize this * behavior. */ clear(): void; readonly size: number; [Symbol.iterator](): IterableIterator<T>; entries(): IterableIterator<[number, T]>; /** * @return [...this].toString() */ toString(): string; // Convenience mutators. pop(): T; push(...args: InsertArgs): T | undefined; shift(): T; unshift(...args: InsertArgs): T | undefined; // OPT: may want to optimize methods involving slice // or iteration generally (usually n vs nlog(n)). // OPT: optimize includes, indexOf, lastIndexOf if you know how to get // the index of an element immediately. // OPT: optimize join for TextCollab (in particular, join('')). // Convenience accessors concat(...items: ConcatArray<T>[]): T[]; concat(...items: (T | ConcatArray<T>)[]): T[]; find<S extends T>( predicate: (this: void, value: T, index: number, obj: this) => value is S, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): S | undefined; find( predicate: (value: T, index: number, obj: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): T | undefined; findIndex( predicate: (value: T, index: number, obj: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): number; flatMap<U, This = undefined>( callback: ( this: This, value: T, index: number, array: this ) => U | ReadonlyArray<U>, thisArg?: This ): U[]; flat<D extends number = 1>(depth?: D): FlatArray<T[], D>[]; includes(searchElement: T, fromIndex?: number): boolean; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every( predicate: (value: T, index: number, list: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): boolean; some( predicate: (value: T, index: number, list: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): boolean; forEach( callbackfn: (value: T, index: number, list: this) => void, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): void; map<U>( callbackfn: (value: T, index: number, list: this) => U, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): U[]; filter<S extends T>( predicate: (value: T, index: number, list: this) => value is S, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): S[]; filter( predicate: (value: T, index: number, list: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): T[]; join(separator?: string): string; reduce( callbackfn: ( previousValue: T, currentValue: T, currentIndex: number, list: this ) => T ): T; reduce<U>( callbackfn: ( previousValue: U, currentValue: T, currentIndex: number, list: this ) => U, initialValue: U ): U; reduceRight( callbackfn: ( previousValue: T, currentValue: T, currentIndex: number, list: this ) => T ): T; reduceRight<U>( callbackfn: ( previousValue: U, currentValue: T, currentIndex: number, list: this ) => U, initialValue: U ): U; slice(start?: number, end?: number): T[]; } /** * This mixin adds default implementations of CList * methods to an arbitrary Collab base class. * You may override the default implementations. * * Implemented methods: all except insert, delete, get, * values, and length. * * Due to limitations of TypeScript, this version of the * function sets all of Base's generic type parameters to their * base type constraint (e.g., {} if they are unconstrained). * If you want to override this, you must make an unsafe * cast to the intended constructor type, as demonstrated * by [[AbstractCListCObject]] and the other examples * in this file. * * In CLists with `InsertArgs == [T]``, you * wish to modify [[push]] and [[unshift]] to allow bulk insertions, * like their `Array` versions. * See [[PrimitiveCList]] for an example of how to do this. */ export function MakeAbstractCList< TBase extends abstract new (...args: any[]) => Collab >( Base: TBase ): abstract new <T, InsertArgs extends unknown[]>( ...args: ConstructorParameters<TBase> ) => AbstractCList<T, InsertArgs> & InstanceType<TBase> { // @ts-expect-error generics in mixins are not supported abstract class Mixin<T, InsertArgs extends unknown[]> extends Base implements AbstractCList<T, InsertArgs> { constructor(...args: any[]) { super(...args); } abstract insert(index: number, ...args: InsertArgs): T | undefined; abstract delete(startIndex: number, count?: number): void; abstract get(index: number): T; abstract values(): IterableIterator<T>; abstract readonly length: number; clear(): void { for (let i = this.length - 1; i >= 0; i--) { this.delete(i); } } get size(): number { return this.length; } [Symbol.iterator](): IterableIterator<T> { return this.values(); } *entries(): IterableIterator<[number, T]> { let i = 0; for (const value of this) { yield [i, value]; i++; } } toString(): string { return [...this].toString(); } // Convenience mutators pop(): T { // OPT: implementations can do this more efficiently // (one tree lookup only) using delete's return value, // or by noting that it's guaranteed to be the end of // the list. const value = this.get(this.length - 1); this.delete(this.length - 1); return value; } push(...args: InsertArgs): T | undefined { return this.insert(this.length, ...args); } shift(): T { // OPT: implementations can do this more efficiently // (one tree lookup only) using delete's return value, // or by noting that it's guaranteed to be the start of // the list. const value = this.get(0); this.delete(0); return value; } unshift(...args: InsertArgs): T | undefined { return this.insert(0, ...args); } // Convenience accessors // TODO: Test these work properly with the Array.call // algorithms; not all of them explicitly say so. // I would expect at least the ones that also appear // on TypedArray are safe. private asArrayLike(): ArrayLike<T> { // OPT: cache the value (make a property of the // list), to prevent recreating it each time it is used? // Use a proxy to define [index] accessors return new Proxy(this, { get: function (target, p) { if (p === "length") return target.length; else return target.get(Number.parseInt(p as string)); }, has(_target, _p) { // Let the Array methods know that we do indeed // have properties for all of the indices. return true; }, }) as unknown as { readonly length: number; readonly [index: number]: T; }; } concat(...items: ConcatArray<T>[]): T[]; concat(...items: (T | ConcatArray<T>)[]): T[] { return this.slice().concat(...items); } find<S extends T>( predicate: (this: void, value: T, index: number, obj: this) => value is S, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): S | undefined; find( predicate: (value: T, index: number, obj: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): T | undefined { return <T | undefined>( Array.prototype.find.call( this.asArrayLike(), (value, index) => predicate(value, index, this), thisArg ) ); } findIndex( predicate: (value: T, index: number, obj: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): number { return Array.prototype.findIndex.call( this.asArrayLike(), (value, index) => predicate(value, index, this), thisArg ); } flatMap<U, This = undefined>( callback: ( this: This, value: T, index: number, array: this ) => U | ReadonlyArray<U>, thisArg?: This ): U[] { const outerThis = this; return this.slice().flatMap(function (this: This, value, index) { return callback.call(this, value, index, outerThis); }, thisArg); } flat<D extends number = 1>(depth?: D): FlatArray<T[], D>[] { return this.slice().flat(depth); } includes(searchElement: T, fromIndex?: number): boolean { return Array.prototype.includes.call( this.asArrayLike(), searchElement, fromIndex ); } indexOf(searchElement: T, fromIndex?: number): number { return Array.prototype.indexOf.call( this.asArrayLike(), searchElement, fromIndex ); } lastIndexOf(searchElement: T, fromIndex?: number): number { return Array.prototype.lastIndexOf.call( this.asArrayLike(), searchElement, fromIndex ); } every( predicate: (value: T, index: number, list: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): boolean { const outerThis = this; return Array.prototype.every.call( this.asArrayLike(), function (this: unknown, value, index) { return predicate.call(this, value, index, outerThis); }, thisArg ); } some( predicate: (value: T, index: number, list: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): boolean { const outerThis = this; return Array.prototype.some.call( this.asArrayLike(), function (this: unknown, value, index) { return predicate.call(this, value, index, outerThis); }, thisArg ); } forEach( callbackfn: (value: T, index: number, list: this) => void, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): void { const outerThis = this; return Array.prototype.forEach.call( this.asArrayLike(), function (this: unknown, value, index) { return callbackfn.call(this, value, index, outerThis); }, thisArg ); } map<U>( callbackfn: (value: T, index: number, list: this) => U, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): U[] { const outerThis = this; // Why is the cast needed here? Type inference // seems to be failing. return Array.prototype.map.call( this.asArrayLike(), function (this: unknown, value: T, index: number): U { return callbackfn.call(this, value, index, outerThis); }, thisArg ) as U[]; } filter<S extends T>( predicate: (value: T, index: number, list: this) => value is S, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): S[]; filter( predicate: (value: T, index: number, list: this) => unknown, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): T[] { const outerThis = this; return <T[]>Array.prototype.filter.call( this.asArrayLike(), function (this: unknown, value, index) { return predicate.call(this, value, index, outerThis); }, thisArg ); } join(separator?: string): string { return Array.prototype.join.call(this.asArrayLike(), separator); } reduce( callbackfn: ( previousValue: T, currentValue: T, currentIndex: number, list: this ) => T ): T; // Had to make initialValue optional here, is // that okay? Same in reduceRight. reduce<U>( callbackfn: ( previousValue: U, currentValue: T, currentIndex: number, list: this ) => U, initialValue?: U ): U { const outerThis = this; // Why is the cast and any needed here? Type inference // seems to be failing. return Array.prototype.reduce.call( this.asArrayLike(), function ( this: unknown, // eslint-disable-next-line @typescript-eslint/no-explicit-any previousValue: any, currentValue, currentIndex ) { return callbackfn.call( this, previousValue, currentValue, currentIndex, outerThis ); }, initialValue ) as U; } reduceRight( callbackfn: ( previousValue: T, currentValue: T, currentIndex: number, list: this ) => T ): T; reduceRight<U>( callbackfn: ( previousValue: U, currentValue: T, currentIndex: number, list: this ) => U, initialValue?: U ): U { const outerThis = this; // Why is the cast and any needed here? Type inference // seems to be failing. return Array.prototype.reduceRight.call( this.asArrayLike(), function ( this: unknown, // eslint-disable-next-line @typescript-eslint/no-explicit-any previousValue: any, currentValue, currentIndex ) { return callbackfn.call( this, previousValue, currentValue, currentIndex, outerThis ); }, initialValue ) as U; } slice(start?: number, end?: number): T[] { return <T[]>Array.prototype.slice.call(this.asArrayLike(), start, end); } } // This almost works except it thinks insert's return // type is unknown for some reason? // eslint-disable-next-line return Mixin as any; } export const AbstractCListCObject = MakeAbstractCList(CObject) as abstract new < T, InsertArgs extends unknown[], Events extends CListEventsRecord<T> = CListEventsRecord<T>, C extends Collab = Collab >( initToken: InitToken ) => AbstractCList<T, InsertArgs> & CObject<Events, C>; export const AbstractCListCPrimitive = MakeAbstractCList( CPrimitive ) as abstract new < T, InsertArgs extends unknown[], Events extends CListEventsRecord<T> = CListEventsRecord<T> >( initToken: InitToken ) => AbstractCList<T, InsertArgs> & CPrimitive<Events>; export const AbstractCListCollab = MakeAbstractCList(Collab) as abstract new < T, InsertArgs extends unknown[], Events extends CListEventsRecord<T> = CListEventsRecord<T> >( initToken: InitToken ) => AbstractCList<T, InsertArgs> & Collab<Events>;
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { ApiManagementServiceResource, ApiManagementServiceListByResourceGroupOptionalParams, ApiManagementServiceListOptionalParams, ApiManagementServiceBackupRestoreParameters, ApiManagementServiceRestoreOptionalParams, ApiManagementServiceRestoreResponse, ApiManagementServiceBackupOptionalParams, ApiManagementServiceBackupResponse, ApiManagementServiceCreateOrUpdateOptionalParams, ApiManagementServiceCreateOrUpdateResponse, ApiManagementServiceUpdateParameters, ApiManagementServiceUpdateOptionalParams, ApiManagementServiceUpdateResponse, ApiManagementServiceGetOptionalParams, ApiManagementServiceGetResponse, ApiManagementServiceDeleteOptionalParams, ApiManagementServiceGetSsoTokenOptionalParams, ApiManagementServiceGetSsoTokenResponse, ApiManagementServiceCheckNameAvailabilityParameters, ApiManagementServiceCheckNameAvailabilityOptionalParams, ApiManagementServiceCheckNameAvailabilityResponse, ApiManagementServiceGetDomainOwnershipIdentifierOptionalParams, ApiManagementServiceGetDomainOwnershipIdentifierResponse, ApiManagementServiceApplyNetworkConfigurationUpdatesOptionalParams, ApiManagementServiceApplyNetworkConfigurationUpdatesResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a ApiManagementService. */ export interface ApiManagementService { /** * List all API Management services within a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ listByResourceGroup( resourceGroupName: string, options?: ApiManagementServiceListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<ApiManagementServiceResource>; /** * Lists all API Management services within an Azure subscription. * @param options The options parameters. */ list( options?: ApiManagementServiceListOptionalParams ): PagedAsyncIterableIterator<ApiManagementServiceResource>; /** * Restores a backup of an API Management service created using the ApiManagementService_Backup * operation on the current service. This is a long running operation and could take several minutes to * complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the Restore API Management service from backup operation. * @param options The options parameters. */ beginRestore( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceRestoreOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceRestoreResponse>, ApiManagementServiceRestoreResponse > >; /** * Restores a backup of an API Management service created using the ApiManagementService_Backup * operation on the current service. This is a long running operation and could take several minutes to * complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the Restore API Management service from backup operation. * @param options The options parameters. */ beginRestoreAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceRestoreOptionalParams ): Promise<ApiManagementServiceRestoreResponse>; /** * Creates a backup of the API Management service to the given Azure Storage Account. This is long * running operation and could take several minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the ApiManagementService_Backup operation. * @param options The options parameters. */ beginBackup( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceBackupOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceBackupResponse>, ApiManagementServiceBackupResponse > >; /** * Creates a backup of the API Management service to the given Azure Storage Account. This is long * running operation and could take several minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the ApiManagementService_Backup operation. * @param options The options parameters. */ beginBackupAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceBackupOptionalParams ): Promise<ApiManagementServiceBackupResponse>; /** * Creates or updates an API Management service. This is long running operation and could take several * minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceResource, options?: ApiManagementServiceCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceCreateOrUpdateResponse>, ApiManagementServiceCreateOrUpdateResponse > >; /** * Creates or updates an API Management service. This is long running operation and could take several * minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceResource, options?: ApiManagementServiceCreateOrUpdateOptionalParams ): Promise<ApiManagementServiceCreateOrUpdateResponse>; /** * Updates an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ beginUpdate( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceUpdateParameters, options?: ApiManagementServiceUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceUpdateResponse>, ApiManagementServiceUpdateResponse > >; /** * Updates an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ beginUpdateAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceUpdateParameters, options?: ApiManagementServiceUpdateOptionalParams ): Promise<ApiManagementServiceUpdateResponse>; /** * Gets an API Management service resource description. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceGetOptionalParams ): Promise<ApiManagementServiceGetResponse>; /** * Deletes an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ beginDelete( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceDeleteOptionalParams ): Promise<void>; /** * Gets the Single-Sign-On token for the API Management Service which is valid for 5 Minutes. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ getSsoToken( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceGetSsoTokenOptionalParams ): Promise<ApiManagementServiceGetSsoTokenResponse>; /** * Checks availability and correctness of a name for an API Management service. * @param parameters Parameters supplied to the CheckNameAvailability operation. * @param options The options parameters. */ checkNameAvailability( parameters: ApiManagementServiceCheckNameAvailabilityParameters, options?: ApiManagementServiceCheckNameAvailabilityOptionalParams ): Promise<ApiManagementServiceCheckNameAvailabilityResponse>; /** * Get the custom domain ownership identifier for an API Management service. * @param options The options parameters. */ getDomainOwnershipIdentifier( options?: ApiManagementServiceGetDomainOwnershipIdentifierOptionalParams ): Promise<ApiManagementServiceGetDomainOwnershipIdentifierResponse>; /** * Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated DNS * changes. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ beginApplyNetworkConfigurationUpdates( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceApplyNetworkConfigurationUpdatesOptionalParams ): Promise< PollerLike< PollOperationState< ApiManagementServiceApplyNetworkConfigurationUpdatesResponse >, ApiManagementServiceApplyNetworkConfigurationUpdatesResponse > >; /** * Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated DNS * changes. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ beginApplyNetworkConfigurationUpdatesAndWait( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceApplyNetworkConfigurationUpdatesOptionalParams ): Promise<ApiManagementServiceApplyNetworkConfigurationUpdatesResponse>; }
the_stack
import chalk from 'chalk'; import * as childProcess from 'child_process'; import * as fs from 'fs'; import * as klaw from 'klaw'; import * as minimist from 'minimist'; import * as os from 'os'; import * as path from 'path'; import * as streamChain from 'stream-chain'; import * as streamJson from 'stream-json'; import { ignore as streamJsonIgnore } from 'stream-json/filters/Ignore'; import { streamArray as streamJsonStreamArray } from 'stream-json/streamers/StreamArray'; const SOURCE_ROOT = path.normalize(path.dirname(__dirname)); const LLVM_BIN = path.resolve( SOURCE_ROOT, '..', 'third_party', 'llvm-build', 'Release+Asserts', 'bin' ); const PLATFORM = os.platform(); type SpawnAsyncResult = { stdout: string; stderr: string; status: number | null; }; class ErrorWithExitCode extends Error { exitCode: number; constructor (message: string, exitCode: number) { super(message); this.exitCode = exitCode; } } async function spawnAsync ( command: string, args: string[], options?: childProcess.SpawnOptionsWithoutStdio | undefined ): Promise<SpawnAsyncResult> { return new Promise((resolve, reject) => { try { const stdio = { stdout: '', stderr: '' }; const spawned = childProcess.spawn(command, args, options || {}); spawned.stdout.on('data', (data) => { stdio.stdout += data; }); spawned.stderr.on('data', (data) => { stdio.stderr += data; }); spawned.on('exit', (code) => resolve({ ...stdio, status: code })); spawned.on('error', (err) => reject(err)); } catch (err) { reject(err); } }); } function getDepotToolsEnv (): NodeJS.ProcessEnv { let depotToolsEnv; const findDepotToolsOnPath = () => { const result = childProcess.spawnSync( PLATFORM === 'win32' ? 'where' : 'which', ['gclient'] ); if (result.status === 0) { return process.env; } }; const checkForBuildTools = () => { const result = childProcess.spawnSync( 'electron-build-tools', ['show', 'env', '--json'], { shell: true } ); if (result.status === 0) { return { ...process.env, ...JSON.parse(result.stdout.toString().trim()) }; } }; try { depotToolsEnv = findDepotToolsOnPath(); if (!depotToolsEnv) depotToolsEnv = checkForBuildTools(); } catch {} if (!depotToolsEnv) { throw new Error("Couldn't find depot_tools, ensure it's on your PATH"); } if (!('CHROMIUM_BUILDTOOLS_PATH' in depotToolsEnv)) { throw new Error( 'CHROMIUM_BUILDTOOLS_PATH environment variable must be set' ); } return depotToolsEnv; } function chunkFilenames (filenames: string[], offset: number = 0): string[][] { // Windows has a max command line length of 2047 characters, so we can't // provide too many filenames without going over that. To work around that, // chunk up a list of filenames such that it won't go over that limit when // used as args. Use a much higher limit on other platforms which will // effectively be a no-op. const MAX_FILENAME_ARGS_LENGTH = PLATFORM === 'win32' ? 2047 - offset : 100 * 1024; return filenames.reduce( (chunkedFilenames: string[][], filename) => { const currChunk = chunkedFilenames[chunkedFilenames.length - 1]; const currChunkLength = currChunk.reduce( (totalLength, _filename) => totalLength + _filename.length + 1, 0 ); if (currChunkLength + filename.length + 1 > MAX_FILENAME_ARGS_LENGTH) { chunkedFilenames.push([filename]); } else { currChunk.push(filename); } return chunkedFilenames; }, [[]] ); } async function runClangTidy ( outDir: string, filenames: string[], checks: string = '', jobs: number = 1 ): Promise<boolean> { const cmd = path.resolve(LLVM_BIN, 'clang-tidy'); const args = [`-p=${outDir}`]; if (checks) args.push(`--checks=${checks}`); // Remove any files that aren't in the compilation database to prevent // errors from cluttering up the output. Since the compilation DB is hundreds // of megabytes, this is done with streaming to not hold it all in memory. const filterCompilationDatabase = (): Promise<string[]> => { const compiledFilenames: string[] = []; return new Promise((resolve) => { const pipeline = streamChain.chain([ fs.createReadStream(path.resolve(outDir, 'compile_commands.json')), streamJson.parser(), streamJsonIgnore({ filter: /\bcommand\b/i }), streamJsonStreamArray(), ({ value: { file, directory } }) => { const filename = path.resolve(directory, file); return filenames.includes(filename) ? filename : null; } ]); pipeline.on('data', (data) => compiledFilenames.push(data)); pipeline.on('end', () => resolve(compiledFilenames)); }); }; // clang-tidy can figure out the file from a short relative filename, so // to get the most bang for the buck on the command line, let's trim the // filenames to the minimum so that we can fit more per invocation filenames = (await filterCompilationDatabase()).map((filename) => path.relative(SOURCE_ROOT, filename) ); if (filenames.length === 0) { throw new Error('No filenames to run'); } const commandLength = cmd.length + args.reduce((length, arg) => length + arg.length, 0); const results: boolean[] = []; const asyncWorkers = []; const chunkedFilenames: string[][] = []; const filesPerWorker = Math.ceil(filenames.length / jobs); for (let i = 0; i < jobs; i++) { chunkedFilenames.push( ...chunkFilenames(filenames.splice(0, filesPerWorker), commandLength) ); } const worker = async () => { let filenames = chunkedFilenames.shift(); while (filenames) { results.push( await spawnAsync(cmd, [...args, ...filenames], {}).then((result) => { // We lost color, so recolorize because it's much more legible // There's a --use-color flag for clang-tidy but it has no effect // on Windows at the moment, so just recolor for everyone let state = null; for (const line of result.stdout.split('\n')) { if (line.includes(' warning: ')) { console.log( line .split(' warning: ') .map((part) => chalk.whiteBright(part)) .join(chalk.magentaBright(' warning: ')) ); state = 'code-line'; } else if (line.includes(' note: ')) { const lineParts = line.split(' note: '); lineParts[0] = chalk.whiteBright(lineParts[0]); console.log(lineParts.join(chalk.grey(' note: '))); state = 'code-line'; } else if (line.startsWith('error:')) { console.log( chalk.redBright('error: ') + line.split(' ').slice(1).join(' ') ); } else if (state === 'code-line') { console.log(line); state = 'post-code-line'; } else if (state === 'post-code-line') { console.log(chalk.greenBright(line)); } else { console.log(line); } } if (result.status !== 0) { console.error(result.stderr); } // On a clean run there's nothing on stdout. A run with warnings-only // will have a status code of zero, but there's output on stdout return result.status === 0 && result.stdout.length === 0; }) ); filenames = chunkedFilenames.shift(); } }; for (let i = 0; i < jobs; i++) { asyncWorkers.push(worker()); } try { await Promise.all(asyncWorkers); return results.every((x) => x); } catch { return false; } } async function findMatchingFiles ( top: string, test: (filename: string) => boolean ): Promise<string[]> { return new Promise((resolve) => { const matches = [] as string[]; klaw(top, { filter: (f) => path.basename(f) !== '.bin' }) .on('end', () => resolve(matches)) .on('data', (item) => { if (test(item.path)) { matches.push(item.path); } }); }); } function parseCommandLine () { const showUsage = (arg?: string) : boolean => { if (!arg || arg.startsWith('-')) { console.log( 'Usage: script/run-clang-tidy.ts [-h|--help] [--jobs|-j] ' + '[--checks] --out-dir OUTDIR [file1 file2]' ); process.exit(0); } return true; }; const opts = minimist(process.argv.slice(2), { boolean: ['help'], string: ['checks', 'out-dir'], default: { jobs: 1 }, alias: { help: 'h', jobs: 'j' }, stopEarly: true, unknown: showUsage }); if (opts.help) showUsage(); if (!opts['out-dir']) { console.log('--out-dir is a required argunment'); process.exit(0); } return opts; } async function main (): Promise<boolean> { const opts = parseCommandLine(); const outDir = path.resolve(opts['out-dir']); if (!fs.existsSync(outDir)) { throw new Error("Output directory doesn't exist"); } else { // Make sure the compile_commands.json file is up-to-date const env = getDepotToolsEnv(); const result = childProcess.spawnSync( 'gn', ['gen', '.', '--export-compile-commands'], { cwd: outDir, env, shell: true } ); if (result.status !== 0) { if (result.error) { console.error(result.error.message); } else { console.error(result.stderr.toString()); } throw new ErrorWithExitCode( 'Failed to automatically generate compile_commands.json for ' + 'output directory', 2 ); } } const filenames = []; if (opts._.length > 0) { filenames.push(...opts._.map((filename) => path.resolve(filename))); } else { filenames.push( ...(await findMatchingFiles( path.resolve(SOURCE_ROOT, 'shell'), (filename: string) => /.*\.(?:cc|h|mm)$/.test(filename) )) ); } return runClangTidy(outDir, filenames, opts.checks, opts.jobs); } if (require.main === module) { main() .then((success) => { process.exit(success ? 0 : 1); }) .catch((err: ErrorWithExitCode) => { console.error(`ERROR: ${err.message}`); process.exit(err.exitCode || 1); }); }
the_stack
import { graphTypes, getEnvironmentsByRoleId, getAppRoleEnvironmentRolesByEnvironmentRoleId, deleteGraphObjects, getUpdateEnvironmentRoleProducer, getOrphanedLocalKeyIds, } from "@core/lib/graph"; import { apiAction } from "../handler"; import { Api } from "@core/types"; import { v4 as uuid } from "uuid"; import { pickDefined } from "@core/lib/utils/object"; import produce, { Draft } from "immer"; import * as R from "ramda"; import * as graphKey from "../graph_key"; import { log } from "@core/lib/utils/logger"; apiAction< Api.Action.RequestActions["RbacCreateEnvironmentRole"], Api.Net.ApiResultTypes["RbacCreateEnvironmentRole"] >({ type: Api.ActionType.RBAC_CREATE_ENVIRONMENT_ROLE, authenticated: true, graphAction: true, rbacUpdate: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => { const appRoleIds = graphTypes(orgGraph) .appRoles.filter(R.complement(R.prop("hasFullEnvironmentPermissions"))) .map(R.prop("id")); if ( !R.equals( appRoleIds.sort(), Object.keys(payload.appRoleEnvironmentRoles).sort() ) ) { return false; } return auth.orgPermissions.has("org_manage_environment_roles"); }, graphHandler: async ({ payload }, orgGraph, auth, now) => { const environmentRoles = graphTypes(orgGraph).environmentRoles; const id = uuid(), environmentRole = { type: "environmentRole", id, ...graphKey.environmentRole(auth.org.id, id), isDefault: false, ...pickDefined( [ "name", "description", "hasLocalKeys", "hasServers", "defaultAllApps", "defaultAllBlocks", "settings", ], payload ), orderIndex: environmentRoles[environmentRoles.length - 1].orderIndex + 1, createdAt: now, updatedAt: now, } as Api.Db.EnvironmentRole; const updatedGraph = produce(orgGraph, (draft) => { draft[environmentRole.id] = environmentRole; if (environmentRole.defaultAllApps) { const apps = graphTypes(orgGraph).apps; for (let app of apps) { const id = uuid(), environment: Api.Db.Environment = { type: "environment", id, ...graphKey.environment(auth.org.id, app.id, id), envParentId: app.id, environmentRoleId: environmentRole.id, isSub: false, settings: {}, createdAt: now, updatedAt: now, }; draft[environment.id] = environment; } } if (environmentRole.defaultAllBlocks) { const blocks = graphTypes(orgGraph).blocks; for (let block of blocks) { const id = uuid(), environment: Api.Db.Environment = { type: "environment", id, ...graphKey.environment(auth.org.id, block.id, id), envParentId: block.id, environmentRoleId: environmentRole.id, isSub: false, settings: {}, createdAt: now, updatedAt: now, }; draft[environment.id] = environment; } } for (let appRoleId in payload.appRoleEnvironmentRoles) { const id = uuid(), appRoleEnvironmentRole: Api.Db.AppRoleEnvironmentRole = { type: "appRoleEnvironmentRole", id, ...graphKey.appRoleEnvironmentRole(auth.org.id, id), appRoleId, environmentRoleId: environmentRole.id, permissions: payload.appRoleEnvironmentRoles[appRoleId], createdAt: now, updatedAt: now, }; draft[appRoleEnvironmentRole.id] = appRoleEnvironmentRole; } }); return { type: "graphHandlerResult", graph: updatedGraph, logTargetIds: [ environmentRole.id, ...(environmentRole.defaultAllApps ? graphTypes(orgGraph).apps.map(R.prop("id")) : []), ...(environmentRole.defaultAllBlocks ? graphTypes(orgGraph).blocks.map(R.prop("id")) : []), ], }; }, }); apiAction< Api.Action.RequestActions["RbacDeleteEnvironmentRole"], Api.Net.ApiResultTypes["RbacDeleteEnvironmentRole"] >({ type: Api.ActionType.RBAC_DELETE_ENVIRONMENT_ROLE, authenticated: true, graphAction: true, rbacUpdate: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => { const environmentRole = userGraph[payload.id]; if ( !environmentRole || environmentRole.type != "environmentRole" || environmentRole.isDefault ) { return false; } return auth.orgPermissions.has("org_manage_environment_roles"); }, graphHandler: async ({ payload }, orgGraph, auth, now) => { const environmentRole = orgGraph[payload.id] as Api.Db.EnvironmentRole; const byType = graphTypes(orgGraph); const environments = getEnvironmentsByRoleId(orgGraph)[payload.id] ?? [], environmentIds = environments.map(R.prop("id")), environmentIdsSet = new Set(environmentIds), keyableParents = [...byType.servers, ...byType.localKeys].filter( ({ environmentId }) => environmentIdsSet.has(environmentId) ), keyableParentIds = keyableParents.map(R.prop("id")), keyableParentIdsSet = new Set(keyableParentIds), generatedEnvkeys = byType.generatedEnvkeys.filter(({ keyableParentId }) => keyableParentIdsSet.has(keyableParentId) ), appRoleEnvironmentRoles = getAppRoleEnvironmentRolesByEnvironmentRoleId(orgGraph)[payload.id] || []; // clear environment role from environmentRoleIpsAllowed (firewall config) on org or any app const updatedGraph = produce(orgGraph, (graphDraft) => { if (auth.org.environmentRoleIpsAllowed?.[environmentRole.id]) { const orgDraft = graphDraft[auth.org.id] as Draft<Api.Db.Org>; delete orgDraft.environmentRoleIpsAllowed![environmentRole.id]; } for (let { id: appId, environmentRoleIpsAllowed } of byType.apps) { if (environmentRoleIpsAllowed?.[environmentRole.id]) { const appDraft = graphDraft[appId] as Draft<Api.Db.App>; delete appDraft.environmentRoleIpsAllowed![environmentRole.id]; } } }); return { type: "graphHandlerResult", graph: deleteGraphObjects( updatedGraph, [ payload.id, ...environmentIds, ...appRoleEnvironmentRoles.map(R.prop("id")), ...keyableParentIds, ...generatedEnvkeys.map(R.prop("id")), ], now ), transactionItems: { hardDeleteEncryptedBlobParams: environments.flatMap((environment) => [ { orgId: auth.org.id, envParentId: environment.envParentId, environmentId: environment.id, blobType: "env", }, { orgId: auth.org.id, envParentId: environment.envParentId, environmentId: environment.id, blobType: "changeset", }, ]), }, logTargetIds: [ environmentRole.id, ...R.uniq(environments.map(R.prop("envParentId"))), ], clearEnvkeySockets: generatedEnvkeys.map((generatedEnvkeyId) => ({ orgId: auth.org.id, generatedEnvkeyId, })), }; }, }); apiAction< Api.Action.RequestActions["RbacUpdateEnvironmentRole"], Api.Net.ApiResultTypes["RbacUpdateEnvironmentRole"] >({ type: Api.ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE, authenticated: true, graphAction: true, rbacUpdate: true, shouldClearOrphanedLocals: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => { const environmentRole = userGraph[payload.id]; if (!environmentRole || environmentRole.type != "environmentRole") { return false; } return auth.orgPermissions.has("org_manage_environment_roles"); }, graphHandler: async ({ payload }, orgGraph, auth, now) => { const environmentRole = orgGraph[payload.id] as Api.Db.EnvironmentRole; const environments = getEnvironmentsByRoleId(orgGraph)[payload.id] ?? []; const producerFn = getUpdateEnvironmentRoleProducer<Api.Graph.OrgGraph>( payload, now ); const updatedGraph = produce<Api.Graph.OrgGraph>(orgGraph, producerFn); const orphanedLocalKeyIds = getOrphanedLocalKeyIds(updatedGraph); const localKeyIdsSet = new Set(orphanedLocalKeyIds); const generatedEnvkeys = graphTypes(orgGraph).generatedEnvkeys.filter( ({ keyableParentId }) => localKeyIdsSet.has(keyableParentId) ); return { type: "graphHandlerResult", graph: updatedGraph, // TODO: narrow down rbac scopes encryptedKeysScope: "all", logTargetIds: [ environmentRole.id, ...R.uniq(environments.map(R.prop("envParentId"))), ], clearEnvkeySockets: generatedEnvkeys.map((generatedEnvkeyId) => ({ orgId: auth.org.id, generatedEnvkeyId, })), }; }, }); apiAction< Api.Action.RequestActions["RbacUpdateEnvironmentRoleSettings"], Api.Net.ApiResultTypes["RbacUpdateEnvironmentRoleSettings"] >({ type: Api.ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE_SETTINGS, authenticated: true, graphAction: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => { const environmentRole = userGraph[payload.id]; if (!environmentRole || environmentRole.type != "environmentRole") { return false; } return auth.orgPermissions.has("org_manage_environment_roles"); }, graphHandler: async ({ payload }, orgGraph, auth, now) => { const environmentRole = orgGraph[payload.id] as Api.Db.EnvironmentRole; const environments = getEnvironmentsByRoleId(orgGraph)[payload.id] ?? []; return { type: "graphHandlerResult", graph: { ...orgGraph, [payload.id]: { ...environmentRole, settings: payload.settings, updatedAt: now, }, }, logTargetIds: [ environmentRole.id, ...R.uniq(environments.map(R.prop("envParentId"))), ], }; }, }); apiAction< Api.Action.RequestActions["RbacReorderEnvironmentRoles"], Api.Net.ApiResultTypes["RbacReorderEnvironmentRoles"] >({ type: Api.ActionType.RBAC_REORDER_ENVIRONMENT_ROLES, graphAction: true, authenticated: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => { if (!auth.orgPermissions.has("org_manage_environment_roles")) { return false; } const { environmentRoles } = graphTypes(orgGraph); for (let { id } of environmentRoles) { if (typeof payload[id] != "number") { return false; } } return true; }, graphHandler: async ({ payload }, orgGraph, auth, now) => { const updatedGraph = produce(orgGraph, (draft) => { for (let id in payload) { const draftEnvironmentRole = draft[id] as Api.Db.EnvironmentRole; draftEnvironmentRole.orderIndex = payload[id]; draftEnvironmentRole.updatedAt = now; } }); const { environments } = graphTypes(orgGraph); return { type: "graphHandlerResult", graph: updatedGraph, logTargetIds: R.uniq(environments.map(R.prop("envParentId"))), }; }, });
the_stack
import type { HttpMethod, IAuthSession } from '@looker/sdk-rtl' import { APIMethods } from '@looker/sdk-rtl' import type { ColumnHeaders, IRowModel } from './RowModel' import { rowPosition } from './RowModel' /** Keyed data for a tab, and the tab's header row */ export interface ITabTable { /** Array of header names, in column order */ header: ColumnHeaders /** Parsed data for the tab */ rows: IRowModel[] } export const defaultScopes = [ // 'https://www.googleapis.com/auth/drive', // 'https://www.googleapis.com/auth/drive.file', // 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/spreadsheets', // 'https://www.googleapis.com/auth/spreadsheets.readonly', ] // https://developers.google.com/sheets/api/reference/rest export class SheetError extends Error { constructor(message?: string) { super(message) // 'Error' breaks prototype chain here Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain } } // Manually recreated type/interface declarations that are NOT complete export interface ITabGridProperties { rowCount: number columnCount: number } export interface ITabProperties { sheetId: number title: string index: number sheetType: string gridProperties: ITabGridProperties } export interface ICellValue { stringValue: string } export interface ICellTextFormat { fontFamily: string } export interface ICellFormat { verticalAlignment: string textFormat: ICellTextFormat } export interface ICellData { userEnteredValue: ICellValue effectiveValue: ICellValue formattedValue: string userEnteredFormat: ICellFormat // effectiveFormat: { // "backgroundColor": { // "red": 1, // "green": 1, // "blue": 1 // }, // "padding": { // "top": 2, // "right": 3, // "bottom": 2, // "left": 3 // }, // "horizontalAlignment": "LEFT", // "verticalAlignment": "BOTTOM", // "wrapStrategy": "OVERFLOW_CELL", // "textFormat": { // "foregroundColor": {}, // "fontFamily": "Arial", // "fontSize": 10, // "bold": false, // "italic": false, // "strikethrough": false, // "underline": false, // "foregroundColorStyle": { // "rgbColor": {} // } // }, // "hyperlinkDisplayType": "PLAIN_TEXT", // "backgroundColorStyle": { // "rgbColor": { // "red": 1, // "green": 1, // "blue": 1 // } // } // } } export interface ITabRowData { values: ICellData[] } export interface ITabData { rowData: ITabRowData[] } export interface ISheetTab { properties: ITabProperties data: ITabData } export interface ISheetProperties { title: string local: string autoRecalc: string timeZone: string } export type TabTables = Record<string, ITabTable> export interface ISheet { /** id of the spreadsheet */ spreadsheetId: string /** Sheet metadata */ properties: ISheetProperties /** Individual sheet tabs */ sheets: ISheetTab[] /** All tabs data loaded into a keyed collection of TabData */ tabs: TabTables /** Url where sheet can be viewed */ spreadsheetUrl: string } /** * Returns the name of the tab * @param tab string or ISheetTab interface */ export const tabName = (tab: string | ISheetTab) => { if (typeof tab === 'string') return tab return tab.properties.title } /** * Loads the GSheet data from a sheet (tab) into a header name collection and data rows * * NOTE: data collection stops when a blank row is encountered, or or at the end of all rows. * * @param tab GSheet sheet to process * @param keyName Optional key column name. Defaults to _id */ export const loadTabTable = (tab: ISheetTab, keyName = '_id'): ITabTable => { const result: ITabTable = { header: [], rows: [], } const rowData = tab.data[0].rowData if (rowData.length < 1) return result // Get column headers const values = rowData[0].values for (let i = 0; i < values.length; i++) { const cell = values[i] // Are we at an empty header column? if (!cell.formattedValue) break result.header.push(cell.formattedValue) } // Index row data for (let rowIndex = 1; rowIndex < rowData.length; rowIndex++) { const r = rowData[rowIndex] const row = {} row[rowPosition] = rowIndex + 1 result.header.forEach((colName, index) => { if (index < r.values.length) { const cell: ICellData = r.values[index] // Only assign cells with values if (cell.formattedValue) row[colName] = cell.formattedValue } }) // An empty data row means we've hit the last row of data // some tabs have thousands of rows of no data if (Object.keys(row).length === 1) { break } if (!row[keyName]) { throw new SheetError( `Tab ${tabName(tab)} row ${rowIndex + 1} has no key column '${keyName}'` ) } result.rows.push(row as IRowModel) } return result } // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values export type SheetValues = any[] const sheetSDKVersion = '0.5.0-beta' export interface ISheetRowResponse { row: number values: SheetValues } export class SheetSDK extends APIMethods { constructor(authSession: IAuthSession, public sheetId: string) { super(authSession, sheetSDKVersion) authSession.settings.agentTag = `SheetSDK ${this.apiVersion}` this.sheetId = encodeURIComponent(sheetId) } async request<TSuccess>(method: HttpMethod, api = '', body: any = undefined) { const path = `https://sheets.googleapis.com/v4/spreadsheets/${this.sheetId}${api}` const response = await this.ok<TSuccess, SheetError>( this.authRequest<TSuccess, SheetError>(method, path, undefined, body) ) // const response = await parseResponse(raw) // if (!raw.ok) throw new SheetError(response) return response } /** * retrieve the entire sheet * **NOTE**: this response is cast to the ISheet interface so some properties may be hidden */ async read() { const api = '?includeGridData=true' const result = (await this.request('GET', api)) as ISheet return result } /** * Index the raw sheet into tab data * @param doc Sheet to index */ async index(doc?: ISheet): Promise<ISheet> { if (!doc) doc = await this.read() if (doc) { doc.tabs = {} // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore doc.sheets.forEach((tab) => (doc.tabs[tabName(tab)] = loadTabTable(tab))) } return doc } /** * Get a values collection for the specified range * @param range Defaults to all values in the default (first?) tab */ async getValues(range = '!A1:end') { const api = range ? `/values/${range}` : '' const sheet = await this.request<any>('GET', api) return sheet.values as SheetValues } /** * Get the values for a sheet row * @param tab name or tab sheet * @param row to retrieve */ async rowGet(tab: string | ISheetTab, row: number) { if (!row) throw new SheetError('row cannot be zero') const name = tabName(tab) const api = `/values/${name}!A${row}:end` const sheet = await this.request<any>('GET', api) return sheet.values as SheetValues } /** * Replaces all values in a sheet from row to the length of the values array * @param tab to update * @param values row array of values * @param row starting position to replace. Defaults to the first row of the sheet */ async batchUpdate(tab: string | ISheetTab, values: SheetValues, row = 1) { if (!values || values.length === 0 || !Array.isArray(values[0])) throw new SheetError( `Nothing to batch update. Expected an array of row values` ) const name = tabName(tab) const data = { range: `${name}!A${row}:end`, majorDimension: 'ROWS', values: values, } const api = `/values:batchUpdate` const body = { valueInputOption: 'RAW', data: [data], includeValuesInResponse: true, responseValueRenderOption: 'UNFORMATTED_VALUE', responseDateTimeRenderOption: 'FORMATTED_STRING', } const response = await this.request<any>('POST', api, JSON.stringify(body)) // remove header row const update = response.responses[0].updatedData.values.slice(1) return update } /** * Clear all values from a tab * @param tab to clear */ async tabClear(tab: string | ISheetTab) { const name = tabName(tab) // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear // TODO is there a way to KNOW what the last column is? const body = { ranges: [name] } const api = `/values:batchClear` const response = await this.request<any>('POST', api, JSON.stringify(body)) return response } /** * Delete the specified row on the tab by compacting the tab * @param tab name or ISheetTab * @param row to remove */ async rowDelete(tab: string | ISheetTab, row: number) { /** * Multiple expensive steps required for this functionality: * - read all values from the sheet * - delete the array entry for the requested row * - batch update the sheet with the new collection */ if (!row) throw new SheetError('row cannot be zero') const batch = await this.tabValues(tab) const rowPos = row - 1 if (rowPos > batch.length) throw new SheetError( `Row ${row} doesn't exist. ${batch.length} rows found.` ) await this.tabClear(tab) // Remove the target row batch.splice(rowPos, 1) const values = await this.batchUpdate(tab, batch) return values } private static bodyValues(values: SheetValues) { return JSON.stringify({ values: [values] }) } /** * Update a row of a sheet with the provided values * * @param tab name or tab sheet * @param row 1-based position of row * @param values to assign in order for the row * * The values collection returned has all rows starting from the updated row * to the end of the sheet. If only one row of values is passed in, only * one row is actually updated, but all remaining rows to the end of the sheet * are also returned */ async rowUpdate( tab: string | ISheetTab, row: number, values: SheetValues ): Promise<ISheetRowResponse> { const body = SheetSDK.bodyValues(values) const name = tabName(tab) // TODO receive changed values back from request // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update const options = 'valueInputOption=RAW&includeValuesInResponse=true&responseValueRenderOption=FORMATTED_VALUE' const api = `/values/${name}!A${row}:end?${options}` const response = await this.request<any>('PUT', api, body) const changeCount = values.length const expected = `1 row(s), ${changeCount} column(s), ${changeCount} cells` const actual = `${response.updatedRows} row(s), ${response.updatedColumns} column(s), ${response.updatedCells} cells` if (expected !== actual) throw new SheetError(`Update expected ${expected} but got ${actual}`) return { row: row, values: response.updatedData.values } } /** * Create a row of a sheet with the provided values * * @param tab name or tab sheet * @param row 1-based position of row * @param values to assign in order for the row * @return number of the created row * * The values collection returned includes only the rows of data that were created */ async rowCreate( tab: string | ISheetTab, row: number, values: SheetValues ): Promise<ISheetRowResponse> { const body = SheetSDK.bodyValues(values) const name = tabName(tab) // TODO receive changed values back from request // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append const options = 'valueInputOption=RAW&insertDataOption=INSERT_ROWS&includeValuesInResponse=true&responseValueRenderOption=FORMATTED_VALUE' const api = `/values/${name}!A${row}:end:append?${options}` const response = await this.request<any>('POST', api, body) const range = response.updates.updatedRange const match = range.match(/!A(\d+):/) if (!match) { throw new SheetError(`Update couldn't extract row from range ${range}`) } const rowId = parseInt(match[1]) return { row: rowId, values: response.updates.updatedData.values } } /** * Get values (rows of columns) from the tab * @param tab name or ISheetTab * @param range defaults to the entire sheet */ async tabValues(tab: string | ISheetTab, range = '!A1:end') { return await this.getValues(`${tabName(tab)}${range}`) } }
the_stack
import * as React from "react"; import { IObject, isString, isArray, isNumber } from "@daybrush/utils"; import { prefix, getId, getScenaAttrs, isScenaFunction, isScenaElement, isScenaFunctionElement, getOffsetOriginMatrix, updateElements } from "../utils/utils"; import { DATA_SCENA_ELEMENT_ID } from "../consts"; import { ScenaJSXElement, ScenaComponent, ElementInfo, AddedInfo, RemovedInfo, MovedResult } from "../types"; export default class Viewport extends React.PureComponent<{ style: IObject<any>, onBlur: (e: any) => any, }> { public components: IObject<ScenaComponent> = {}; public jsxs: IObject<ScenaJSXElement> = {}; public viewport: ElementInfo = { jsx: <div></div>, name: "Viewport", id: "viewport", children: [], }; public ids: IObject<ElementInfo> = { viewport: this.viewport, }; public state = {}; public viewportRef = React.createRef<HTMLDivElement>(); public render() { const style = this.props.style; return <div className={prefix("viewport-container")} onBlur={this.props.onBlur} style={style}> {this.props.children} <div className={prefix("viewport")} {...{ [DATA_SCENA_ELEMENT_ID]: "viewport" }} ref={this.viewportRef}> {this.renderChildren(this.getViewportInfos())} </div> </div>; } public componentDidMount() { this.ids.viewport.el = this.viewportRef.current!; } public renderChildren(children: ElementInfo[]): ScenaJSXElement[] { return children.map(info => { const jsx = info.jsx; const nextChildren = info.children!; const renderedChildren = this.renderChildren(nextChildren); const id = info.id!; const props: IObject<any> = { key: id, }; if (isString(jsx)) { props[DATA_SCENA_ELEMENT_ID] = id; return React.createElement(jsx, props, ...renderedChildren) as ScenaJSXElement; } else if (isScenaFunction(jsx)) { props.scenaElementId = id; props.scenaAttrs = info.attrs || {}; props.scenaText = info.innerText; props.scenaHTML = info.innerHTML; return React.createElement(jsx, props) as ScenaJSXElement; } else if (isString(jsx.type)) { props[DATA_SCENA_ELEMENT_ID] = id; } else { props.scenaElementId = id; props.scenaAttrs = info.attrs || {}; props.scenaText = info.innerText; props.scenaHTML = info.innerHTML; } const jsxChildren = jsx.props.children; return React.cloneElement(jsx, { ...jsx.props, ...props }, ...(isArray(jsxChildren) ? jsxChildren : [jsxChildren]), ...this.renderChildren(nextChildren), ) as ScenaJSXElement; }); } public getJSX(id: string) { return this.jsxs[id]; } public getComponent(id: string) { return this.components[id]; } public makeId(ids: IObject<any> = this.ids) { while (true) { const id = `scena${Math.floor(Math.random() * 100000000)}`; if (ids[id]) { continue; } return id; } } public setInfo(id: string, info: ElementInfo) { const ids = this.ids; ids[id] = info; } public getInfo(id: string) { return this.ids[id]; } public getLastChildInfo(id: string) { const info = this.getInfo(id); const children = info.children!; return children[children.length - 1]; } public getNextInfo(id: string) { const info = this.getInfo(id); const parentInfo = this.getInfo(info.scopeId!)!; const parentChildren = parentInfo.children!; const index = parentChildren.indexOf(info); return parentChildren[index + 1]; } public getPrevInfo(id: string) { const info = this.getInfo(id); const parentInfo = this.getInfo(info.scopeId!)!; const parentChildren = parentInfo.children!; const index = parentChildren.indexOf(info); return parentChildren[index - 1]; } public getInfoByElement(el: HTMLElement | SVGElement) { return this.ids[getId(el)]; } public getInfoByIndexes(indexes: number[]) { return indexes.reduce((info: ElementInfo, index: number) => { return info.children![index]; }, this.viewport); } public getElement(id: string) { const info = this.getInfo(id); return info ? info.el : null; } public getViewportInfos() { return this.viewport.children!; } public getIndexes(target: HTMLElement | SVGElement | string): number[] { const info = (isString(target) ? this.getInfo(target) : this.getInfoByElement(target))!; if (!info.scopeId) { return []; } const parentInfo = this.getInfo(info.scopeId)!; return [...this.getIndexes(info.scopeId), parentInfo.children!.indexOf(info)]; } public registerChildren(jsxs: ElementInfo[], parentScopeId?: string) { return jsxs.map(info => { const id = info.id || this.makeId(); const jsx = info.jsx; const children = info.children || []; const scopeId = parentScopeId || info.scopeId || "viewport"; let componentId = ""; let jsxId = ""; if (isScenaElement(jsx)) { jsxId = this.makeId(this.jsxs); this.jsxs[jsxId] = jsx; // const component = jsx.type; // componentId = component.scenaComponentId; // this.components[componentId] = component; } const elementInfo: ElementInfo = { ...info, jsx, children: this.registerChildren(children, id), scopeId, componentId, jsxId, frame: info.frame || {}, el: null, id, }; this.setInfo(id, elementInfo); return elementInfo; }); } public appendJSXs(jsxs: ElementInfo[], appendIndex: number, scopeId?: string): Promise<AddedInfo> { const jsxInfos = this.registerChildren(jsxs, scopeId); jsxInfos.forEach((info, i) => { const scopeInfo = this.getInfo(scopeId || info.scopeId!); const children = scopeInfo.children!; if (appendIndex > -1) { children.splice(appendIndex + i, 0, info); info.index = appendIndex + i; } else if (isNumber(info.index)) { children.splice(info.index, 0, info); } else { info.index = children.length; children.push(info); } }); return new Promise(resolve => { this.forceUpdate(() => { resolve({ added: updateElements(jsxInfos), }); }); }); } public getIndex(id: string | HTMLElement) { const indexes = this.getIndexes(id); const length = indexes.length; return length ? indexes[length - 1] : -1; } public getElements(ids: string[]) { return ids.map(id => this.getElement(id)).filter(el => el) as Array<HTMLElement | SVGElement>; } public unregisterChildren(children: ElementInfo[], isChild?: boolean): ElementInfo[] { const ids = this.ids; return children.slice(0).map(info => { const target = info.el!; let innerText = ""; let innerHTML = ""; if (info.attrs!.contenteditable) { innerText = (target as HTMLElement).innerText; } else { innerHTML = target.innerHTML; } if (!isChild) { const parentInfo = this.getInfo(info.scopeId!); const parentChildren = parentInfo.children!; const index = parentChildren.indexOf(info); parentInfo.children!.splice(index, 1); } const nextChildren = this.unregisterChildren(info.children!, true); delete ids[info.id!]; delete info.el; return { ...info, innerText, innerHTML, attrs: getScenaAttrs(target), children: nextChildren, }; }); } public removeTargets(targets: Array<HTMLElement | SVGElement>): Promise<RemovedInfo> { const removedChildren = this.getSortedTargets(targets).map(target => { return this.getInfoByElement(target); }).filter(info => info) as ElementInfo[]; const indexes = removedChildren.map(info => this.getIndex(info.id!)); const removed = this.unregisterChildren(removedChildren); removed.forEach((info, i) => { info.index = indexes[i]; }) return new Promise(resolve => { this.forceUpdate(() => { resolve({ removed, }); }) }); } public getSortedIndexesList(targets: Array<string | HTMLElement | SVGElement | number[]>) { const indexesList = targets.map(target => { if (Array.isArray(target)) { return target; } return this.getIndexes(target!) }); indexesList.sort((a, b) => { const aLength = a.length; const bLength = b.length; const length = Math.min(aLength, bLength); for (let i = 0; i < length; ++i) { if (a[i] === b[i]) { continue; } return a[i] - b[i]; } return aLength - bLength; }); return indexesList; } public getSortedTargets(targets: Array<string | HTMLElement | SVGElement>) { return this.getSortedInfos(targets).map(info => info.el!); } public getSortedInfos(targets: Array<string | HTMLElement | SVGElement>) { const indexesList = this.getSortedIndexesList(targets); return indexesList.map(indexes => this.getInfoByIndexes(indexes)); } public moveInside(target: HTMLElement | SVGElement | string): Promise<MovedResult> { const info = isString(target) ? this.getInfo(target)! : this.getInfoByElement(target)!; const prevInfo = this.getPrevInfo(info.id!); let moved: ElementInfo[]; if (!prevInfo || isScenaFunction(prevInfo.jsx) || isScenaFunctionElement(prevInfo.jsx)) { moved = []; } else { moved = [info]; } const lastInfo = prevInfo && this.getLastChildInfo(prevInfo.id!); return this.move(moved, prevInfo, lastInfo); } public moveOutside(target: HTMLElement | SVGElement | string): Promise<MovedResult> { const info = isString(target) ? this.getInfo(target)! : this.getInfoByElement(target)!; const parentInfo = this.getInfo(info.scopeId!); const rootInfo = this.getInfo(parentInfo.scopeId!); const moved = rootInfo ? [info] : []; return this.move(moved, rootInfo, parentInfo); } public moves(infos: Array<{ info: ElementInfo, parentInfo: ElementInfo, prevInfo?: ElementInfo }>): Promise<MovedResult> { const container = this.viewportRef.current!; const nextInfos = infos.map(info => { return { ...info, moveMatrix: getOffsetOriginMatrix(info.info.el!, container), }; }) const prevInfos = nextInfos.map(({ info, moveMatrix }) => { return { info, parentInfo: this.getInfo(info.scopeId!), prevInfo: this.getPrevInfo(info.id!), // moveMatrix: mat4.invert(mat4.create(), moveMatrix!), }; }); nextInfos.forEach(({ info, parentInfo, prevInfo }) => { const children = this.getInfo(info.scopeId!).children!; children.splice(children.indexOf(info), 1); const parnetChildren = parentInfo.children!; parnetChildren.splice(prevInfo ? parnetChildren.indexOf(prevInfo) + 1 : 0, 0, info); info.scopeId = parentInfo.id; }); return new Promise(resolve => { const movedInfos = nextInfos.map(({ info }) => info); this.forceUpdate(() => { updateElements(movedInfos); resolve({ prevInfos, nextInfos, }); }) }); } public move(infos: ElementInfo[], parentInfo: ElementInfo, prevInfo?: ElementInfo): Promise<MovedResult> { const sortedInfos = this.getSortedInfos(infos.map(info => info.el!)); return this.moves(sortedInfos.map((info, i) => { return { info, parentInfo, prevInfo: i === 0 ? prevInfo : sortedInfos[i - 1], }; })); } }
the_stack
import { Auth } from 'aws-amplify'; import { IndexTransformer, PrimaryKeyTransformer } from '@aws-amplify/graphql-index-transformer'; import { HasOneTransformer, HasManyTransformer } from '@aws-amplify/graphql-relational-transformer'; import { ModelTransformer } from '@aws-amplify/graphql-model-transformer'; import { AuthTransformer } from '@aws-amplify/graphql-auth-transformer'; import { GraphQLTransform } from '@aws-amplify/graphql-transformer-core'; import { Output } from 'aws-sdk/clients/cloudformation'; import { CloudFormationClient } from '../CloudFormationClient'; import { S3Client } from '../S3Client'; import { cleanupStackAfterTest, deploy } from '../deployNestedStacks'; import { CognitoIdentityServiceProvider as CognitoClient, S3, CognitoIdentity, IAM } from 'aws-sdk'; import moment from 'moment'; import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync'; import { createUserPool, createIdentityPool, createUserPoolClient, configureAmplify, authenticateUser, signupUser, createGroup, addUserToGroup, } from '../cognitoUtils'; import { IAMHelper } from '../IAMHelper'; import { ResourceConstants } from 'graphql-transformer-common'; import gql from 'graphql-tag'; import AWS = require('aws-sdk'); import 'isomorphic-fetch'; // to deal with bug in cognito-identity-js (global as any).fetch = require('node-fetch'); // To overcome of the way of how AmplifyJS picks up currentUserCredentials const anyAWS = AWS as any; if (anyAWS && anyAWS.config && anyAWS.config.credentials) { delete anyAWS.config.credentials; } jest.setTimeout(2000000); const AWS_REGION = 'us-west-2'; function outputValueSelector(key: string) { return (outputs: Output[]) => { const output = outputs.find((o: Output) => o.OutputKey === key); return output ? output.OutputValue : null; }; } const cf = new CloudFormationClient(AWS_REGION); const customS3Client = new S3Client(AWS_REGION); const cognitoClient = new CognitoClient({ apiVersion: '2016-04-19', region: AWS_REGION }); const identityClient = new CognitoIdentity({ apiVersion: '2014-06-30', region: AWS_REGION }); const iamHelper = new IAMHelper(AWS_REGION); const awsS3Client = new S3({ region: AWS_REGION }); // stack info const BUILD_TIMESTAMP = moment().format('YYYYMMDDHHmmss'); const STACK_NAME = `MultiAuthV2TransformerTests-${BUILD_TIMESTAMP}`; const BUCKET_NAME = `appsync-multi-auth-v2-transformer-test-bucket-${BUILD_TIMESTAMP}`; const LOCAL_FS_BUILD_DIR = '/tmp/multi_authv2_transformer_tests/'; const S3_ROOT_DIR_KEY = 'deployments'; const AUTH_ROLE_NAME = `${STACK_NAME}-authRole`; const UNAUTH_ROLE_NAME = `${STACK_NAME}-unauthRole`; const CUSTOM_GROUP_ROLE_NAME = `${STACK_NAME}-customGroupRole`; let USER_POOL_ID: string; let IDENTITY_POOL_ID: string; let GRAPHQL_ENDPOINT: string; let APIKEY_GRAPHQL_CLIENT: AWSAppSyncClient<any> = undefined; let USER_POOL_AUTH_CLIENT: AWSAppSyncClient<any> = undefined; let IAM_CUSTOM_GROUP_CLIENT: AWSAppSyncClient<any> = undefined; let IAM_UNAUTHCLIENT: AWSAppSyncClient<any> = undefined; let IAM_AUTHCLIENT: AWSAppSyncClient<any> = undefined; const CUSTOM_GROUP_NAME = 'customGroup'; const USERNAME1 = 'user1@test.com'; const USERNAME2 = 'user2@test.com'; const TMP_PASSWORD = 'Password123!'; const REAL_PASSWORD = 'Password1234!'; beforeAll(async () => { const validSchema = ` # Allow anyone to access. This is translated into API_KEY. type PostPublic @model @auth(rules: [{ allow: public }]) { id: ID! title: String } # Allow anyone to access. This is translated to IAM with unauth role. type PostPublicIAM @model @auth(rules: [{ allow: public, provider: iam }]) { id: ID! title: String } # Allow anyone with a valid Amazon Cognito UserPools JWT to access. type PostPrivate @model @auth(rules: [{ allow: private }]) { id: ID! title: String } # Allow anyone with a sigv4 signed request with relevant policy to access. type PostPrivateIAM @model @auth(rules: [{ allow: private, provider: iam }]) { id: ID! title: String } # I have a model that is protected by userPools by default. # I want to call createPost from my lambda. type PostOwnerIAM @model @auth( rules: [ # The cognito user pool owner can CRUD. { allow: owner } # A lambda function using IAM can call Mutation.createPost. { allow: private, provider: iam, operations: [create] } ] ) { id: ID! title: String owner: String } type PostSecretFieldIAM @model @auth( rules: [ # The cognito user pool and can CRUD. { allow: private } # iam user can also have CRUD { allow: private, provider: iam } ] ) { id: ID title: String owner: String secret: String @auth( rules: [ # Only a lambda function using IAM can create/read/update this field { allow: private, provider: iam, operations: [create,read,update] } ] ) } type PostConnection @model @auth(rules: [{ allow: public }]) { id: ID! title: String! comments: [CommentConnection] @hasMany } # allow access via cognito user pools type CommentConnection @model @auth(rules: [{ allow: private }]) { id: ID! content: String! post: PostConnection @hasOne } type PostIAMWithKeys @model @auth( rules: [ # API Key can CRUD { allow: public } # IAM can read { allow: public, provider: iam, operations: [read] } ] ) { id: ID! title: String type: String @index( name: "byDate" sortKeyFields: ["date"] queryField: "getPostIAMWithKeysByDate" ) date: AWSDateTime } # This type is for the managed policy slicing, only deployment test in this e2e type TodoWithExtraLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongName @model(subscriptions: null) @auth(rules: [{ allow: private, provider: iam }]) { id: ID! namenamenamenamenamenamenamenamenamenamenamenamenamenamename001: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename002: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename003: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename004: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename005: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename006: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename007: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename008: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename009: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename010: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename011: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename012: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename013: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename014: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename015: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename016: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename017: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename018: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename019: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename020: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename021: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename022: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename023: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename024: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename025: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename026: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename027: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename028: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename029: String! @auth(rules: [{ allow: private, provider: iam }]) namenamenamenamenamenamenamenamenamenamenamenamenamenamename030: String! description: String } `; // create deployment bucket try { await awsS3Client.createBucket({ Bucket: BUCKET_NAME }).promise(); } catch (e) { // fail early if we can't create the bucket expect(e).not.toBeDefined(); } // create userpool const userPoolResponse = await createUserPool(cognitoClient, `UserPool${STACK_NAME}`); USER_POOL_ID = userPoolResponse.UserPool.Id; const userPoolClientResponse = await createUserPoolClient(cognitoClient, USER_POOL_ID, `UserPool${STACK_NAME}`); const userPoolClientId = userPoolClientResponse.UserPoolClient.ClientId; // create auth and unauthroles const roles = await iamHelper.createRoles(AUTH_ROLE_NAME, UNAUTH_ROLE_NAME); // create admin group role const customGroupRole = await iamHelper.createRoleForCognitoGroup(CUSTOM_GROUP_ROLE_NAME); await createGroup(USER_POOL_ID, CUSTOM_GROUP_NAME, customGroupRole.Arn); // create identitypool IDENTITY_POOL_ID = await createIdentityPool(identityClient, `IdentityPool${STACK_NAME}`, { authRoleArn: roles.authRole.Arn, unauthRoleArn: roles.unauthRole.Arn, providerName: `cognito-idp.${AWS_REGION}.amazonaws.com/${USER_POOL_ID}`, clientId: userPoolClientId, useTokenAuth: true, }); const transformer = new GraphQLTransform({ authConfig: { defaultAuthentication: { authenticationType: 'AMAZON_COGNITO_USER_POOLS', }, additionalAuthenticationProviders: [ { authenticationType: 'API_KEY', apiKeyConfig: { description: 'E2E Test API Key', apiKeyExpirationDays: 300, }, }, { authenticationType: 'AWS_IAM', }, ], }, transformers: [ new ModelTransformer(), new IndexTransformer(), new PrimaryKeyTransformer(), new HasOneTransformer(), new HasManyTransformer(), new AuthTransformer({ identityPoolId: IDENTITY_POOL_ID }), ], }); const out = transformer.transform(validSchema); const finishedStack = await deploy( customS3Client, cf, STACK_NAME, out, { AuthCognitoUserPoolId: USER_POOL_ID, authRoleName: roles.authRole.RoleName, unauthRoleName: roles.unauthRole.RoleName }, LOCAL_FS_BUILD_DIR, BUCKET_NAME, S3_ROOT_DIR_KEY, BUILD_TIMESTAMP, ); // Wait for any propagation to avoid random // "The security token included in the request is invalid" errors await new Promise<void>(res => setTimeout(() => res(), 5000)); expect(finishedStack).toBeDefined(); const getApiEndpoint = outputValueSelector(ResourceConstants.OUTPUTS.GraphQLAPIEndpointOutput); const getApiKey = outputValueSelector(ResourceConstants.OUTPUTS.GraphQLAPIApiKeyOutput); GRAPHQL_ENDPOINT = getApiEndpoint(finishedStack.Outputs); const apiKey = getApiKey(finishedStack.Outputs); expect(apiKey).toBeTruthy(); // Verify we have all the details expect(GRAPHQL_ENDPOINT).toBeTruthy(); expect(USER_POOL_ID).toBeTruthy(); expect(userPoolClientId).toBeTruthy(); // Configure Amplify, create users, and sign in configureAmplify(USER_POOL_ID, userPoolClientId, IDENTITY_POOL_ID); const unauthCreds = await Auth.currentCredentials(); IAM_UNAUTHCLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, auth: { type: AUTH_TYPE.AWS_IAM, credentials: { accessKeyId: unauthCreds.accessKeyId, secretAccessKey: unauthCreds.secretAccessKey, sessionToken: unauthCreds.sessionToken, }, }, disableOffline: true, }); await signupUser(USER_POOL_ID, USERNAME1, TMP_PASSWORD); const authRes = await authenticateUser(USERNAME1, TMP_PASSWORD, REAL_PASSWORD); const idToken = authRes.getIdToken().getJwtToken(); USER_POOL_AUTH_CLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, auth: { type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS, jwtToken: () => idToken, }, disableOffline: true, }); await Auth.signIn(USERNAME1, REAL_PASSWORD); const authCreds = await Auth.currentCredentials(); IAM_AUTHCLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, auth: { type: AUTH_TYPE.AWS_IAM, credentials: authCreds, }, disableOffline: true, }); await Auth.signOut(); await signupUser(USER_POOL_ID, USERNAME2, TMP_PASSWORD); await addUserToGroup(CUSTOM_GROUP_NAME, USERNAME2, USER_POOL_ID); await authenticateUser(USERNAME2, TMP_PASSWORD, REAL_PASSWORD); await Auth.signIn(USERNAME2, REAL_PASSWORD); const authCreds2 = await Auth.currentCredentials(); IAM_CUSTOM_GROUP_CLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, auth: { type: AUTH_TYPE.AWS_IAM, credentials: authCreds2, }, disableOffline: true, }); APIKEY_GRAPHQL_CLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, auth: { type: AUTH_TYPE.API_KEY, apiKey: apiKey, }, disableOffline: true, }); }); afterAll(async () => { await cleanupStackAfterTest( BUCKET_NAME, STACK_NAME, cf, { cognitoClient, userPoolId: USER_POOL_ID }, { identityClient, identityPoolId: IDENTITY_POOL_ID }, ); try { await iamHelper.deleteRole(CUSTOM_GROUP_ROLE_NAME); } catch (e) { console.warn(`Error during custom group role cleanup ${e}`); } try { await iamHelper.deleteRole(AUTH_ROLE_NAME); } catch (e) { console.warn(`Error during auth role cleanup ${e}`); } try { await iamHelper.deleteRole(UNAUTH_ROLE_NAME); } catch (e) { console.warn(`Error during unauth role cleanup ${e}`); } }); test("test 'public' authStrategy", async () => { try { const createMutation = gql` mutation { createPostPublic(input: { title: "Hello, World!" }) { id title } } `; const getQuery = gql` query ($id: ID!) { getPostPublic(id: $id) { id title } } `; const response = await APIKEY_GRAPHQL_CLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); expect(response.data.createPostPublic.id).toBeDefined(); expect(response.data.createPostPublic.title).toEqual('Hello, World!'); const postId = response.data.createPostPublic.id; // user authenticated with user pools should fail await expect( USER_POOL_AUTH_CLIENT.query<any>({ query: getQuery, variables: { id: postId }, fetchPolicy: 'no-cache', }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostPublic on type Query'); // user authenticated with iam should fail // should be a 401 error since the unauth role does not have a policy to getPostPublic await expect( IAM_UNAUTHCLIENT.query({ query: getQuery, variables: { id: postId }, fetchPolicy: 'no-cache', }), ).rejects.toThrow('Network error: Response not successful: Received status code 401'); } catch (err) { expect(err).not.toBeDefined(); } }); test(`Test 'public' provider: 'iam' authStrategy`, async () => { try { const createMutation = gql` mutation { createPostPublicIAM(input: { title: "Hello, World!" }) { id title } } `; const getQuery = gql` query ($id: ID!) { getPostPublicIAM(id: $id) { id title } } `; const response = await IAM_UNAUTHCLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); expect(response.data.createPostPublicIAM.id).toBeDefined(); expect(response.data.createPostPublicIAM.title).toEqual('Hello, World!'); const postId = response.data.createPostPublicIAM.id; // Authenticate User Pools user must fail await expect( USER_POOL_AUTH_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostPublicIAM on type Query'); // API Key must fail await expect( APIKEY_GRAPHQL_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostPublicIAM on type Query'); } catch (e) { expect(e).not.toBeDefined(); } }); test(`Test 'private' authStrategy`, async () => { try { const createMutation = gql` mutation { createPostPrivate(input: { title: "Hello, World!" }) { id title } } `; const getQuery = gql` query ($id: ID!) { getPostPrivate(id: $id) { id title } } `; const response = await USER_POOL_AUTH_CLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); expect(response.data.createPostPrivate.id).toBeDefined(); expect(response.data.createPostPrivate.title).toEqual('Hello, World!'); const postId = response.data.createPostPrivate.id; // Authenticate API Key fail await expect( APIKEY_GRAPHQL_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostPrivate on type Query'); // IAM with unauth role must fail await expect( IAM_UNAUTHCLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrowError('Network error: Response not successful: Received status code 401'); } catch (e) { expect(e).not.toBeDefined(); } }); test(`Test only allow private iam arn`, async () => { try { const createMutation = gql` mutation { createPostPrivateIAM(input: { title: "Hello, World!" }) { id title } } `; const getQuery = gql` query ($id: ID!) { getPostPrivateIAM(id: $id) { id title } } `; const response = await IAM_AUTHCLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); expect(response.data.createPostPrivateIAM.id).toBeDefined(); expect(response.data.createPostPrivateIAM.title).toEqual('Hello, World!'); const postId = response.data.createPostPrivateIAM.id; // Authenticate User Pools user must fail await expect( USER_POOL_AUTH_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostPrivateIAM on type Query'); // API Key must fail await expect( APIKEY_GRAPHQL_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostPrivateIAM on type Query'); // public iam user must fail await expect( IAM_UNAUTHCLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('Network error: Response not successful: Received status code 401'); // we expect the custom group client to fail even if their signed in they'll still recieve a 401 // because the attached role does not have a policy to access the api await expect( IAM_CUSTOM_GROUP_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postId, }, }), ).rejects.toThrow('Network error: Response not successful: Received status code 401'); } catch (e) { console.error(e); expect(e).not.toBeDefined(); } }); test(`Test 'private' provider: 'iam' authStrategy`, async () => { // This test reuses the unauth role, but any IAM credentials would work // in real world scenarios, we've to see if provider override works. // - Create UserPool - Verify owner // - Create IAM - Verify owner (blank) // - Get UserPool owner - Verify success // - Get UserPool non-owner - Verify deny // - Get IAM - Verify deny // - Get API Key - Verify deny try { const createMutation = gql` mutation { createPostOwnerIAM(input: { title: "Hello, World!" }) { id title owner } } `; const getQuery = gql` query ($id: ID!) { getPostOwnerIAM(id: $id) { id title owner } } `; const response = await USER_POOL_AUTH_CLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); expect(response.data.createPostOwnerIAM.id).toBeDefined(); expect(response.data.createPostOwnerIAM.title).toEqual('Hello, World!'); expect(response.data.createPostOwnerIAM.owner).toEqual(USERNAME1); const postIdOwner = response.data.createPostOwnerIAM.id; const responseIAM = await IAM_AUTHCLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); expect(responseIAM.data.createPostOwnerIAM.id).toBeDefined(); expect(responseIAM.data.createPostOwnerIAM.title).toEqual('Hello, World!'); expect(responseIAM.data.createPostOwnerIAM.owner).toBeNull(); const postIdIAM = responseIAM.data.createPostOwnerIAM.id; const responseGetUserPool = await USER_POOL_AUTH_CLIENT.query<any>({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postIdOwner, }, }); expect(responseGetUserPool.data.getPostOwnerIAM.id).toBeDefined(); expect(responseGetUserPool.data.getPostOwnerIAM.title).toEqual('Hello, World!'); expect(responseGetUserPool.data.getPostOwnerIAM.owner).toEqual(USERNAME1); await expect( USER_POOL_AUTH_CLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postIdIAM }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostOwnerIAM on type Query'); await expect( IAM_UNAUTHCLIENT.query({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postIdOwner }, }), ).rejects.toThrow('Network error: Response not successful: Received status code 401'); await expect( APIKEY_GRAPHQL_CLIENT.query({ query: getQuery, variables: { id: postIdOwner }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access getPostOwnerIAM on type Query'); } catch (e) { console.error(e); expect(e).not.toBeDefined(); } }); describe(`Test IAM protected field operations`, () => { // This test reuses the unauth role, but any IAM credentials would work // in real world scenarios, we've to see if provider override works. const createMutation = gql` mutation { createPostSecretFieldIAM(input: { title: "Hello, World!" }) { id title } } `; const createMutationWithSecret = gql` mutation { createPostSecretFieldIAM(input: { title: "Hello, World!", secret: "42" }) { id title secret } } `; const getQuery = gql` query ($id: ID!) { getPostSecretFieldIAM(id: $id) { id title } } `; const getQueryWithSecret = gql` query ($id: ID!) { getPostSecretFieldIAM(id: $id) { id title secret } } `; let postIdNoSecret = ''; let postIdSecret = ''; beforeAll(async () => { try { // - Create UserPool - no secret - Success const response = await USER_POOL_AUTH_CLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); postIdNoSecret = response.data.createPostSecretFieldIAM.id; // - Create IAM - with secret - Success const responseIAMSecret = await IAM_AUTHCLIENT.mutate<any>({ mutation: createMutationWithSecret, fetchPolicy: 'no-cache', }); postIdSecret = responseIAMSecret.data.createPostSecretFieldIAM.id; } catch (e) { expect(e).not.toBeDefined(); } }); it('Get UserPool - Succeed', async () => { const responseGetUserPool = await USER_POOL_AUTH_CLIENT.query<any>({ query: getQuery, fetchPolicy: 'no-cache', variables: { id: postIdNoSecret, }, }); expect(responseGetUserPool.data.getPostSecretFieldIAM.id).toBeDefined(); expect(responseGetUserPool.data.getPostSecretFieldIAM.title).toEqual('Hello, World!'); }); it('Get UserPool with secret - Fail', async () => { expect.assertions(1); await expect( USER_POOL_AUTH_CLIENT.query({ query: getQueryWithSecret, fetchPolicy: 'no-cache', variables: { id: postIdSecret }, }), ).rejects.toThrow('GraphQL error: Not Authorized to access secret on type String'); }); }); describe(`IAM Tests`, () => { const createMutation = gql` mutation { createPostIAMWithKeys(input: { title: "Hello, World!", type: "Post", date: "2019-01-01T00:00:00Z" }) { id title type date } } `; const getPostIAMWithKeysByDate = gql` query { getPostIAMWithKeysByDate(type: "Post") { items { id title type date } } } `; let postId = ''; beforeAll(async () => { try { // - Create API Key - Success const response = await APIKEY_GRAPHQL_CLIENT.mutate<any>({ mutation: createMutation, fetchPolicy: 'no-cache', }); postId = response.data.createPostIAMWithKeys.id; } catch (e) { expect(e).not.toBeDefined(); } }); it('Execute @key query - Succeed', async () => { const response = await IAM_UNAUTHCLIENT.query<any>({ query: getPostIAMWithKeysByDate, fetchPolicy: 'no-cache', }); expect(response.data.getPostIAMWithKeysByDate.items).toBeDefined(); expect(response.data.getPostIAMWithKeysByDate.items.length).toEqual(1); const post = response.data.getPostIAMWithKeysByDate.items[0]; expect(post.id).toEqual(postId); expect(post.title).toEqual('Hello, World!'); expect(post.type).toEqual('Post'); expect(post.date).toEqual('2019-01-01T00:00:00Z'); }); }); describe(`relational tests with @auth on type`, () => { const createPostMutation = gql` mutation { createPostConnection(input: { title: "Hello, World!" }) { id title } } `; const createCommentMutation = gql` mutation ($postId: ID!) { createCommentConnection(input: { content: "Comment", commentConnectionPostId: $postId }) { id content } } `; const getPostQuery = gql` query ($postId: ID!) { getPostConnection(id: $postId) { id title } } `; const getPostQueryWithComments = gql` query ($postId: ID!) { getPostConnection(id: $postId) { id title comments { items { id content } } } } `; const getCommentQuery = gql` query ($commentId: ID!) { getCommentConnection(id: $commentId) { id content } } `; const getCommentWithPostQuery = gql` query ($commentId: ID!) { getCommentConnection(id: $commentId) { id content post { id title } } } `; let postId = ''; let commentId = ''; beforeAll(async () => { try { // Add a comment with ApiKey - Succeed const response = await APIKEY_GRAPHQL_CLIENT.mutate<any>({ mutation: createPostMutation, fetchPolicy: 'no-cache', }); postId = response.data.createPostConnection.id; // Add a comment with UserPool - Succeed const commentResponse = await USER_POOL_AUTH_CLIENT.mutate<any>({ mutation: createCommentMutation, fetchPolicy: 'no-cache', variables: { postId, }, }); commentId = commentResponse.data.createCommentConnection.id; } catch (e) { expect(e).not.toBeDefined(); } }); it('Create a Post with UserPool - Fail', async () => { expect.assertions(1); await expect( USER_POOL_AUTH_CLIENT.mutate<any>({ mutation: createPostMutation, fetchPolicy: 'no-cache', }), ).rejects.toThrow('GraphQL error: Not Authorized to access createPostConnection on type Mutation'); }); it('Add a comment with ApiKey - Fail', async () => { expect.assertions(1); await expect( APIKEY_GRAPHQL_CLIENT.mutate<any>({ mutation: createCommentMutation, fetchPolicy: 'no-cache', variables: { postId, }, }), ).rejects.toThrow('Not Authorized to access createCommentConnection on type Mutation'); }); it('Get Post with ApiKey - Succeed', async () => { const responseGetPost = await APIKEY_GRAPHQL_CLIENT.query<any>({ query: getPostQuery, fetchPolicy: 'no-cache', variables: { postId, }, }); expect(responseGetPost.data.getPostConnection.id).toEqual(postId); expect(responseGetPost.data.getPostConnection.title).toEqual('Hello, World!'); }); it('Get Post with UserPool - Fail', async () => { expect.assertions(1); await expect( USER_POOL_AUTH_CLIENT.query<any>({ query: getPostQuery, fetchPolicy: 'no-cache', variables: { postId, }, }), ).rejects.toThrow('Not Authorized to access getPostConnection on type Query'); }); it('Get Comment with UserPool - Succeed', async () => { const responseGetComment = await USER_POOL_AUTH_CLIENT.query<any>({ query: getCommentQuery, fetchPolicy: 'no-cache', variables: { commentId, }, }); expect(responseGetComment.data.getCommentConnection.id).toEqual(commentId); expect(responseGetComment.data.getCommentConnection.content).toEqual('Comment'); }); it('Get Comment with ApiKey - Fail', async () => { expect.assertions(1); await expect( APIKEY_GRAPHQL_CLIENT.query<any>({ query: getCommentQuery, fetchPolicy: 'no-cache', variables: { commentId, }, }), ).rejects.toThrow('Not Authorized to access getCommentConnection on type Query'); }); });
the_stack
'use strict'; /** * This is a very simple HTML to JSX converter. It turns out that browsers * have good HTML parsers (who would have thought?) so we utilise this by * inserting the HTML into a temporary DOM node, and then do a breadth-first * traversal of the resulting DOM tree. */ // https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType var NODE_TYPE = { ELEMENT: 1, TEXT: 3, COMMENT: 8 }; var ATTRIBUTE_MAPPING = { 'for': 'htmlFor', 'class': 'className' }; var ELEMENT_ATTRIBUTE_MAPPING = { 'input': { 'checked': 'defaultChecked', 'value': 'defaultValue' } }; var HTMLDOMPropertyConfig = require('react-dom/lib/HTMLDOMPropertyConfig'); // Populate property map with ReactJS's attribute and property mappings // TODO handle/use .Properties value eg: MUST_USE_PROPERTY is not HTML attr for (var propname in HTMLDOMPropertyConfig.Properties) { if (!HTMLDOMPropertyConfig.Properties.hasOwnProperty(propname)) { continue; } var mapFrom = HTMLDOMPropertyConfig.DOMAttributeNames[propname] || propname.toLowerCase(); if (!ATTRIBUTE_MAPPING[mapFrom]) ATTRIBUTE_MAPPING[mapFrom] = propname; } /** * Repeats a string a certain number of times. * Also: the future is bright and consists of native string repetition: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat * * @param {string} string String to repeat * @param {number} times Number of times to repeat string. Integer. * @see http://jsperf.com/string-repeater/2 */ function repeatString(string, times) { if (times === 1) { return string; } if (times < 0) { throw new Error(); } var repeated = ''; while (times) { if (times & 1) { repeated += string; } if (times >>= 1) { string += string; } } return repeated; } /** * Determine if the string ends with the specified substring. * * @param {string} haystack String to search in * @param {string} needle String to search for * @return {boolean} */ function endsWith(haystack, needle) { return haystack.slice(-needle.length) === needle; } /** * Trim the specified substring off the string. If the string does not end * with the specified substring, this is a no-op. * * @param {string} haystack String to search in * @param {string} needle String to search for * @return {string} */ function trimEnd(haystack, needle) { return endsWith(haystack, needle) ? haystack.slice(0, -needle.length) : haystack; } /** * Convert a hyphenated string to camelCase. */ function hyphenToCamelCase(string) { return string.replace(/-(.)/g, function(match, chr) { return chr.toUpperCase(); }); } /** * Determines if the specified string consists entirely of whitespace. */ function isEmpty(string) { return !/[^\s]/.test(string); } /** * Determines if the CSS value can be converted from a * 'px' suffixed string to a numeric value * * @param {string} value CSS property value * @return {boolean} */ function isConvertiblePixelValue(value) { return /^\d+px$/.test(value); } /** * Determines if the specified string consists entirely of numeric characters. */ function isNumeric(input) { return input !== undefined && input !== null && (typeof input === 'number' || parseInt(input, 10) == input); } const createElement = function(tag) { return document.createElement(tag); }; var tempEl = createElement('div'); /** * Escapes special characters by converting them to their escaped equivalent * (eg. "<" to "&lt;"). Only escapes characters that absolutely must be escaped. * * @param {string} value * @return {string} */ function escapeSpecialChars(value) { // Uses this One Weird Trick to escape text - Raw text inserted as textContent // will have its escaped version in innerHTML. tempEl.textContent = value; return tempEl.innerHTML; } export type Config = { createClass?: boolean; outputClassName?: string; /** as a string e.g. ' ' or '\t' */ indent?: string; } export class HTMLtoJSX { private config: Config; private output: string; private level: number; private _inPreTag: boolean; constructor(config:Config) { this.config = config || {}; if (this.config.createClass === undefined) { this.config.createClass = true; } if (!this.config.indent) { this.config.indent = ' '; } } /** * Reset the internal state of the converter */ reset = () => { this.output = ''; this.level = 0; this._inPreTag = false; } /** * Main entry point to the converter. Given the specified HTML, returns a * JSX object representing it. * @param {string} html HTML to convert * @return {string} JSX */ convert = (html) => { this.reset(); var containerEl = createElement('div'); containerEl.innerHTML = '\n' + this._cleanInput(html) + '\n'; if (this.config.createClass) { if (this.config.outputClassName) { this.output = 'var ' + this.config.outputClassName + ' = React.createClass({\n'; } else { this.output = 'React.createClass({\n'; } this.output += this.config.indent + 'render: function() {' + "\n"; this.output += this.config.indent + this.config.indent + 'return (\n'; } if (this._onlyOneTopLevel(containerEl)) { // Only one top-level element, the component can return it directly // No need to actually visit the container element this._traverse(containerEl); } else { // More than one top-level element, need to wrap the whole thing in a // container. this.output += this.config.indent + this.config.indent + this.config.indent; this.level++; this._visit(containerEl); } this.output = this.output.trim() + '\n'; if (this.config.createClass) { this.output += this.config.indent + this.config.indent + ');\n'; this.output += this.config.indent + '}\n'; this.output += '});'; } return this.output; } /** * Cleans up the specified HTML so it's in a format acceptable for * converting. * * @param {string} html HTML to clean * @return {string} Cleaned HTML */ _cleanInput = (html) => { // Remove unnecessary whitespace html = html.trim(); // Ugly method to strip script tags. They can wreak havoc on the DOM nodes // so let's not even put them in the DOM. html = html.replace(/<script([\s\S]*?)<\/script>/g, ''); return html; } /** * Determines if there's only one top-level node in the DOM tree. That is, * all the HTML is wrapped by a single HTML tag. * * @param {DOMElement} containerEl Container element * @return {boolean} */ _onlyOneTopLevel = (containerEl) => { // Only a single child element if ( containerEl.childNodes.length === 1 && containerEl.childNodes[0].nodeType === NODE_TYPE.ELEMENT ) { return true; } // Only one element, and all other children are whitespace var foundElement = false; for (var i = 0, count = containerEl.childNodes.length; i < count; i++) { var child = containerEl.childNodes[i]; if (child.nodeType === NODE_TYPE.ELEMENT) { if (foundElement) { // Encountered an element after already encountering another one // Therefore, more than one element at root level return false; } else { foundElement = true; } } else if (child.nodeType === NODE_TYPE.TEXT && !isEmpty(child.textContent)) { // Contains text content return false; } } return true; } /** * Gets a newline followed by the correct indentation for the current * nesting level * * @return {string} */ _getIndentedNewline = () => { return '\n' + repeatString(this.config.indent, this.level + 2); } /** * Handles processing the specified node * * @param {Node} node */ _visit = (node) => { this._beginVisit(node); this._traverse(node); this._endVisit(node); } /** * Traverses all the children of the specified node * * @param {Node} node */ _traverse = (node) => { this.level++; for (var i = 0, count = node.childNodes.length; i < count; i++) { this._visit(node.childNodes[i]); } this.level--; } /** * Handle pre-visit behaviour for the specified node. * * @param {Node} node */ _beginVisit = (node) => { switch (node.nodeType) { case NODE_TYPE.ELEMENT: this._beginVisitElement(node); break; case NODE_TYPE.TEXT: this._visitText(node); break; case NODE_TYPE.COMMENT: this._visitComment(node); break; default: console.warn('Unrecognised node type: ' + node.nodeType); } } /** * Handles post-visit behaviour for the specified node. * * @param {Node} node */ _endVisit = (node) => { switch (node.nodeType) { case NODE_TYPE.ELEMENT: this._endVisitElement(node); break; // No ending tags required for these types case NODE_TYPE.TEXT: case NODE_TYPE.COMMENT: break; } } /** * Handles pre-visit behaviour for the specified element node * * @param {DOMElement} node */ _beginVisitElement = (node) => { var tagName = node.tagName.toLowerCase(); var attributes = []; for (var i = 0, count = node.attributes.length; i < count; i++) { attributes.push(this._getElementAttribute(node, node.attributes[i])); } if (tagName === 'textarea') { // Hax: textareas need their inner text moved to a "defaultValue" attribute. attributes.push('defaultValue={' + JSON.stringify(node.value) + '}'); } if (tagName === 'style') { // Hax: style tag contents need to be dangerously set due to liberal curly brace usage attributes.push('dangerouslySetInnerHTML={{__html: ' + JSON.stringify(node.textContent) + ' }}'); } if (tagName === 'pre') { this._inPreTag = true; } this.output += '<' + tagName; if (attributes.length > 0) { this.output += ' ' + attributes.join(' '); } if (!this._isSelfClosing(node)) { this.output += '>'; } } /** * Handles post-visit behaviour for the specified element node * * @param {Node} node */ _endVisitElement = (node) => { var tagName = node.tagName.toLowerCase(); // De-indent a bit // TODO: It's inefficient to do it this way :/ this.output = trimEnd(this.output, this.config.indent); if (this._isSelfClosing(node)) { this.output += ' />'; } else { this.output += '</' + node.tagName.toLowerCase() + '>'; } if (tagName === 'pre') { this._inPreTag = false; } } /** * Determines if this element node should be rendered as a self-closing * tag. * * @param {Node} node * @return {boolean} */ _isSelfClosing = (node) => { // If it has children, it's not self-closing // Exception: All children of a textarea are moved to a "defaultValue" attribute, style attributes are dangerously set. return !node.firstChild || node.tagName.toLowerCase() === 'textarea' || node.tagName.toLowerCase() === 'style'; } /** * Handles processing of the specified text node * * @param {TextNode} node */ _visitText = (node) => { var parentTag = node.parentNode && node.parentNode.tagName.toLowerCase(); if (parentTag === 'textarea' || parentTag === 'style') { // Ignore text content of textareas and styles, as it will have already been moved // to a "defaultValue" attribute and "dangerouslySetInnerHTML" attribute respectively. return; } var text = escapeSpecialChars(node.textContent) if (this._inPreTag) { // If this text is contained within a <pre>, we need to ensure the JSX // whitespace coalescing rules don't eat the whitespace. This means // wrapping newlines and sequences of two or more spaces in variables. text = text .replace(/\r/g, '') .replace(/( {2,}|\n|\t|\{|\})/g, function(whitespace) { return '{' + JSON.stringify(whitespace) + '}'; }); } else { // If there's a newline in the text, adjust the indent level if (text.indexOf('\n') > -1) { text = text.replace(/\n\s*/g, this._getIndentedNewline()); } } this.output += text; } /** * Handles processing of the specified text node * * @param {Text} node */ _visitComment = (node) => { this.output += '{/*' + node.textContent.replace('*/', '* /') + '*/}'; } /** * Gets a JSX formatted version of the specified attribute from the node * * @param {DOMElement} node * @param {object} attribute * @return {string} */ _getElementAttribute = (node, attribute) => { switch (attribute.name) { case 'style': return this._getStyleAttribute(attribute.value); default: var tagName = node.tagName.toLowerCase(); var name = (ELEMENT_ATTRIBUTE_MAPPING[tagName] && ELEMENT_ATTRIBUTE_MAPPING[tagName][attribute.name]) || ATTRIBUTE_MAPPING[attribute.name] || attribute.name; var result = name; // Numeric values should be output as {123} not "123" if (isNumeric(attribute.value)) { result += '={' + attribute.value + '}'; } else if (attribute.value.length > 0) { result += '="' + attribute.value.replace('"', '&quot;') + '"'; } return result; } } /** * Gets a JSX formatted version of the specified element styles * * @param {string} styles * @return {string} */ _getStyleAttribute = (styles) => { var jsxStyles = new StyleParser(styles).toJSXString(); return 'style={{' + jsxStyles + '}}'; } }; /** * Handles parsing of inline styles */ export class StyleParser { styles = {}; /** @param {string} rawStyle Raw style attribute */ constructor(rawStyle) { this.parse(rawStyle); }; /** * Parse the specified inline style attribute value * @param {string} rawStyle Raw style attribute */ parse = (rawStyle) => { rawStyle.split(';').forEach(function(style) { style = style.trim(); var firstColon = style.indexOf(':'); var key = style.substr(0, firstColon); var value = style.substr(firstColon + 1).trim(); if (key !== '') { // Style key should be case insensitive key = key.toLowerCase(); this.styles[key] = value; } }, this); } /** * Convert the style information represented by this parser into a JSX * string * * @return {string} */ toJSXString = () => { var output = []; for (var key in this.styles) { if (!this.styles.hasOwnProperty(key)) { continue; } output.push(this.toJSXKey(key) + ': ' + this.toJSXValue(this.styles[key])); } return output.join(', '); } /** * Convert the CSS style key to a JSX style key * * @param {string} key CSS style key * @return {string} JSX style key */ private toJSXKey = (key) => { // Don't capitalize -ms- prefix if(/^-ms-/.test(key)) { key = key.substr(1); } return hyphenToCamelCase(key); } /** * Convert the CSS style value to a JSX style value * * @param {string} value CSS style value * @return {string} JSX style value */ private toJSXValue = (value) => { if (isNumeric(value)) { // If numeric, no quotes return value; } else if (isConvertiblePixelValue(value)) { // "500px" -> 500 return trimEnd(value, 'px'); } else { // Probably a string, wrap it in quotes return '\'' + value.replace(/'/g, '"') + '\''; } } }
the_stack
import { BaseResource } from 'ms-rest-azure'; import { CloudError } from 'ms-rest-azure'; import * as moment from 'moment'; export { BaseResource } from 'ms-rest-azure'; export { CloudError } from 'ms-rest-azure'; /** * @class * Initializes a new instance of the StorageBlobCreatedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.Storage.BlobCreated event. * * @member {string} [api] The name of the API/operation that triggered this * event. * @member {string} [clientRequestId] A request id provided by the client of * the storage API operation that triggered this event. * @member {string} [requestId] The request id generated by the Storage service * for the storage API operation that triggered this event. * @member {string} [eTag] The etag of the object at the time this event was * triggered. * @member {string} [contentType] The content type of the blob. This is the * same as what would be returned in the Content-Type header from the blob. * @member {number} [contentLength] The size of the blob in bytes. This is the * same as what would be returned in the Content-Length header from the blob. * @member {string} [blobType] The type of blob. * @member {string} [url] The path to the blob. * @member {string} [sequencer] An opaque string value representing the logical * sequence of events for any particular blob name. Users can use standard * string comparison to understand the relative sequence of two events on the * same blob name. * @member {object} [storageDiagnostics] For service use only. Diagnostic data * occasionally included by the Azure Storage service. This property should be * ignored by event consumers. */ export interface StorageBlobCreatedEventData { api?: string; clientRequestId?: string; requestId?: string; eTag?: string; contentType?: string; contentLength?: number; blobType?: string; url?: string; sequencer?: string; storageDiagnostics?: any; } /** * @class * Initializes a new instance of the StorageBlobDeletedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.Storage.BlobDeleted event. * * @member {string} [api] The name of the API/operation that triggered this * event. * @member {string} [clientRequestId] A request id provided by the client of * the storage API operation that triggered this event. * @member {string} [requestId] The request id generated by the Storage service * for the storage API operation that triggered this event. * @member {string} [contentType] The content type of the blob. This is the * same as what would be returned in the Content-Type header from the blob. * @member {string} [blobType] The type of blob. * @member {string} [url] The path to the blob. * @member {string} [sequencer] An opaque string value representing the logical * sequence of events for any particular blob name. Users can use standard * string comparison to understand the relative sequence of two events on the * same blob name. * @member {object} [storageDiagnostics] For service use only. Diagnostic data * occasionally included by the Azure Storage service. This property should be * ignored by event consumers. */ export interface StorageBlobDeletedEventData { api?: string; clientRequestId?: string; requestId?: string; contentType?: string; blobType?: string; url?: string; sequencer?: string; storageDiagnostics?: any; } /** * @class * Initializes a new instance of the EventHubCaptureFileCreatedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.EventHub.CaptureFileCreated event. * * @member {string} [fileurl] The path to the capture file. * @member {string} [fileType] The file type of the capture file. * @member {string} [partitionId] The shard ID. * @member {number} [sizeInBytes] The file size. * @member {number} [eventCount] The number of events in the file. * @member {number} [firstSequenceNumber] The smallest sequence number from the * queue. * @member {number} [lastSequenceNumber] The last sequence number from the * queue. * @member {date} [firstEnqueueTime] The first time from the queue. * @member {date} [lastEnqueueTime] The last time from the queue. */ export interface EventHubCaptureFileCreatedEventData { fileurl?: string; fileType?: string; partitionId?: string; sizeInBytes?: number; eventCount?: number; firstSequenceNumber?: number; lastSequenceNumber?: number; firstEnqueueTime?: Date; lastEnqueueTime?: Date; } /** * @class * Initializes a new instance of the ResourceWriteSuccessData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceWriteSuccess event. This is raised when a * resource create or update operation succeeds. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceWriteSuccessData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceWriteFailureData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceWriteFailure event. This is raised when a * resource create or update operation fails. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceWriteFailureData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceWriteCancelData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceWriteCancel event. This is raised when a * resource create or update operation is canceled. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceWriteCancelData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceDeleteSuccessData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceDeleteSuccess event. This is raised when a * resource delete operation succeeds. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceDeleteSuccessData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceDeleteFailureData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceDeleteFailure event. This is raised when a * resource delete operation fails. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceDeleteFailureData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceDeleteCancelData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.Resources.ResourceDeleteCancel event. This is raised when a * resource delete operation is canceled. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceDeleteCancelData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceActionSuccessData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceActionSuccess event. This is raised when a * resource action operation succeeds. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceActionSuccessData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceActionFailureData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Resources.ResourceActionFailure event. This is raised when a * resource action operation fails. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceActionFailureData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the ResourceActionCancelData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.Resources.ResourceActionCancel event. This is raised when a * resource action operation is canceled. * * @member {string} [tenantId] The tenant ID of the resource. * @member {string} [subscriptionId] The subscription ID of the resource. * @member {string} [resourceGroup] The resource group of the resource. * @member {string} [resourceProvider] The resource provider performing the * operation. * @member {string} [resourceUri] The URI of the resource in the operation. * @member {string} [operationName] The operation that was performed. * @member {string} [status] The status of the operation. * @member {string} [authorization] The requested authorization for the * operation. * @member {string} [claims] The properties of the claims. * @member {string} [correlationId] An operation ID used for troubleshooting. * @member {string} [httpRequest] The details of the operation. */ export interface ResourceActionCancelData { tenantId?: string; subscriptionId?: string; resourceGroup?: string; resourceProvider?: string; resourceUri?: string; operationName?: string; status?: string; authorization?: string; claims?: string; correlationId?: string; httpRequest?: string; } /** * @class * Initializes a new instance of the EventGridEvent class. * @constructor * Properties of an event published to an Event Grid topic. * * @member {string} id An unique identifier for the event. * @member {string} [topic] The resource path of the event source. * @member {string} subject A resource path relative to the topic path. * @member {object} data Event data specific to the event type. * @member {string} eventType The type of the event that occurred. * @member {date} eventTime The time (in UTC) the event was generated. * @member {string} [metadataVersion] The schema version of the event metadata. * @member {string} dataVersion The schema version of the data object. */ export interface EventGridEvent { id: string; topic?: string; subject: string; data: any; eventType: string; eventTime: Date; readonly metadataVersion?: string; dataVersion: string; } /** * @class * Initializes a new instance of the SubscriptionValidationEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.EventGrid.SubscriptionValidationEvent. * * @member {string} [validationCode] The validation code sent by Azure Event * Grid to validate an event subscription. To complete the validation * handshake, the subscriber must either respond with this validation code as * part of the validation response, or perform a GET request on the * validationUrl (available starting version 2018-05-01-preview). * @member {string} [validationUrl] The validation URL sent by Azure Event Grid * (available starting version 2018-05-01-preview). To complete the validation * handshake, the subscriber must either respond with the validationCode as * part of the validation response, or perform a GET request on the * validationUrl (available starting version 2018-05-01-preview). */ export interface SubscriptionValidationEventData { readonly validationCode?: string; readonly validationUrl?: string; } /** * @class * Initializes a new instance of the SubscriptionValidationResponse class. * @constructor * To complete an event subscription validation handshake, a subscriber can use * either the validationCode or the validationUrl received in a * SubscriptionValidationEvent. When the validationCode is used, the * SubscriptionValidationResponse can be used to build the response. * * @member {string} [validationResponse] The validation response sent by the * subscriber to Azure Event Grid to complete the validation of an event * subscription. */ export interface SubscriptionValidationResponse { validationResponse?: string; } /** * @class * Initializes a new instance of the SubscriptionDeletedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.EventGrid.SubscriptionDeletedEvent. * * @member {string} [eventSubscriptionId] The Azure resource ID of the deleted * event subscription. */ export interface SubscriptionDeletedEventData { readonly eventSubscriptionId?: string; } /** * @class * Initializes a new instance of the DeviceLifeCycleEventProperties class. * @constructor * Schema of the Data property of an EventGridEvent for a device life cycle * event (DeviceCreated, DeviceDeleted). * * @member {string} [deviceId] The unique identifier of the device. This * case-sensitive string can be up to 128 characters long, and supports ASCII * 7-bit alphanumeric characters plus the following special characters: - : . + * % _ &#35; * ? ! ( ) , = @ ; $ '. * @member {string} [hubName] Name of the IoT Hub where the device was created * or deleted. * @member {object} [twin] Information about the device twin, which is the * cloud representation of application device metadata. * @member {string} [twin.authenticationType] Authentication type used for this * device: either SAS, SelfSigned, or CertificateAuthority. * @member {number} [twin.cloudToDeviceMessageCount] Count of cloud to device * messages sent to this device. * @member {string} [twin.connectionState] Whether the device is connected or * disconnected. * @member {string} [twin.deviceId] The unique identifier of the device twin. * @member {string} [twin.etag] A piece of information that describes the * content of the device twin. Each etag is guaranteed to be unique per device * twin. * @member {string} [twin.lastActivityTime] The ISO8601 timestamp of the last * activity. * @member {object} [twin.properties] Properties JSON element. * @member {object} [twin.properties.desired] A portion of the properties that * can be written only by the application back-end, and read by the device. * @member {object} [twin.properties.desired.metadata] Metadata information for * the properties JSON document. * @member {string} [twin.properties.desired.metadata.lastUpdated] The ISO8601 * timestamp of the last time the properties were updated. * @member {number} [twin.properties.desired.version] Version of device twin * properties. * @member {object} [twin.properties.reported] A portion of the properties that * can be written only by the device, and read by the application back-end. * @member {object} [twin.properties.reported.metadata] Metadata information * for the properties JSON document. * @member {string} [twin.properties.reported.metadata.lastUpdated] The ISO8601 * timestamp of the last time the properties were updated. * @member {number} [twin.properties.reported.version] Version of device twin * properties. * @member {string} [twin.status] Whether the device twin is enabled or * disabled. * @member {string} [twin.statusUpdateTime] The ISO8601 timestamp of the last * device twin status update. * @member {number} [twin.version] An integer that is incremented by one each * time the device twin is updated. * @member {object} [twin.x509Thumbprint] The thumbprint is a unique value for * the x509 certificate, commonly used to find a particular certificate in a * certificate store. The thumbprint is dynamically generated using the SHA1 * algorithm, and does not physically exist in the certificate. * @member {string} [twin.x509Thumbprint.primaryThumbprint] Primary thumbprint * for the x509 certificate. * @member {string} [twin.x509Thumbprint.secondaryThumbprint] Secondary * thumbprint for the x509 certificate. */ export interface DeviceLifeCycleEventProperties { deviceId?: string; hubName?: string; twin?: DeviceTwinInfo; } /** * @class * Initializes a new instance of the IotHubDeviceCreatedEventData class. * @constructor * Event data for Microsoft.Devices.DeviceCreated event. * */ export interface IotHubDeviceCreatedEventData extends DeviceLifeCycleEventProperties { } /** * @class * Initializes a new instance of the IotHubDeviceDeletedEventData class. * @constructor * Event data for Microsoft.Devices.DeviceDeleted event. * */ export interface IotHubDeviceDeletedEventData extends DeviceLifeCycleEventProperties { } /** * @class * Initializes a new instance of the DeviceConnectionStateEventProperties class. * @constructor * Schema of the Data property of an EventGridEvent for a device connection * state event (DeviceConnected, DeviceDisconnected). * * @member {string} [deviceId] The unique identifier of the device. This * case-sensitive string can be up to 128 characters long, and supports ASCII * 7-bit alphanumeric characters plus the following special characters: - : . + * % _ &#35; * ? ! ( ) , = @ ; $ '. * @member {string} [moduleId] The unique identifier of the module. This * case-sensitive string can be up to 128 characters long, and supports ASCII * 7-bit alphanumeric characters plus the following special characters: - : . + * % _ &#35; * ? ! ( ) , = @ ; $ '. * @member {string} [hubName] Name of the IoT Hub where the device was created * or deleted. * @member {object} [deviceConnectionStateEventInfo] Information about the * device connection state event. * @member {string} [deviceConnectionStateEventInfo.sequenceNumber] Sequence * number is string representation of a hexadecimal number. string compare can * be used to identify the larger number because both in ASCII and HEX numbers * come after alphabets. If you are converting the string to hex, then the * number is a 256 bit number. */ export interface DeviceConnectionStateEventProperties { deviceId?: string; moduleId?: string; hubName?: string; deviceConnectionStateEventInfo?: DeviceConnectionStateEventInfo; } /** * @class * Initializes a new instance of the IotHubDeviceConnectedEventData class. * @constructor * Event data for Microsoft.Devices.DeviceConnected event. * */ export interface IotHubDeviceConnectedEventData extends DeviceConnectionStateEventProperties { } /** * @class * Initializes a new instance of the IotHubDeviceDisconnectedEventData class. * @constructor * Event data for Microsoft.Devices.DeviceDisconnected event. * */ export interface IotHubDeviceDisconnectedEventData extends DeviceConnectionStateEventProperties { } /** * @class * Initializes a new instance of the DeviceTelemetryEventProperties class. * @constructor * Schema of the Data property of an EventGridEvent for a device telemetry * event (DeviceTelemetry). * * @member {object} [body] The content of the message from the device. * @member {object} [properties] Application properties are user-defined * strings that can be added to the message. These fields are optional. * @member {object} [systemProperties] System properties help identify contents * and source of the messages. */ export interface DeviceTelemetryEventProperties { body?: any; properties?: { [propertyName: string]: string }; systemProperties?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the IotHubDeviceTelemetryEventData class. * @constructor * Event data for Microsoft.Devices.DeviceTelemetry event. * */ export interface IotHubDeviceTelemetryEventData extends DeviceTelemetryEventProperties { } /** * @class * Initializes a new instance of the DeviceTwinMetadata class. * @constructor * Metadata information for the properties JSON document. * * @member {string} [lastUpdated] The ISO8601 timestamp of the last time the * properties were updated. */ export interface DeviceTwinMetadata { lastUpdated?: string; } /** * @class * Initializes a new instance of the DeviceTwinProperties class. * @constructor * A portion of the properties that can be written only by the application * back-end, and read by the device. * * @member {object} [metadata] Metadata information for the properties JSON * document. * @member {string} [metadata.lastUpdated] The ISO8601 timestamp of the last * time the properties were updated. * @member {number} [version] Version of device twin properties. */ export interface DeviceTwinProperties { metadata?: DeviceTwinMetadata; version?: number; } /** * @class * Initializes a new instance of the DeviceTwinInfoProperties class. * @constructor * Properties JSON element. * * @member {object} [desired] A portion of the properties that can be written * only by the application back-end, and read by the device. * @member {object} [desired.metadata] Metadata information for the properties * JSON document. * @member {string} [desired.metadata.lastUpdated] The ISO8601 timestamp of the * last time the properties were updated. * @member {number} [desired.version] Version of device twin properties. * @member {object} [reported] A portion of the properties that can be written * only by the device, and read by the application back-end. * @member {object} [reported.metadata] Metadata information for the properties * JSON document. * @member {string} [reported.metadata.lastUpdated] The ISO8601 timestamp of * the last time the properties were updated. * @member {number} [reported.version] Version of device twin properties. */ export interface DeviceTwinInfoProperties { desired?: DeviceTwinProperties; reported?: DeviceTwinProperties; } /** * @class * Initializes a new instance of the DeviceTwinInfoX509Thumbprint class. * @constructor * The thumbprint is a unique value for the x509 certificate, commonly used to * find a particular certificate in a certificate store. The thumbprint is * dynamically generated using the SHA1 algorithm, and does not physically * exist in the certificate. * * @member {string} [primaryThumbprint] Primary thumbprint for the x509 * certificate. * @member {string} [secondaryThumbprint] Secondary thumbprint for the x509 * certificate. */ export interface DeviceTwinInfoX509Thumbprint { primaryThumbprint?: string; secondaryThumbprint?: string; } /** * @class * Initializes a new instance of the DeviceTwinInfo class. * @constructor * Information about the device twin, which is the cloud representation of * application device metadata. * * @member {string} [authenticationType] Authentication type used for this * device: either SAS, SelfSigned, or CertificateAuthority. * @member {number} [cloudToDeviceMessageCount] Count of cloud to device * messages sent to this device. * @member {string} [connectionState] Whether the device is connected or * disconnected. * @member {string} [deviceId] The unique identifier of the device twin. * @member {string} [etag] A piece of information that describes the content of * the device twin. Each etag is guaranteed to be unique per device twin. * @member {string} [lastActivityTime] The ISO8601 timestamp of the last * activity. * @member {object} [properties] Properties JSON element. * @member {object} [properties.desired] A portion of the properties that can * be written only by the application back-end, and read by the device. * @member {object} [properties.desired.metadata] Metadata information for the * properties JSON document. * @member {string} [properties.desired.metadata.lastUpdated] The ISO8601 * timestamp of the last time the properties were updated. * @member {number} [properties.desired.version] Version of device twin * properties. * @member {object} [properties.reported] A portion of the properties that can * be written only by the device, and read by the application back-end. * @member {object} [properties.reported.metadata] Metadata information for the * properties JSON document. * @member {string} [properties.reported.metadata.lastUpdated] The ISO8601 * timestamp of the last time the properties were updated. * @member {number} [properties.reported.version] Version of device twin * properties. * @member {string} [status] Whether the device twin is enabled or disabled. * @member {string} [statusUpdateTime] The ISO8601 timestamp of the last device * twin status update. * @member {number} [version] An integer that is incremented by one each time * the device twin is updated. * @member {object} [x509Thumbprint] The thumbprint is a unique value for the * x509 certificate, commonly used to find a particular certificate in a * certificate store. The thumbprint is dynamically generated using the SHA1 * algorithm, and does not physically exist in the certificate. * @member {string} [x509Thumbprint.primaryThumbprint] Primary thumbprint for * the x509 certificate. * @member {string} [x509Thumbprint.secondaryThumbprint] Secondary thumbprint * for the x509 certificate. */ export interface DeviceTwinInfo { authenticationType?: string; cloudToDeviceMessageCount?: number; connectionState?: string; deviceId?: string; etag?: string; lastActivityTime?: string; properties?: DeviceTwinInfoProperties; status?: string; statusUpdateTime?: string; version?: number; x509Thumbprint?: DeviceTwinInfoX509Thumbprint; } /** * @class * Initializes a new instance of the DeviceConnectionStateEventInfo class. * @constructor * Information about the device connection state event. * * @member {string} [sequenceNumber] Sequence number is string representation * of a hexadecimal number. string compare can be used to identify the larger * number because both in ASCII and HEX numbers come after alphabets. If you * are converting the string to hex, then the number is a 256 bit number. */ export interface DeviceConnectionStateEventInfo { sequenceNumber?: string; } /** * @class * Initializes a new instance of the ContainerRegistryEventData class. * @constructor * The content of the event request message. * * @member {string} [id] The event ID. * @member {date} [timestamp] The time at which the event occurred. * @member {string} [action] The action that encompasses the provided event. * @member {object} [target] The target of the event. * @member {string} [target.mediaType] The MIME type of the referenced object. * @member {number} [target.size] The number of bytes of the content. Same as * Length field. * @member {string} [target.digest] The digest of the content, as defined by * the Registry V2 HTTP API Specification. * @member {number} [target.length] The number of bytes of the content. Same as * Size field. * @member {string} [target.repository] The repository name. * @member {string} [target.url] The direct URL to the content. * @member {string} [target.tag] The tag name. * @member {object} [request] The request that generated the event. * @member {string} [request.id] The ID of the request that initiated the * event. * @member {string} [request.addr] The IP or hostname and possibly port of the * client connection that initiated the event. This is the RemoteAddr from the * standard http request. * @member {string} [request.host] The externally accessible hostname of the * registry instance, as specified by the http host header on incoming * requests. * @member {string} [request.method] The request method that generated the * event. * @member {string} [request.useragent] The user agent header of the request. * @member {object} [actor] The agent that initiated the event. For most * situations, this could be from the authorization context of the request. * @member {string} [actor.name] The subject or username associated with the * request context that generated the event. * @member {object} [source] The registry node that generated the event. Put * differently, while the actor initiates the event, the source generates it. * @member {string} [source.addr] The IP or hostname and the port of the * registry node that generated the event. Generally, this will be resolved by * os.Hostname() along with the running port. * @member {string} [source.instanceID] The running instance of an application. * Changes after each restart. */ export interface ContainerRegistryEventData { id?: string; timestamp?: Date; action?: string; target?: ContainerRegistryEventTarget; request?: ContainerRegistryEventRequest; actor?: ContainerRegistryEventActor; source?: ContainerRegistryEventSource; } /** * @class * Initializes a new instance of the ContainerRegistryImagePushedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.ContainerRegistry.ImagePushed event. * */ export interface ContainerRegistryImagePushedEventData extends ContainerRegistryEventData { } /** * @class * Initializes a new instance of the ContainerRegistryImageDeletedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.ContainerRegistry.ImageDeleted event. * */ export interface ContainerRegistryImageDeletedEventData extends ContainerRegistryEventData { } /** * @class * Initializes a new instance of the ContainerRegistryArtifactEventData class. * @constructor * The content of the event request message. * * @member {string} [id] The event ID. * @member {date} [timestamp] The time at which the event occurred. * @member {string} [action] The action that encompasses the provided event. * @member {object} [target] The target of the event. * @member {string} [target.mediaType] The MIME type of the artifact. * @member {number} [target.size] The size in bytes of the artifact. * @member {string} [target.digest] The digest of the artifact. * @member {string} [target.repository] The repository name of the artifact. * @member {string} [target.tag] The tag of the artifact. * @member {string} [target.name] The name of the artifact. * @member {string} [target.version] The version of the artifact. */ export interface ContainerRegistryArtifactEventData { id?: string; timestamp?: Date; action?: string; target?: ContainerRegistryArtifactEventTarget; } /** * @class * Initializes a new instance of the ContainerRegistryChartPushedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.ContainerRegistry.ChartPushed event. * */ export interface ContainerRegistryChartPushedEventData extends ContainerRegistryArtifactEventData { } /** * @class * Initializes a new instance of the ContainerRegistryChartDeletedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.ContainerRegistry.ChartDeleted event. * */ export interface ContainerRegistryChartDeletedEventData extends ContainerRegistryArtifactEventData { } /** * @class * Initializes a new instance of the ContainerRegistryEventTarget class. * @constructor * The target of the event. * * @member {string} [mediaType] The MIME type of the referenced object. * @member {number} [size] The number of bytes of the content. Same as Length * field. * @member {string} [digest] The digest of the content, as defined by the * Registry V2 HTTP API Specification. * @member {number} [length] The number of bytes of the content. Same as Size * field. * @member {string} [repository] The repository name. * @member {string} [url] The direct URL to the content. * @member {string} [tag] The tag name. */ export interface ContainerRegistryEventTarget { mediaType?: string; size?: number; digest?: string; length?: number; repository?: string; url?: string; tag?: string; } /** * @class * Initializes a new instance of the ContainerRegistryEventRequest class. * @constructor * The request that generated the event. * * @member {string} [id] The ID of the request that initiated the event. * @member {string} [addr] The IP or hostname and possibly port of the client * connection that initiated the event. This is the RemoteAddr from the * standard http request. * @member {string} [host] The externally accessible hostname of the registry * instance, as specified by the http host header on incoming requests. * @member {string} [method] The request method that generated the event. * @member {string} [useragent] The user agent header of the request. */ export interface ContainerRegistryEventRequest { id?: string; addr?: string; host?: string; method?: string; useragent?: string; } /** * @class * Initializes a new instance of the ContainerRegistryEventActor class. * @constructor * The agent that initiated the event. For most situations, this could be from * the authorization context of the request. * * @member {string} [name] The subject or username associated with the request * context that generated the event. */ export interface ContainerRegistryEventActor { name?: string; } /** * @class * Initializes a new instance of the ContainerRegistryEventSource class. * @constructor * The registry node that generated the event. Put differently, while the actor * initiates the event, the source generates it. * * @member {string} [addr] The IP or hostname and the port of the registry node * that generated the event. Generally, this will be resolved by os.Hostname() * along with the running port. * @member {string} [instanceID] The running instance of an application. * Changes after each restart. */ export interface ContainerRegistryEventSource { addr?: string; instanceID?: string; } /** * @class * Initializes a new instance of the ContainerRegistryArtifactEventTarget class. * @constructor * The target of the event. * * @member {string} [mediaType] The MIME type of the artifact. * @member {number} [size] The size in bytes of the artifact. * @member {string} [digest] The digest of the artifact. * @member {string} [repository] The repository name of the artifact. * @member {string} [tag] The tag of the artifact. * @member {string} [name] The name of the artifact. * @member {string} [version] The version of the artifact. */ export interface ContainerRegistryArtifactEventTarget { mediaType?: string; size?: number; digest?: string; repository?: string; tag?: string; name?: string; version?: string; } /** * @class * Initializes a new instance of the ServiceBusActiveMessagesAvailableWithNoListenersEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners event. * * @member {string} [namespaceName] The namespace name of the * Microsoft.ServiceBus resource. * @member {string} [requestUri] The endpoint of the Microsoft.ServiceBus * resource. * @member {string} [entityType] The entity type of the Microsoft.ServiceBus * resource. Could be one of 'queue' or 'subscriber'. * @member {string} [queueName] The name of the Microsoft.ServiceBus queue. If * the entity type is of type 'subscriber', then this value will be null. * @member {string} [topicName] The name of the Microsoft.ServiceBus topic. If * the entity type is of type 'queue', then this value will be null. * @member {string} [subscriptionName] The name of the Microsoft.ServiceBus * topic's subscription. If the entity type is of type 'queue', then this value * will be null. */ export interface ServiceBusActiveMessagesAvailableWithNoListenersEventData { namespaceName?: string; requestUri?: string; entityType?: string; queueName?: string; topicName?: string; subscriptionName?: string; } /** * @class * Initializes a new instance of the ServiceBusDeadletterMessagesAvailableWithNoListenersEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListenersEvent event. * * @member {string} [namespaceName] The namespace name of the * Microsoft.ServiceBus resource. * @member {string} [requestUri] The endpoint of the Microsoft.ServiceBus * resource. * @member {string} [entityType] The entity type of the Microsoft.ServiceBus * resource. Could be one of 'queue' or 'subscriber'. * @member {string} [queueName] The name of the Microsoft.ServiceBus queue. If * the entity type is of type 'subscriber', then this value will be null. * @member {string} [topicName] The name of the Microsoft.ServiceBus topic. If * the entity type is of type 'queue', then this value will be null. * @member {string} [subscriptionName] The name of the Microsoft.ServiceBus * topic's subscription. If the entity type is of type 'queue', then this value * will be null. */ export interface ServiceBusDeadletterMessagesAvailableWithNoListenersEventData { namespaceName?: string; requestUri?: string; entityType?: string; queueName?: string; topicName?: string; subscriptionName?: string; } /** * @class * Initializes a new instance of the MediaJobStateChangeEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Media.JobStateChange event. * * @member {string} [previousState] The previous state of the Job. Possible * values include: 'Canceled', 'Canceling', 'Error', 'Finished', 'Processing', * 'Queued', 'Scheduled' * @member {string} [state] The new state of the Job. Possible values include: * 'Canceled', 'Canceling', 'Error', 'Finished', 'Processing', 'Queued', * 'Scheduled' * @member {object} [correlationData] Gets the Job correlation data. */ export interface MediaJobStateChangeEventData { readonly previousState?: string; readonly state?: string; correlationData?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the MediaJobErrorDetail class. * @constructor * Details of JobOutput errors. * * @member {string} [code] Code describing the error detail. * @member {string} [message] A human-readable representation of the error. */ export interface MediaJobErrorDetail { readonly code?: string; readonly message?: string; } /** * @class * Initializes a new instance of the MediaJobError class. * @constructor * Details of JobOutput errors. * * @member {string} [code] Error code describing the error. Possible values * include: 'ServiceError', 'ServiceTransientError', 'DownloadNotAccessible', * 'DownloadTransientError', 'UploadNotAccessible', 'UploadTransientError', * 'ConfigurationUnsupported', 'ContentMalformed', 'ContentUnsupported' * @member {string} [message] A human-readable language-dependent * representation of the error. * @member {string} [category] Helps with categorization of errors. Possible * values include: 'Service', 'Download', 'Upload', 'Configuration', 'Content' * @member {string} [retry] Indicates that it may be possible to retry the Job. * If retry is unsuccessful, please contact Azure support via Azure Portal. * Possible values include: 'DoNotRetry', 'MayRetry' * @member {array} [details] An array of details about specific errors that led * to this reported error. */ export interface MediaJobError { readonly code?: string; readonly message?: string; readonly category?: string; readonly retry?: string; readonly details?: MediaJobErrorDetail[]; } /** * @class * Initializes a new instance of the MediaJobOutput class. * @constructor * The event data for a Job output. * * @member {object} [error] Gets the Job output error. * @member {string} [error.code] Error code describing the error. Possible * values include: 'ServiceError', 'ServiceTransientError', * 'DownloadNotAccessible', 'DownloadTransientError', 'UploadNotAccessible', * 'UploadTransientError', 'ConfigurationUnsupported', 'ContentMalformed', * 'ContentUnsupported' * @member {string} [error.message] A human-readable language-dependent * representation of the error. * @member {string} [error.category] Helps with categorization of errors. * Possible values include: 'Service', 'Download', 'Upload', 'Configuration', * 'Content' * @member {string} [error.retry] Indicates that it may be possible to retry * the Job. If retry is unsuccessful, please contact Azure support via Azure * Portal. Possible values include: 'DoNotRetry', 'MayRetry' * @member {array} [error.details] An array of details about specific errors * that led to this reported error. * @member {string} [label] Gets the Job output label. * @member {number} progress Gets the Job output progress. * @member {string} state Gets the Job output state. Possible values include: * 'Canceled', 'Canceling', 'Error', 'Finished', 'Processing', 'Queued', * 'Scheduled' * @member {string} odatatype Polymorphic Discriminator */ export interface MediaJobOutput { error?: MediaJobError; label?: string; progress: number; state: string; odatatype: string; } /** * @class * Initializes a new instance of the MediaJobOutputAsset class. * @constructor * The event data for a Job output asset. * * @member {string} [assetName] Gets the Job output asset name. */ export interface MediaJobOutputAsset extends MediaJobOutput { assetName?: string; } /** * @class * Initializes a new instance of the MediaJobOutputProgressEventData class. * @constructor * Job Output Progress Event Data. * * @member {string} [label] Gets the Job output label. * @member {number} [progress] Gets the Job output progress. * @member {object} [jobCorrelationData] Gets the Job correlation data. */ export interface MediaJobOutputProgressEventData { label?: string; progress?: number; jobCorrelationData?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the MediaJobOutputStateChangeEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Media.JobOutputStateChange event. * * @member {string} [previousState] The previous state of the Job. Possible * values include: 'Canceled', 'Canceling', 'Error', 'Finished', 'Processing', * 'Queued', 'Scheduled' * @member {object} [output] Gets the output. * @member {object} [output.error] Gets the Job output error. * @member {string} [output.error.code] Error code describing the error. * Possible values include: 'ServiceError', 'ServiceTransientError', * 'DownloadNotAccessible', 'DownloadTransientError', 'UploadNotAccessible', * 'UploadTransientError', 'ConfigurationUnsupported', 'ContentMalformed', * 'ContentUnsupported' * @member {string} [output.error.message] A human-readable language-dependent * representation of the error. * @member {string} [output.error.category] Helps with categorization of * errors. Possible values include: 'Service', 'Download', 'Upload', * 'Configuration', 'Content' * @member {string} [output.error.retry] Indicates that it may be possible to * retry the Job. If retry is unsuccessful, please contact Azure support via * Azure Portal. Possible values include: 'DoNotRetry', 'MayRetry' * @member {array} [output.error.details] An array of details about specific * errors that led to this reported error. * @member {string} [output.label] Gets the Job output label. * @member {number} [output.progress] Gets the Job output progress. * @member {string} [output.state] Gets the Job output state. Possible values * include: 'Canceled', 'Canceling', 'Error', 'Finished', 'Processing', * 'Queued', 'Scheduled' * @member {string} [output.odatatype] Polymorphic Discriminator * @member {object} [jobCorrelationData] Gets the Job correlation data. */ export interface MediaJobOutputStateChangeEventData { readonly previousState?: string; output?: MediaJobOutput; jobCorrelationData?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the MediaJobScheduledEventData class. * @constructor * Job scheduled event data * */ export interface MediaJobScheduledEventData extends MediaJobStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobProcessingEventData class. * @constructor * Job processing event data * */ export interface MediaJobProcessingEventData extends MediaJobStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobCancelingEventData class. * @constructor * Job canceling event data * */ export interface MediaJobCancelingEventData extends MediaJobStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobFinishedEventData class. * @constructor * Job finished event data * * @member {array} [outputs] Gets the Job outputs. */ export interface MediaJobFinishedEventData extends MediaJobStateChangeEventData { outputs?: MediaJobOutput[]; } /** * @class * Initializes a new instance of the MediaJobCanceledEventData class. * @constructor * Job canceled event data * * @member {array} [outputs] Gets the Job outputs. */ export interface MediaJobCanceledEventData extends MediaJobStateChangeEventData { outputs?: MediaJobOutput[]; } /** * @class * Initializes a new instance of the MediaJobErroredEventData class. * @constructor * Job error state event data * * @member {array} [outputs] Gets the Job outputs. */ export interface MediaJobErroredEventData extends MediaJobStateChangeEventData { outputs?: MediaJobOutput[]; } /** * @class * Initializes a new instance of the MediaJobOutputCanceledEventData class. * @constructor * Job output canceled event data * */ export interface MediaJobOutputCanceledEventData extends MediaJobOutputStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobOutputCancelingEventData class. * @constructor * Job output canceling event data * */ export interface MediaJobOutputCancelingEventData extends MediaJobOutputStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobOutputErroredEventData class. * @constructor * Job output error event data * */ export interface MediaJobOutputErroredEventData extends MediaJobOutputStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobOutputFinishedEventData class. * @constructor * Job output finished event data * */ export interface MediaJobOutputFinishedEventData extends MediaJobOutputStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobOutputProcessingEventData class. * @constructor * Job output processing event data * */ export interface MediaJobOutputProcessingEventData extends MediaJobOutputStateChangeEventData { } /** * @class * Initializes a new instance of the MediaJobOutputScheduledEventData class. * @constructor * Job output scheduled event data * */ export interface MediaJobOutputScheduledEventData extends MediaJobOutputStateChangeEventData { } /** * @class * Initializes a new instance of the MediaLiveEventEncoderConnectedEventData class. * @constructor * Encoder connect event data. * * @member {string} [ingestUrl] Gets the ingest URL provided by the live event. * @member {string} [streamId] Gets the stream Id. * @member {string} [encoderIp] Gets the remote IP. * @member {string} [encoderPort] Gets the remote port. */ export interface MediaLiveEventEncoderConnectedEventData { readonly ingestUrl?: string; readonly streamId?: string; readonly encoderIp?: string; readonly encoderPort?: string; } /** * @class * Initializes a new instance of the MediaLiveEventConnectionRejectedEventData class. * @constructor * Encoder connection rejected event data. * * @member {string} [ingestUrl] Gets the ingest URL provided by the live event. * @member {string} [streamId] Gets the stream Id. * @member {string} [encoderIp] Gets the remote IP. * @member {string} [encoderPort] Gets the remote port. * @member {string} [resultCode] Gets the result code. */ export interface MediaLiveEventConnectionRejectedEventData { readonly ingestUrl?: string; readonly streamId?: string; readonly encoderIp?: string; readonly encoderPort?: string; readonly resultCode?: string; } /** * @class * Initializes a new instance of the MediaLiveEventEncoderDisconnectedEventData class. * @constructor * Encoder disconnected event data. * * @member {string} [ingestUrl] Gets the ingest URL provided by the live event. * @member {string} [streamId] Gets the stream Id. * @member {string} [encoderIp] Gets the remote IP. * @member {string} [encoderPort] Gets the remote port. * @member {string} [resultCode] Gets the result code. */ export interface MediaLiveEventEncoderDisconnectedEventData { readonly ingestUrl?: string; readonly streamId?: string; readonly encoderIp?: string; readonly encoderPort?: string; readonly resultCode?: string; } /** * @class * Initializes a new instance of the MediaLiveEventIncomingStreamReceivedEventData class. * @constructor * Encoder connect event data. * * @member {string} [ingestUrl] Gets the ingest URL provided by the live event. * @member {string} [trackType] Gets the type of the track (Audio / Video). * @member {string} [trackName] Gets the track name. * @member {number} [bitrate] Gets the bitrate of the track. * @member {string} [encoderIp] Gets the remote IP. * @member {string} [encoderPort] Gets the remote port. * @member {string} [timestamp] Gets the first timestamp of the data chunk * received. * @member {string} [duration] Gets the duration of the first data chunk. * @member {string} [timescale] Gets the timescale in which timestamp is * represented. */ export interface MediaLiveEventIncomingStreamReceivedEventData { readonly ingestUrl?: string; readonly trackType?: string; readonly trackName?: string; readonly bitrate?: number; readonly encoderIp?: string; readonly encoderPort?: string; readonly timestamp?: string; readonly duration?: string; readonly timescale?: string; } /** * @class * Initializes a new instance of the MediaLiveEventIncomingStreamsOutOfSyncEventData class. * @constructor * Incoming streams out of sync event data. * * @member {string} [minLastTimestamp] Gets the minimum last timestamp * received. * @member {string} [typeOfStreamWithMinLastTimestamp] Gets the type of stream * with minimum last timestamp. * @member {string} [maxLastTimestamp] Gets the maximum timestamp among all the * tracks (audio or video). * @member {string} [typeOfStreamWithMaxLastTimestamp] Gets the type of stream * with maximum last timestamp. * @member {string} [timescaleOfMinLastTimestamp] Gets the timescale in which * "MinLastTimestamp" is represented. * @member {string} [timescaleOfMaxLastTimestamp] Gets the timescale in which * "MaxLastTimestamp" is represented. */ export interface MediaLiveEventIncomingStreamsOutOfSyncEventData { readonly minLastTimestamp?: string; readonly typeOfStreamWithMinLastTimestamp?: string; readonly maxLastTimestamp?: string; readonly typeOfStreamWithMaxLastTimestamp?: string; readonly timescaleOfMinLastTimestamp?: string; readonly timescaleOfMaxLastTimestamp?: string; } /** * @class * Initializes a new instance of the MediaLiveEventIncomingVideoStreamsOutOfSyncEventData class. * @constructor * Incoming video stream out of synch event data. * * @member {string} [firstTimestamp] Gets the first timestamp received for one * of the quality levels. * @member {string} [firstDuration] Gets the duration of the data chunk with * first timestamp. * @member {string} [secondTimestamp] Gets the timestamp received for some * other quality levels. * @member {string} [secondDuration] Gets the duration of the data chunk with * second timestamp. * @member {string} [timescale] Gets the timescale in which both the timestamps * and durations are represented. */ export interface MediaLiveEventIncomingVideoStreamsOutOfSyncEventData { readonly firstTimestamp?: string; readonly firstDuration?: string; readonly secondTimestamp?: string; readonly secondDuration?: string; readonly timescale?: string; } /** * @class * Initializes a new instance of the MediaLiveEventIncomingDataChunkDroppedEventData class. * @constructor * Ingest fragment dropped event data. * * @member {string} [timestamp] Gets the timestamp of the data chunk dropped. * @member {string} [trackType] Gets the type of the track (Audio / Video). * @member {number} [bitrate] Gets the bitrate of the track. * @member {string} [timescale] Gets the timescale of the Timestamp. * @member {string} [resultCode] Gets the result code for fragment drop * operation. * @member {string} [trackName] Gets the name of the track for which fragment * is dropped. */ export interface MediaLiveEventIncomingDataChunkDroppedEventData { readonly timestamp?: string; readonly trackType?: string; readonly bitrate?: number; readonly timescale?: string; readonly resultCode?: string; readonly trackName?: string; } /** * @class * Initializes a new instance of the MediaLiveEventIngestHeartbeatEventData class. * @constructor * Ingest fragment dropped event data. * * @member {string} [trackType] Gets the type of the track (Audio / Video). * @member {string} [trackName] Gets the track name. * @member {number} [bitrate] Gets the bitrate of the track. * @member {number} [incomingBitrate] Gets the incoming bitrate. * @member {string} [lastTimestamp] Gets the last timestamp. * @member {string} [timescale] Gets the timescale of the last timestamp. * @member {number} [overlapCount] Gets the fragment Overlap count. * @member {number} [discontinuityCount] Gets the fragment Discontinuity count. * @member {number} [nonincreasingCount] Gets Non increasing count. * @member {boolean} [unexpectedBitrate] Gets a value indicating whether * unexpected bitrate is present or not. * @member {string} [state] Gets the state of the live event. * @member {boolean} [healthy] Gets a value indicating whether preview is * healthy or not. */ export interface MediaLiveEventIngestHeartbeatEventData { readonly trackType?: string; readonly trackName?: string; readonly bitrate?: number; readonly incomingBitrate?: number; readonly lastTimestamp?: string; readonly timescale?: string; readonly overlapCount?: number; readonly discontinuityCount?: number; readonly nonincreasingCount?: number; readonly unexpectedBitrate?: boolean; readonly state?: string; readonly healthy?: boolean; } /** * @class * Initializes a new instance of the MediaLiveEventTrackDiscontinuityDetectedEventData class. * @constructor * Ingest track discontinuity detected event data. * * @member {string} [trackType] Gets the type of the track (Audio / Video). * @member {string} [trackName] Gets the track name. * @member {number} [bitrate] Gets the bitrate. * @member {string} [previousTimestamp] Gets the timestamp of the previous * fragment. * @member {string} [newTimestamp] Gets the timestamp of the current fragment. * @member {string} [timescale] Gets the timescale in which both timestamps and * discontinuity gap are represented. * @member {string} [discontinuityGap] Gets the discontinuity gap between * PreviousTimestamp and NewTimestamp. */ export interface MediaLiveEventTrackDiscontinuityDetectedEventData { readonly trackType?: string; readonly trackName?: string; readonly bitrate?: number; readonly previousTimestamp?: string; readonly newTimestamp?: string; readonly timescale?: string; readonly discontinuityGap?: string; } /** * @class * Initializes a new instance of the MapsGeofenceEventProperties class. * @constructor * Schema of the Data property of an EventGridEvent for a Geofence event * (GeofenceEntered, GeofenceExited, GeofenceResult). * * @member {array} [expiredGeofenceGeometryId] Lists of the geometry ID of the * geofence which is expired relative to the user time in the request. * @member {array} [geometries] Lists the fence geometries that either fully * contain the coordinate position or have an overlap with the searchBuffer * around the fence. * @member {array} [invalidPeriodGeofenceGeometryId] Lists of the geometry ID * of the geofence which is in invalid period relative to the user time in the * request. * @member {boolean} [isEventPublished] True if at least one event is published * to the Azure Maps event subscriber, false if no event is published to the * Azure Maps event subscriber. */ export interface MapsGeofenceEventProperties { expiredGeofenceGeometryId?: string[]; geometries?: MapsGeofenceGeometry[]; invalidPeriodGeofenceGeometryId?: string[]; isEventPublished?: boolean; } /** * @class * Initializes a new instance of the MapsGeofenceEnteredEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Maps.GeofenceEntered event. * */ export interface MapsGeofenceEnteredEventData extends MapsGeofenceEventProperties { } /** * @class * Initializes a new instance of the MapsGeofenceExitedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Maps.GeofenceExited event. * */ export interface MapsGeofenceExitedEventData extends MapsGeofenceEventProperties { } /** * @class * Initializes a new instance of the MapsGeofenceResultEventData class. * @constructor * Schema of the Data property of an EventGridEvent for a * Microsoft.Maps.GeofenceResult event. * */ export interface MapsGeofenceResultEventData extends MapsGeofenceEventProperties { } /** * @class * Initializes a new instance of the MapsGeofenceGeometry class. * @constructor * The geofence geometry. * * @member {string} [deviceId] ID of the device. * @member {number} [distance] Distance from the coordinate to the closest * border of the geofence. Positive means the coordinate is outside of the * geofence. If the coordinate is outside of the geofence, but more than the * value of searchBuffer away from the closest geofence border, then the value * is 999. Negative means the coordinate is inside of the geofence. If the * coordinate is inside the polygon, but more than the value of searchBuffer * away from the closest geofencing border,then the value is -999. A value of * 999 means that there is great confidence the coordinate is well outside the * geofence. A value of -999 means that there is great confidence the * coordinate is well within the geofence. * @member {string} [geometryId] The unique ID for the geofence geometry. * @member {number} [nearestLat] Latitude of the nearest point of the geometry. * @member {number} [nearestLon] Longitude of the nearest point of the * geometry. * @member {string} [udId] The unique id returned from user upload service when * uploading a geofence. Will not be included in geofencing post API. */ export interface MapsGeofenceGeometry { deviceId?: string; distance?: number; geometryId?: string; nearestLat?: number; nearestLon?: number; udId?: string; } /** * @class * Initializes a new instance of the AppConfigurationKeyValueModifiedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.AppConfiguration.KeyValueModified event. * * @member {string} [key] The key used to identify the key-value that was * modified. * @member {string} [label] The label, if any, used to identify the key-value * that was modified. * @member {string} [etag] The etag representing the new state of the * key-value. */ export interface AppConfigurationKeyValueModifiedEventData { key?: string; label?: string; etag?: string; } /** * @class * Initializes a new instance of the AppConfigurationKeyValueDeletedEventData class. * @constructor * Schema of the Data property of an EventGridEvent for an * Microsoft.AppConfiguration.KeyValueDeleted event. * * @member {string} [key] The key used to identify the key-value that was * deleted. * @member {string} [label] The label, if any, used to identify the key-value * that was deleted. * @member {string} [etag] The etag representing the key-value that was * deleted. */ export interface AppConfigurationKeyValueDeletedEventData { key?: string; label?: string; etag?: string; }
the_stack
* Licensed Materials - Property of IBM * © Copyright IBM Corp. 2016 */ // This is retrofitted type definitions just to make // typedoc happy with generating doc on the src/*.ts files. // The typescript compiler and node typings are at level 1.8 // typedoc operates a compiler at level 1.6. // // The definitions below are mostly pulled from node.d.ts // and tweaked so that typedoc does not complain. // declare var __dirname : string; declare var require: any; declare namespace NodeJS { export interface EventEmitter { addListener(event: string, listener: Function): EventEmitter; // : this on(event: string, listener: Function): EventEmitter; // : this; once(event: string, listener: Function): EventEmitter; // : this; removeListener(event: string, listener: Function): EventEmitter; // : this; removeAllListeners(event?: string): EventEmitter; // : this; setMaxListeners(n: number): EventEmitter; // : this; getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; listenerCount(type: string): number; } } declare module "events" { export class EventEmitter implements NodeJS.EventEmitter { static EventEmitter: EventEmitter; static listenerCount(emitter: EventEmitter, event: string): number; // deprecated static defaultMaxListeners: number; addListener(event: string, listener: Function): EventEmitter; // : this; on(event: string, listener: Function): EventEmitter; // : this; once(event: string, listener: Function): EventEmitter; // : this; removeListener(event: string, listener: Function): EventEmitter; // : this; removeAllListeners(event?: string): EventEmitter; // : this; setMaxListeners(n: number): EventEmitter; // : this; getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; listenerCount(type: string): number; } } interface Buffer extends NodeBuffer {} /** * Raw data is stored in instances of the Buffer class. * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' */ declare var Buffer: { /** * Allocates a new buffer containing the given {str}. * * @param str String to store in buffer. * @param encoding encoding to use, optional. Default is 'utf8' */ new (str: string, encoding?: string): Buffer; /** * Allocates a new buffer of {size} octets. * * @param size count of octets to allocate. */ new (size: number): Buffer; /** * Allocates a new buffer containing the given {array} of octets. * * @param array The octets to store. */ new (array: Uint8Array): Buffer; /** * Produces a Buffer backed by the same allocated memory as * the given {ArrayBuffer}. * * * @param arrayBuffer The ArrayBuffer with which to share memory. */ new (arrayBuffer: ArrayBuffer): Buffer; /** * Allocates a new buffer containing the given {array} of octets. * * @param array The octets to store. */ new (array: any[]): Buffer; /** * Copies the passed {buffer} data onto a new {Buffer} instance. * * @param buffer The buffer to copy. */ new (buffer: Buffer): Buffer; prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. * * @param array */ from(array: any[]): Buffer; /** * When passed a reference to the .buffer property of a TypedArray instance, * the newly created Buffer will share the same allocated memory as the TypedArray. * The optional {byteOffset} and {length} arguments specify a memory range * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() * @param byteOffset * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. * * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. * * @param str */ from(str: string, encoding?: string): Buffer; /** * Returns true if {obj} is a Buffer * * @param obj object to test. */ isBuffer(obj: any): obj is Buffer; /** * Returns true if {encoding} is a valid encoding argument. * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' * * @param encoding string to test. */ isEncoding(encoding: string): boolean; /** * Gives the actual byte length of a string. encoding defaults to 'utf8'. * This is not the same as String.prototype.length since that returns the number of characters in a string. * * @param string string to test. * @param encoding encoding used to evaluate (defaults to 'utf8') */ byteLength(string: string, encoding?: string): number; /** * Returns a buffer which is the result of concatenating all the buffers in the list together. * * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. * If the list has exactly one item, then the first item of the list is returned. * If the list has more than one item, then a new Buffer is created. * * @param list An array of Buffer objects to concatenate * @param totalLength Total length of the buffers when concatenated. * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. */ concat(list: Buffer[], totalLength?: number): Buffer; /** * The same as buf1.compare(buf2). */ compare(buf1: Buffer, buf2: Buffer): number; }; /** * @deprecated */ interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; toJSON(): any; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; readUInt8(offset: number, noAssert?: boolean): number; readUInt16LE(offset: number, noAssert?: boolean): number; readUInt16BE(offset: number, noAssert?: boolean): number; readUInt32LE(offset: number, noAssert?: boolean): number; readUInt32BE(offset: number, noAssert?: boolean): number; readInt8(offset: number, noAssert?: boolean): number; readInt16LE(offset: number, noAssert?: boolean): number; readInt16BE(offset: number, noAssert?: boolean): number; readInt32LE(offset: number, noAssert?: boolean): number; readInt32BE(offset: number, noAssert?: boolean): number; readFloatLE(offset: number, noAssert?: boolean): number; readFloatBE(offset: number, noAssert?: boolean): number; readDoubleLE(offset: number, noAssert?: boolean): number; readDoubleBE(offset: number, noAssert?: boolean): number; writeUInt8(value: number, offset: number, noAssert?: boolean): number; writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; writeInt8(value: number, offset: number, noAssert?: boolean): number; writeInt16LE(value: number, offset: number, noAssert?: boolean): number; writeInt16BE(value: number, offset: number, noAssert?: boolean): number; writeInt32LE(value: number, offset: number, noAssert?: boolean): number; writeInt32BE(value: number, offset: number, noAssert?: boolean): number; writeFloatLE(value: number, offset: number, noAssert?: boolean): number; writeFloatBE(value: number, offset: number, noAssert?: boolean): number; writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; fill(value: any, offset?: number, end?: number): Buffer; // TODO: encoding param indexOf(value: string | number | Buffer, byteOffset?: number): number; // TODO: entries // TODO: includes // TODO: keys // TODO: values } declare module "url" { export interface Url { href?: string; protocol?: string; auth?: string; hostname?: string; port?: string; host?: string; pathname?: string; search?: string; query?: string | any; slashes?: boolean; hash?: string; path?: string; } export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; export function format(url: Url): string; export function resolve(from: string, to: string): string; } declare var process : Process; interface Process { env: {[name:string]:string}; } declare module "debug" { function defaultFunc (s:string): any; export = defaultFunc; }
the_stack
import * as vd from "virtual-dom"; import { CancelMapillaryError } from "../../error/CancelMapillaryError"; import { Spatial } from "../../geo/Spatial"; import { Image } from "../../graph/Image"; import { Navigator } from "../../viewer/Navigator"; import { NavigationDirection } from "../../graph/edge/NavigationDirection"; import { NavigationEdge } from "../../graph/edge/interfaces/NavigationEdge"; import { NavigationEdgeStatus } from "../../graph/interfaces/NavigationEdgeStatus"; import { Sequence } from "../../graph/Sequence"; import { ViewportSize } from "../../render/interfaces/ViewportSize"; import { RenderCamera } from "../../render/RenderCamera"; import { EulerRotation } from "../../state/interfaces/EulerRotation"; import { DirectionConfiguration } from "../interfaces/DirectionConfiguration"; import { DirectionDOMCalculator } from "./DirectionDOMCalculator"; import { isSpherical } from "../../geo/Geo"; /** * @class DirectionDOMRenderer * @classdesc DOM renderer for direction arrows. */ export class DirectionDOMRenderer { private _spatial: Spatial; private _calculator: DirectionDOMCalculator; private _image: Image; private _rotation: EulerRotation; private _epsilon: number; private _highlightKey: string; private _distinguishSequence: boolean; private _needsRender: boolean; private _stepEdges: NavigationEdge[]; private _turnEdges: NavigationEdge[]; private _sphericalEdges: NavigationEdge[]; private _sequenceEdgeKeys: string[]; private _stepDirections: NavigationDirection[]; private _turnDirections: NavigationDirection[]; private _turnNames: { [dir: number]: string }; private _isEdge: boolean = false; constructor(configuration: DirectionConfiguration, size: ViewportSize) { this._spatial = new Spatial(); this._calculator = new DirectionDOMCalculator(configuration, size); this._image = null; this._rotation = { phi: 0, theta: 0 }; this._epsilon = 0.5 * Math.PI / 180; this._highlightKey = null; this._distinguishSequence = false; this._needsRender = false; this._stepEdges = []; this._turnEdges = []; this._sphericalEdges = []; this._sequenceEdgeKeys = []; this._stepDirections = [ NavigationDirection.StepForward, NavigationDirection.StepBackward, NavigationDirection.StepLeft, NavigationDirection.StepRight, ]; this._turnDirections = [ NavigationDirection.TurnLeft, NavigationDirection.TurnRight, NavigationDirection.TurnU, ]; this._turnNames = {}; this._turnNames[NavigationDirection.TurnLeft] = "mapillary-direction-turn-left"; this._turnNames[NavigationDirection.TurnRight] = "mapillary-direction-turn-right"; this._turnNames[NavigationDirection.TurnU] = "mapillary-direction-turn-around"; // detects IE 8-11, then Edge 20+. let isIE: boolean = !!(<any>document).documentMode; this._isEdge = !isIE && !!(<any>window).StyleMedia; } /** * Get needs render. * * @returns {boolean} Value indicating whether render should be called. */ public get needsRender(): boolean { return this._needsRender; } /** * Renders virtual DOM elements. * * @description Calling render resets the needs render property. */ public render(navigator: Navigator): vd.VNode { this._needsRender = false; let rotation: EulerRotation = this._rotation; let steps: vd.VNode[] = []; let turns: vd.VNode[] = []; if (isSpherical(this._image.cameraType)) { steps = steps.concat(this._createSphericalArrows(navigator, rotation)); } else { steps = steps.concat( this._createPerspectiveToSphericalArrows(navigator, rotation)); steps = steps.concat(this._createStepArrows(navigator, rotation)); turns = turns.concat(this._createTurnArrows(navigator)); } return this._getContainer(steps, turns, rotation); } public setEdges(edgeStatus: NavigationEdgeStatus, sequence: Sequence): void { this._setEdges(edgeStatus, sequence); this._setNeedsRender(); } /** * Set image for which to show edges. * * @param {Image} image */ public setImage(image: Image): void { this._image = image; this._clearEdges(); this._setNeedsRender(); } /** * Set the render camera to use for calculating rotations. * * @param {RenderCamera} renderCamera */ public setRenderCamera(renderCamera: RenderCamera): void { let rotation: EulerRotation = renderCamera.rotation; if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) { return; } this._rotation = rotation; this._setNeedsRender(); } /** * Set configuration values. * * @param {DirectionConfiguration} configuration */ public setConfiguration(configuration: DirectionConfiguration): void { let needsRender: boolean = false; if (this._highlightKey !== configuration.highlightId || this._distinguishSequence !== configuration.distinguishSequence) { this._highlightKey = configuration.highlightId; this._distinguishSequence = configuration.distinguishSequence; needsRender = true; } if (this._calculator.minWidth !== configuration.minWidth || this._calculator.maxWidth !== configuration.maxWidth) { this._calculator.configure(configuration); needsRender = true; } if (needsRender) { this._setNeedsRender(); } } /** * Detect the element's width and height and resize * elements accordingly. * * @param {ViewportSize} size Size of vßiewer container element. */ public resize(size: ViewportSize): void { this._calculator.resize(size); this._setNeedsRender(); } private _setNeedsRender(): void { if (this._image != null) { this._needsRender = true; } } private _clearEdges(): void { this._stepEdges = []; this._turnEdges = []; this._sphericalEdges = []; this._sequenceEdgeKeys = []; } private _setEdges(edgeStatus: NavigationEdgeStatus, sequence: Sequence): void { this._stepEdges = []; this._turnEdges = []; this._sphericalEdges = []; this._sequenceEdgeKeys = []; for (let edge of edgeStatus.edges) { let direction: NavigationDirection = edge.data.direction; if (this._stepDirections.indexOf(direction) > -1) { this._stepEdges.push(edge); continue; } if (this._turnDirections.indexOf(direction) > -1) { this._turnEdges.push(edge); continue; } if (edge.data.direction === NavigationDirection.Spherical) { this._sphericalEdges.push(edge); } } if (this._distinguishSequence && sequence != null) { let edges: NavigationEdge[] = this._sphericalEdges .concat(this._stepEdges) .concat(this._turnEdges); for (let edge of edges) { let edgeKey: string = edge.target; for (let sequenceKey of sequence.imageIds) { if (sequenceKey === edgeKey) { this._sequenceEdgeKeys.push(edgeKey); break; } } } } } private _createSphericalArrows(navigator: Navigator, rotation: EulerRotation): vd.VNode[] { let arrows: vd.VNode[] = []; for (let sphericalEdge of this._sphericalEdges) { arrows.push( this._createVNodeByKey( navigator, sphericalEdge.target, sphericalEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "mapillary-direction-arrow-spherical")); } for (let stepEdge of this._stepEdges) { arrows.push( this._createSphericalToPerspectiveArrow( navigator, stepEdge.target, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction)); } return arrows; } private _createSphericalToPerspectiveArrow( navigator: Navigator, key: string, azimuth: number, rotation: EulerRotation, direction: NavigationDirection): vd.VNode { let threshold: number = Math.PI / 8; let relativePhi: number = rotation.phi; switch (direction) { case NavigationDirection.StepBackward: relativePhi = rotation.phi - Math.PI; break; case NavigationDirection.StepLeft: relativePhi = rotation.phi + Math.PI / 2; break; case NavigationDirection.StepRight: relativePhi = rotation.phi - Math.PI / 2; break; default: break; } if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) { return this._createVNodeByKey( navigator, key, azimuth, rotation, this._calculator.outerRadius, "mapillary-direction-arrow-step"); } return this._createVNodeInactive(key, azimuth, rotation); } private _createPerspectiveToSphericalArrows(navigator: Navigator, rotation: EulerRotation): vd.VNode[] { let arrows: vd.VNode[] = []; for (let sphericalEdge of this._sphericalEdges) { arrows.push( this._createVNodeByKey( navigator, sphericalEdge.target, sphericalEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "mapillary-direction-arrow-spherical", true)); } return arrows; } private _createStepArrows(navigator: Navigator, rotation: EulerRotation): vd.VNode[] { let arrows: vd.VNode[] = []; for (let stepEdge of this._stepEdges) { arrows.push( this._createVNodeByDirection( navigator, stepEdge.target, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction)); } return arrows; } private _createTurnArrows(navigator: Navigator): vd.VNode[] { let turns: vd.VNode[] = []; for (let turnEdge of this._turnEdges) { let direction: NavigationDirection = turnEdge.data.direction; let name: string = this._turnNames[direction]; turns.push( this._createVNodeByTurn( navigator, turnEdge.target, name, direction)); } return turns; } private _createVNodeByKey( navigator: Navigator, key: string, azimuth: number, rotation: EulerRotation, offset: number, className: string, shiftVertically?: boolean): vd.VNode { let onClick: (e: Event) => void = (e: Event): void => { navigator.moveTo$(key) .subscribe( undefined, (error: Error): void => { if (!(error instanceof CancelMapillaryError)) { console.error(error); } }); }; return this._createVNode( key, azimuth, rotation, offset, className, "mapillary-direction-circle", onClick, shiftVertically); } private _createVNodeByDirection( navigator: Navigator, key: string, azimuth: number, rotation: EulerRotation, direction: NavigationDirection): vd.VNode { let onClick: (e: Event) => void = (e: Event): void => { navigator.moveDir$(direction) .subscribe( undefined, (error: Error): void => { if (!(error instanceof CancelMapillaryError)) { console.error(error); } }); }; return this._createVNode( key, azimuth, rotation, this._calculator.outerRadius, "mapillary-direction-arrow-step", "mapillary-direction-circle", onClick); } private _createVNodeByTurn( navigator: Navigator, key: string, className: string, direction: NavigationDirection): vd.VNode { let onClick: (e: Event) => void = (e: Event): void => { navigator.moveDir$(direction) .subscribe( undefined, (error: Error): void => { if (!(error instanceof CancelMapillaryError)) { console.error(error); } }); }; let style: any = { height: this._calculator.turnCircleSizeCss, transform: "rotate(0)", // apply transform to preserve 3D width: this._calculator.turnCircleSizeCss, }; switch (direction) { case NavigationDirection.TurnLeft: style.left = "5px"; style.top = "5px"; break; case NavigationDirection.TurnRight: style.right = "5px"; style.top = "5px"; break; case NavigationDirection.TurnU: style.left = "5px"; style.bottom = "5px"; break; default: break; } let circleProperties: vd.createProperties = { attributes: { "data-id": key, }, onclick: onClick, style: style, }; let circleClassName: string = "mapillary-direction-turn-circle"; if (this._sequenceEdgeKeys.indexOf(key) > -1) { circleClassName += "-sequence"; } if (this._highlightKey === key) { circleClassName += "-highlight"; } let turn: vd.VNode = vd.h(`div.${className}`, {}, []); return vd.h("div." + circleClassName, circleProperties, [turn]); } private _createVNodeInactive(key: string, azimuth: number, rotation: EulerRotation): vd.VNode { return this._createVNode( key, azimuth, rotation, this._calculator.outerRadius, "mapillary-direction-arrow-inactive", "mapillary-direction-circle-inactive"); } private _createVNode( key: string, azimuth: number, rotation: EulerRotation, radius: number, className: string, circleClassName: string, onClick?: (e: Event) => void, shiftVertically?: boolean): vd.VNode { let translation: number[] = this._calculator.angleToCoordinates(azimuth - rotation.phi); // rotate 90 degrees clockwise and flip over X-axis let translationX: number = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth); let translationY: number = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight); let shadowTranslation: number[] = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi); let shadowOffset: number = this._calculator.shadowOffset; let shadowTranslationX: number = -shadowOffset * shadowTranslation[1]; let shadowTranslationY: number = shadowOffset * shadowTranslation[0]; let filter: string = `drop-shadow(${shadowTranslationX}px ${shadowTranslationY}px 1px rgba(0,0,0,0.8))`; let properties: vd.createProperties = { style: { "-webkit-filter": filter, filter: filter, }, }; let chevron: vd.VNode = vd.h("div." + className, properties, []); let azimuthDeg: number = -this._spatial.radToDeg(azimuth - rotation.phi); let circleTransform: string = shiftVertically ? `translate(${translationX}px, ${translationY}px) rotate(${azimuthDeg}deg) translateZ(-0.01px)` : `translate(${translationX}px, ${translationY}px) rotate(${azimuthDeg}deg)`; let circleProperties: vd.createProperties = { attributes: { "data-id": key }, onclick: onClick, style: { height: this._calculator.stepCircleSizeCss, marginLeft: this._calculator.stepCircleMarginCss, marginTop: this._calculator.stepCircleMarginCss, transform: circleTransform, width: this._calculator.stepCircleSizeCss, }, }; if (this._sequenceEdgeKeys.indexOf(key) > -1) { circleClassName += "-sequence"; } if (this._highlightKey === key) { circleClassName += "-highlight"; } return vd.h("div." + circleClassName, circleProperties, [chevron]); } private _getContainer( steps: vd.VNode[], turns: vd.VNode[], rotation: EulerRotation): vd.VNode { // edge does not handle hover on perspective transforms. let transform: string = this._isEdge ? "rotateX(60deg)" : `perspective(${this._calculator.containerWidthCss}) rotateX(60deg)`; let properties: vd.createProperties = { oncontextmenu: (event: MouseEvent): void => { event.preventDefault(); }, style: { bottom: this._calculator.containerBottomCss, height: this._calculator.containerHeightCss, left: this._calculator.containerLeftCss, marginLeft: this._calculator.containerMarginCss, transform: transform, width: this._calculator.containerWidthCss, }, }; return vd.h("div.mapillary-direction-perspective", properties, turns.concat(steps)); } }
the_stack
import classnames from "classnames"; import {SparkRoutes} from "helpers/spark_routes"; import {MithrilComponent, MithrilViewComponent} from "jsx/mithril-component"; import _ from "lodash"; import m from "mithril"; import Stream from "mithril/stream"; import {stringOrUndefined} from "models/compare/pipeline_instance_json"; import {MaterialModification} from "models/config_repos/types"; import {MaterialAPIs, MaterialModifications, MaterialUsages, MaterialWithFingerprint} from "models/materials/materials"; import {FlashMessage, FlashMessageModel, MessageType} from "views/components/flash_message"; import {SearchField} from "views/components/forms/input_fields"; import {HeaderPanel} from "views/components/header_panel"; import {Link} from "views/components/link"; import linkStyles from "views/components/link/index.scss"; import {Modal, ModalState, Size} from "views/components/modal"; import {Spinner} from "views/components/spinner"; import {Table} from "views/components/table"; import spinnerCss from "views/pages/agents/spinner.scss"; import styles from "./index.scss"; import {MaterialWidget} from "./material_widget"; export class ShowModificationsModal extends Modal { errorMessage: Stream<string> = Stream(); private material: MaterialWithFingerprint; private modifications: Stream<MaterialModifications> = Stream(); private service: ApiService; private searchQuery: Stream<string> = Stream(""); private operationInProgress: Stream<boolean> = Stream(); constructor(material: MaterialWithFingerprint, service: ApiService = new FetchHistoryService()) { super(Size.large); this.material = material; this.service = service; this.fetchModifications(); } body(): m.Children { const title = `${this.material.typeForDisplay()} : ${this.material.displayName()}`; const searchBox = <div className={styles.searchBoxWrapper}> <SearchField property={this.searchQuery} dataTestId={"search-box"} name={"some-name"} oninput={this.onPatternChange.bind(this)} placeholder="Search in revision, comment or username"/> </div>; const header = <HeaderPanel title={title} buttons={searchBox}/>; if (!_.isEmpty(this.errorMessage())) { return <div data-test-id="modifications-modal" class={styles.modificationModal}> {header} <div className={styles.modificationWrapper}> <FlashMessage type={MessageType.alert} message={this.errorMessage()}/> </div> </div>; } if (this.operationInProgress() || this.isLoading()) { return <div data-test-id="modifications-modal" class={styles.modificationModal}> {header} <div class={classnames(styles.modificationWrapper, styles.spinnerWrapper)}> <Spinner css={spinnerCss}/> </div> </div>; } if (_.isEmpty(this.modifications())) { const msg = _.isEmpty(this.searchQuery()) ? "This material has not been parsed yet!" : <span>No modifications found for query: <i>{this.searchQuery()}</i></span>; return <div data-test-id="modifications-modal" class={styles.modificationModal}> {header} <div class={styles.modificationWrapper}> {msg} </div> </div>; } return <div data-test-id="modifications-modal" class={styles.modificationModal}> {header} <div class={styles.modificationWrapper}> {this.modifications().map((mod, index) => { const details = MaterialWidget.showModificationDetails(mod); ShowModificationsModal.updateWithVsmLink(details, mod, this.material.fingerprint()); const username = details.get("Username"); return <div data-test-id={`mod-${index}`} class={styles.modification}> <div class={styles.user}> <div className={styles.truncate} data-test-id="mod-username" title={username}>{username}</div> <div className={styles.truncate} data-test-id="mod-modified-time">{details.get("Modified Time")}</div> </div> <div class={styles.commentWrapper} data-test-id="mod-comment"> <CommentRenderer text={details.get("Comment")}/> </div> <div class={styles.rev} data-test-id="mod-rev">{details.get("Revision")}</div> </div>; })} </div> <PaginationWidget previousLink={this.modifications().previousLink} nextLink={this.modifications().nextLink} onPageChange={this.onPageChange.bind(this)}/> </div>; } title(): string { return 'Modifications'; } private static updateWithVsmLink(details: Map<string, m.Children>, mod: MaterialModification, fingerprint: string) { const vsmLink = <Link dataTestId={"vsm-link"} href={SparkRoutes.materialsVsmLink(fingerprint, mod.revision)} title={"Value Stream Map"}>VSM</Link>; const revision = details.get("Revision"); details.set("Revision", <div><span class={styles.revision} title={revision}>{revision} </span>| {vsmLink}</div>); } private onPageChange(link: string) { this.fetchModifications(link); } private onPatternChange(e: InputEvent) { // @ts-ignore this.searchQuery(e.target!.value); // this needs to be done as the oninput method is called before the property stream gets updated _.throttle(() => this.fetchModifications(), 500, {trailing: true})(); } private fetchModifications(link?: string) { if (this.operationInProgress() !== true) { this.operationInProgress(true); this.errorMessage(""); this.service.fetchHistory(this.material.fingerprint(), this.searchQuery(), link, (mods) => { this.modifications(mods); this.operationInProgress(false); this.focusOnSearchBox(); }, (errMsg) => { this.errorMessage(errMsg); this.operationInProgress(false); }); } } private focusOnSearchBox() { if (!_.isEmpty(this.searchQuery())) { document.getElementsByTagName('input')[1].focus(); } } } interface PaginationAttrs { previousLink: stringOrUndefined; nextLink: stringOrUndefined; onPageChange: (link: string) => void; } class PaginationWidget extends MithrilViewComponent<PaginationAttrs> { view(vnode: m.Vnode<PaginationAttrs, this>): m.Children | void | null { const hasPreviousPage = vnode.attrs.previousLink !== undefined; const hasNextPage = vnode.attrs.nextLink !== undefined; const onPreviousClick = (e: MouseEvent) => { e.stopPropagation(); if (hasPreviousPage) { vnode.attrs.onPageChange(vnode.attrs.previousLink!); } }; const onNextClick = (e: MouseEvent) => { e.stopPropagation(); if (hasNextPage) { vnode.attrs.onPageChange(vnode.attrs.nextLink!); } }; return <div data-test-id="pagination" className={styles.pagination}> <a title="Previous" role="button" className={classnames(linkStyles.inlineLink, styles.paginationLink, {[styles.disabled]: !hasPreviousPage})} href="#" onclick={onPreviousClick}>Previous</a> <a title="Next" role="button" className={classnames(linkStyles.inlineLink, styles.paginationLink, {[styles.disabled]: !hasNextPage})} href="#" onclick={onNextClick}>Next</a> </div>; } } export interface ApiService { fetchHistory(fingerprint: string, searchPattern: string, link: stringOrUndefined, onSuccess: (data: MaterialModifications) => void, onError: (message: string) => void): void; } class FetchHistoryService implements ApiService { fetchHistory(fingerprint: string, searchPattern: string, link: stringOrUndefined, onSuccess: (data: MaterialModifications) => void, onError: (message: string) => void): void { MaterialAPIs.modifications(fingerprint, searchPattern, link).then((result) => { result.do((successResponse) => onSuccess(successResponse.body), (errorResponse) => onError(errorResponse.message)); }); } } export class ShowUsagesModal extends Modal { usages?: MaterialUsages; private readonly name: string; private message: FlashMessageModel = new FlashMessageModel(); constructor(material: MaterialWithFingerprint, usages?: MaterialUsages) { super(); this.name = material.displayName(); // used for testing if (usages) { this.usages = usages; } else { this.fetchUsages(material); } } title(): string { return 'Usages'; } body(): m.Children { if (this.isLoading()) { return; } if (this.message.hasMessage()) { return <FlashMessage type={this.message.type} message={this.message.message}/>; } if (this.usages !== undefined && this.usages.length <= 0) { return (<i> No usages for material '{this.name}' found.</i>); } const data: m.Child[][] = []; if (this.usages !== undefined) { data.push(...this.usages .map((pipeline: string, index) => { return [ <span>{pipeline}</span>, <Link href={SparkRoutes.pipelineEditPath('pipelines', pipeline, 'materials')} target={"_blank"} dataTestId={`material-link-${index}`}>View/Edit Material</Link> ]; })); } return <div class={styles.usages}> <Table headers={["Pipeline", "Material Setting"]} data={data}/> </div>; } private fetchUsages(material: MaterialWithFingerprint) { this.modalState = ModalState.LOADING; MaterialAPIs.usages(material.fingerprint()) .then((result) => { result.do((successResponse) => { this.usages = successResponse.body; }, (errorResponse) => { this.message.alert(JSON.parse(errorResponse.body!).message); }); }).finally(() => this.modalState = ModalState.OK); } } interface EllipseAttrs { text: string; } interface EllipseState { expanded: Stream<boolean>; setExpandedTo: (state: boolean, e: MouseEvent) => void; } class CommentRenderer extends MithrilComponent<EllipseAttrs, EllipseState> { private static MIN_CHAR_COUNT = 73; oninit(vnode: m.Vnode<EllipseAttrs, EllipseState>): any { vnode.state.expanded = Stream<boolean>(false); vnode.state.setExpandedTo = (state: boolean) => { vnode.state.expanded(state); }; } view(vnode: m.Vnode<EllipseAttrs, EllipseState>): m.Children | void | null { const charactersToShow = Math.min(this.getCharCountToShow(vnode), vnode.attrs.text.length); if (this.shouldRenderWithoutEllipse(vnode)) { return <span>{vnode.attrs.text}</span>; } return <span class={classnames(styles.ellipseWrapper, styles.comment)} data-test-id="ellipsized-content"> {vnode.state.expanded() ? vnode.attrs.text : CommentRenderer.getEllipsizedString(vnode, charactersToShow)} {vnode.state.expanded() ? CommentRenderer.element(vnode, "less", false) : CommentRenderer.element(vnode, "more", true)} </span>; } private static getEllipsizedString(vnode: m.Vnode<EllipseAttrs, EllipseState>, charactersToShow: number) { return vnode.attrs.text.substr(0, charactersToShow).concat("..."); } private static element(vnode: m.Vnode<EllipseAttrs, EllipseState>, text: string, state: boolean) { return <span data-test-id={`ellipse-action-${text}`} class={styles.ellipsisActionButton} onclick={vnode.state.setExpandedTo.bind(this, state)}>{text}</span>; } private getCharCountToShow(vnode: m.Vnode<EllipseAttrs, EllipseState>) { return (vnode.attrs.text.includes('\n') ? Math.min(vnode.attrs.text.indexOf('\n'), CommentRenderer.MIN_CHAR_COUNT) : CommentRenderer.MIN_CHAR_COUNT); } private shouldRenderWithoutEllipse(vnode: m.Vnode<EllipseAttrs, EllipseState>) { return vnode.attrs.text.length <= CommentRenderer.MIN_CHAR_COUNT && !vnode.attrs.text.includes('\n'); } }
the_stack
import { expect } from "chai"; import { Guid, Id64 } from "@itwin/core-bentley"; import { LineString3d, Loop, Point3d } from "@itwin/core-geometry"; import { AreaPattern, Code, ColorDef, GeometricElement3dProps, GeometryParams, GeometryPartProps, GeometryStreamBuilder, GeometryStreamIterator, IModel, } from "@itwin/core-common"; import { GenericSchema, GeometricElement3d, GeometryPart, PhysicalModel, PhysicalObject, PhysicalPartition, RenderMaterialElement, SnapshotDb, SpatialCategory, SubCategory, SubjectOwnsPartitionElements, } from "../../core-backend"; import { IModelTestUtils } from "../IModelTestUtils"; // The only geometry in our geometry streams will be squares of 1 meter in x and y, with origin at (pos, 0, 0). interface Primitive { pos: number } interface PartRef { partId: string; origin?: number; // origin in X. y and z are zero. } interface Symbology { categoryId?: string; subCategoryId?: string; color?: ColorDef; materialId?: string; patternOrigin?: number; } function makeGeomParams(symb: Symbology): GeometryParams { const params = new GeometryParams(symb.categoryId ?? Id64.invalid, symb.subCategoryId); params.lineColor = symb.color; params.materialId = symb.materialId; if (symb.patternOrigin) params.pattern = AreaPattern.Params.fromJSON({ origin: [symb.patternOrigin, 0, 0] }); return params; } interface AppendSubRanges { appendSubRanges: true } type UnionMember<T, U> = T & { [k in keyof U]?: never }; type GeomWriterEntry = UnionMember<PartRef, Symbology & Primitive & AppendSubRanges> | UnionMember<Symbology, PartRef & Primitive & AppendSubRanges> | UnionMember<Primitive, PartRef & Symbology & AppendSubRanges> | UnionMember<AppendSubRanges, Symbology & Primitive & PartRef>; class GeomWriter { public readonly builder: GeometryStreamBuilder; public constructor(symbology?: Symbology) { this.builder = new GeometryStreamBuilder(); if (symbology) this.append(symbology); } public append(entry: GeomWriterEntry): void { if (entry.partId) this.builder.appendGeometryPart3d(entry.partId, new Point3d(entry.origin, 0, 0)); else if (entry.subCategoryId || entry.categoryId || entry.color || entry.materialId || entry.patternOrigin) this.builder.appendGeometryParamsChange(makeGeomParams(entry)); else if (undefined !== entry.pos) this.builder.appendGeometry(Loop.createPolygon([new Point3d(entry.pos, 0, 0), new Point3d(entry.pos + 1, 0, 0), new Point3d(entry.pos + 1, 1, 0), new Point3d(entry.pos, 1, 0)])); else if (undefined !== entry.appendSubRanges) this.builder.appendGeometryRanges(); } } // SubGraphicRange where x dimension is 1 meter and y and z are empty. interface SubRange { low: number } type GeomStreamEntry = UnionMember<PartRef, Symbology & SubRange & Primitive> | UnionMember<Symbology, PartRef & SubRange & Primitive> | UnionMember<SubRange, PartRef & Symbology & Primitive> | UnionMember<Primitive, PartRef & Symbology & SubRange>; function readGeomStream(iter: GeometryStreamIterator): GeomStreamEntry[] & { viewIndependent: boolean } { const result: GeomStreamEntry[] = []; for (const entry of iter) { const symb: Symbology = { categoryId: entry.geomParams.categoryId, subCategoryId: entry.geomParams.subCategoryId }; if (undefined !== entry.geomParams.lineColor) symb.color = entry.geomParams.lineColor; if (undefined !== entry.geomParams.materialId) symb.materialId = entry.geomParams.materialId; if (entry.geomParams.pattern) { expect(entry.geomParams.pattern.origin).not.to.be.undefined; symb.patternOrigin = entry.geomParams.pattern.origin!.x; } result.push(symb); if (entry.localRange) { expect(entry.localRange.low.y).to.equal(0); expect(entry.localRange.low.z).to.equal(0); expect(entry.localRange.high.y).to.equal(1); expect(entry.localRange.high.z).to.equal(0); expect(entry.localRange.high.x - entry.localRange.low.x).to.equal(1); result.push({ low: entry.localRange.low.x }); } if (entry.primitive.type === "geometryQuery") { expect(entry.primitive.geometry.geometryCategory).to.equal("curveCollection"); if (entry.primitive.geometry.geometryCategory === "curveCollection") { expect(entry.primitive.geometry.children!.length).to.equal(1); expect(entry.primitive.geometry.children![0]).instanceOf(LineString3d); const pts = (entry.primitive.geometry.children![0] as LineString3d).points; expect(pts.length).to.equal(5); expect(pts[1].x).to.equal(pts[0].x + 1); result.push({ pos: pts[0].x }); } } else { expect(entry.primitive.type).to.equal("partReference"); if (entry.primitive.type === "partReference") { const partRef: PartRef = { partId: entry.primitive.part.id }; if (entry.primitive.part.toLocal) partRef.origin = entry.primitive.part.toLocal.origin.x; result.push(partRef); } } } (result as any).viewIndependent = iter.isViewIndependent; return result as GeomStreamEntry[] & { viewIndependent: boolean }; } describe("DgnDb.inlineGeometryPartReferences", () => { let imodel: SnapshotDb; let modelId: string; let categoryId: string; let blueSubCategoryId: string; let redSubCategoryId: string; let materialId: string; beforeEach(() => { imodel = SnapshotDb.createEmpty(IModelTestUtils.prepareOutputFile("InlineGeomParts", `${Guid.createValue()}.bim`), { rootSubject: { name: "InlineGeomParts", description: "InlineGeomParts" }, }); GenericSchema.registerSchema(); const partitionId = imodel.elements.insertElement({ classFullName: PhysicalPartition.classFullName, model: IModel.repositoryModelId, parent: new SubjectOwnsPartitionElements(IModel.rootSubjectId), code: PhysicalPartition.createCode(imodel, IModel.rootSubjectId, `PhysicalPartition_${Guid.createValue()}`), }); expect(Id64.isValidId64(partitionId)).to.be.true; const model = imodel.models.createModel({ classFullName: PhysicalModel.classFullName, modeledElement: { id: partitionId }, }); expect(model).instanceOf(PhysicalModel); modelId = imodel.models.insertModel(model.toJSON()); expect(Id64.isValidId64(modelId)).to.be.true; categoryId = SpatialCategory.insert(imodel, IModel.dictionaryId, "ctgry", { color: ColorDef.blue.toJSON() }); expect(Id64.isValidId64(categoryId)).to.be.true; blueSubCategoryId = IModel.getDefaultSubCategoryId(categoryId); redSubCategoryId = SubCategory.insert(imodel, categoryId, "red", { color: ColorDef.red.toJSON() }); expect(Id64.isValidId64(redSubCategoryId)).to.be.true; materialId = RenderMaterialElement.insert(imodel, IModel.dictionaryId, "mat", { paletteName: "pal" }); expect(Id64.isValidId64(materialId)).to.be.true; }); afterEach(() => { imodel.close(); }); function insertGeometryPart(geom: GeomWriterEntry[]): string { const writer = new GeomWriter(); for (const entry of geom) writer.append(entry); const props: GeometryPartProps = { classFullName: GeometryPart.classFullName, model: IModel.dictionaryId, code: GeometryPart.createCode(imodel, IModel.dictionaryId, Guid.createValue()), geom: writer.builder.geometryStream, }; const partId = imodel.elements.insertElement(props); expect(Id64.isValidId64(partId)).to.be.true; return partId; } function insertElement(geom: GeomWriterEntry[], viewIndependent = false): string { const writer = new GeomWriter({ categoryId }); if (viewIndependent) writer.builder.isViewIndependent = true; for (const entry of geom) writer.append(entry); const props: GeometricElement3dProps = { classFullName: PhysicalObject.classFullName, model: modelId, code: Code.createEmpty(), category: categoryId, geom: writer.builder.geometryStream, placement: { origin: [0, 0, 0], angles: { }, }, }; const elemId = imodel.elements.insertElement(props); expect(Id64.isValidId64(elemId)).to.be.true; return elemId; } function readElementGeom(id: string): GeomStreamEntry[] & { viewIndependent: boolean } { let iter; const elem = imodel.elements.getElement({ id, wantGeometry: true }); if (elem instanceof GeometryPart) { iter = GeometryStreamIterator.fromGeometryPart(elem); } else { expect(elem).instanceOf(GeometricElement3d); iter = GeometryStreamIterator.fromGeometricElement3d(elem as GeometricElement3d); } return readGeomStream(iter); } function expectGeom(actual: GeomStreamEntry[], expected: GeomStreamEntry[]): void { expect(actual).to.deep.equal(expected); } function inlinePartRefs(): number { const result = imodel.nativeDb.inlineGeometryPartReferences(); expect(result.numCandidateParts).to.equal(result.numPartsDeleted); expect(result.numRefsInlined).to.equal(result.numCandidateParts); return result.numRefsInlined; } it("inlines and deletes a simple unique part reference", () => { // Create single reference to a part and perform sanity checks on our geometry validation code. const partId = insertGeometryPart([{ pos: 123 }]); expectGeom(readElementGeom(partId), [ { categoryId: "0", subCategoryId: "0" }, { pos: 123 }, ]); const elemId = insertElement([{ partId }]); expectGeom(readElementGeom(elemId), [ { categoryId, subCategoryId: blueSubCategoryId }, { partId }, ]); // Inline and delete the part. expect(inlinePartRefs()).to.equal(1); expect(imodel.elements.tryGetElement(partId)).to.be.undefined; const geom = readElementGeom(elemId); expect(geom.viewIndependent).to.be.false; expectGeom(geom, [ { categoryId, subCategoryId: blueSubCategoryId }, { low: 123 }, { pos: 123 }, ]); }); it("inlines and deletes unique parts, ignoring non-unique parts", () => { const part1 = insertGeometryPart([{ pos: 1 }]); const part2 = insertGeometryPart([{ pos: 2 }]); const part3 = insertGeometryPart([{ pos: 3 }]); const part4 = insertGeometryPart([{ pos: 4 }]); const elem1 = insertElement([{ partId: part1 }]); const elem2 = insertElement([{ partId: part2 }, { partId: part3 }]); const elem3 = insertElement([{ partId: part3 }]); const elem4 = insertElement([{ partId: part4 }]); const elem5 = insertElement([{ partId: part4 }]); expect(inlinePartRefs()).to.equal(2); const symb = { categoryId, subCategoryId: blueSubCategoryId }; expectGeom(readElementGeom(elem1), [symb, { low: 1 }, { pos: 1 }]); expectGeom(readElementGeom(elem2), [symb, { low: 2 }, { pos: 2 }, symb, { partId: part3 }]); expectGeom(readElementGeom(elem3), [symb, { partId: part3 }]); expectGeom(readElementGeom(elem4), [symb, { partId: part4 }]); expectGeom(readElementGeom(elem5), [symb, { partId: part4 }]); }); it("applies part transform", () => { const partId = insertGeometryPart([{ pos: -8 }]); const elemId = insertElement([{ partId, origin: 50 }]); expect(inlinePartRefs()).to.equal(1); expectGeom(readElementGeom(elemId), [ { categoryId, subCategoryId: blueSubCategoryId }, { low: 42 }, { pos: 42 }, ]); }); it("applies element symbology to part and resets element symbology after embedding part", () => { const part1 = insertGeometryPart([ { pos: 1 }, { color: ColorDef.green }, { pos: 1.5}, ]); const part2 = insertGeometryPart([ { pos: 2 }, { materialId }, { pos: 2.5 }, ]); // Sanity check. expectGeom(readElementGeom(part2), [ { categoryId: "0", subCategoryId: "0" }, { pos: 2 }, { categoryId: "0", subCategoryId: "0", materialId }, { pos: 2.5 }, ]); const part3 = insertGeometryPart([ { pos: 3 }, { materialId: "0" }, { pos: 3.5 }, ]); const elemId = insertElement([ { pos: -1 }, { subCategoryId: redSubCategoryId }, { partId: part1 }, { pos: -2 }, { color: ColorDef.black }, { partId: part2 }, { pos: -3 }, { materialId, color: ColorDef.white }, { partId: part3 }, { pos: -4 }, ]); expect(inlinePartRefs()).to.equal(3); expectGeom(readElementGeom(elemId), [ { categoryId, subCategoryId: blueSubCategoryId }, { pos: -1 }, { categoryId, subCategoryId: redSubCategoryId }, { low: 1}, { pos: 1 }, { categoryId, subCategoryId: redSubCategoryId, color: ColorDef.green }, { low: 1.5 }, { pos: 1.5 }, { categoryId, subCategoryId: redSubCategoryId }, { low: -2 }, { pos: -2 }, { categoryId, subCategoryId: redSubCategoryId, color: ColorDef.black }, { low: 2 }, { pos: 2 }, { categoryId, subCategoryId: redSubCategoryId, materialId }, { low: 2.5 }, { pos: 2.5 }, { categoryId, subCategoryId: redSubCategoryId, color: ColorDef.black }, { low: -3 }, { pos: -3 }, { categoryId, subCategoryId: redSubCategoryId, color: ColorDef.white, materialId }, { low: 3 }, { pos: 3 }, { categoryId, subCategoryId: redSubCategoryId, materialId: "0" }, { low: 3.5 }, { pos: 3.5 }, {categoryId, subCategoryId: redSubCategoryId, color: ColorDef.white, materialId }, { low: -4 }, { pos: -4 }, ]); }); it("inserts subgraphic ranges for parts", () => { const part1 = insertGeometryPart([{ pos: 1 }]); const part2 = insertGeometryPart([{ pos: 2 }]); const elem = insertElement([ { pos: -1 }, { partId: part1 }, { partId: part2, origin: 5 }, ]); expect(inlinePartRefs()).to.equal(2); expectGeom(readElementGeom(elem), [ { categoryId, subCategoryId: blueSubCategoryId }, { pos: -1 }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 1 }, { pos: 1 }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 7 }, { pos: 7 }, ]); }); it("preserves existing subgraphic ranges", () => { const partId = insertGeometryPart([{ pos: 0 }]); const elem = insertElement([ { appendSubRanges: true }, { pos: -1 }, { partId }, { pos: 1 }, ]); expectGeom(readElementGeom(elem), [ { categoryId, subCategoryId: blueSubCategoryId }, { low: -1 }, { pos: -1 }, { categoryId, subCategoryId: blueSubCategoryId }, { partId }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 1 }, { pos: 1 }, ]); expect(inlinePartRefs()).to.equal(1); expectGeom(readElementGeom(elem), [ { categoryId, subCategoryId: blueSubCategoryId }, { low: -1 }, { pos: -1 }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 0 }, { pos: 0 }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 1 }, { pos: 1 }, ]); }); it("inserts subgraphic ranges geometry following part", () => { const partId = insertGeometryPart([{ pos: 1 }]); const elem = insertElement([ { pos: 0 }, { partId }, { pos: 2 }, ]); expect(inlinePartRefs()).to.equal(1); expectGeom(readElementGeom(elem), [ { categoryId, subCategoryId: blueSubCategoryId }, { pos: 0 }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 1 }, { pos: 1 }, { categoryId, subCategoryId: blueSubCategoryId }, { low: 2 }, { pos: 2 }, ]); }); it("applies transform to patterns", () => { const part1 = insertGeometryPart([{ pos: 1 }]); const part2 = insertGeometryPart([{ patternOrigin: 123 }, { pos: 2 }]); expectGeom(readElementGeom(part2), [ { categoryId: "0", subCategoryId: "0", patternOrigin: 123 }, { pos: 2 }, ]); const elemId = insertElement([ { patternOrigin: 456 }, { pos: -1 }, { partId: part1, origin: 8 }, { pos: -2 }, { partId: part2, origin: 12 }, { pos: -3 }, ]); expectGeom(readElementGeom(elemId), [ { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { pos: -1 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { partId: part1, origin: 8 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { pos: -2 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { partId: part2, origin: 12 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { pos: -3 }, ]); expect(inlinePartRefs()).to.equal(2); expectGeom(readElementGeom(elemId), [ { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { pos: -1 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { low: 1 + 8 }, { pos: 1 + 8 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { low: -2 }, { pos: -2 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 123 + 12 }, { low: 2 + 12 }, { pos: 2 + 12 }, { categoryId, subCategoryId: blueSubCategoryId, patternOrigin: 456 }, { low: -3 }, { pos: -3 }, ]); }); it("preserves element header flags", () => { const partId = insertGeometryPart([{ pos: 1 }]); const elemId = insertElement([{ partId }], true); expect(readElementGeom(elemId).viewIndependent).to.be.true; expect(inlinePartRefs()).to.equal(1); expect(readElementGeom(elemId).viewIndependent).to.be.true; }); });
the_stack
import * as cp from 'child_process'; import * as util from 'util'; /* vscode"stdlib" */ import * as vscode from 'vscode'; /* local */ import * as utilAnsibleCfg from './utils/ansibleCfg'; const execAsync = util.promisify(cp.exec); enum MultilineStyle { Literal = '|', Folding = '>', } enum ChompingStyle { Strip = '-', Keep = '+', } async function askForVaultId(ansibleCfg: utilAnsibleCfg.AnsibleVaultConfig) { const vaultId = 'default'; const identityList = ansibleCfg.defaults?.vault_identity_list ?.split(',') .map((id: string) => id.split('@', 2)[0].trim()); if (!identityList) { return undefined; } if (identityList.length === 1) { return identityList[0]; } const chosenVault = await vscode.window.showQuickPick(identityList); return chosenVault || vaultId; } function displayInvalidConfigError(): void { vscode.window.showErrorMessage( 'no valid ansible vault config found, cannot de/-encrypt' ); } function ansibleVaultPath(config: vscode.WorkspaceConfiguration): string { return `${config.ansible.path || 'ansible' }-vault` } export const toggleEncrypt = async (): Promise<void> => { const editor = vscode.window.activeTextEditor; if (!editor) { return; } const selection = editor.selection; if (!selection) { return; } const config = vscode.workspace.getConfiguration('ansible'); const doc = editor.document; // Read `ansible.cfg` or environment variable const rootPath: string | undefined = utilAnsibleCfg.getRootPath( editor.document.uri ); const ansibleConfig = await utilAnsibleCfg.getAnsibleCfg(rootPath); if (!ansibleConfig) { displayInvalidConfigError(); return; } // Extract `ansible-vault` password console.log(`Getting vault keyfile from ${ansibleConfig.path}`); vscode.window.showInformationMessage( `Getting vault keyfile from ${ansibleConfig.path}` ); const text = editor.document.getText(selection); const useVaultIDs = !!ansibleConfig.defaults.vault_identity_list; // Go encrypt / decrypt if (!!text) { const type = getInlineTextType(text); const indentationLevel = getIndentationLevel(editor, selection); const tabSize = Number(editor.options.tabSize); if (type === 'plaintext') { console.log('Encrypt selected text'); const vaultId: string | undefined = useVaultIDs ? await askForVaultId(ansibleConfig) : undefined; if (useVaultIDs && !vaultId) { displayInvalidConfigError(); return; } let encryptedText: string; try { encryptedText = await encryptInline( text, rootPath, vaultId, indentationLevel, tabSize, config ); } catch (e) { vscode.window.showErrorMessage(`Inline encryption failed: ${e}`); return; } const leadingSpaces = ' '.repeat((indentationLevel + 1) * tabSize); editor.edit((editBuilder) => { editBuilder.replace( selection, encryptedText.replace(/\n\s*/g, `\n${leadingSpaces}`) ); }); } else if (type === 'encrypted') { console.log('Decrypt selected text'); let decryptedText: string; try { decryptedText = await decryptInline( text, rootPath, indentationLevel, tabSize, // tabSize is always defined config ); } catch (e) { vscode.window.showErrorMessage(`Inline decryption failed: ${e}`); return; } editor.edit((editBuilder) => { editBuilder.replace(selection, decryptedText); }); } } else { const document = await vscode.workspace.openTextDocument(doc.fileName); const type = getTextType(document.getText()); if (type === 'plaintext') { console.log('Encrypt entire file'); const vaultId: string | undefined = useVaultIDs ? await askForVaultId(ansibleConfig) : undefined; if (useVaultIDs && !vaultId) { displayInvalidConfigError(); return; } vscode.window.activeTextEditor?.document.save(); try { await encryptFile(doc.fileName, rootPath, vaultId, config); vscode.window.showInformationMessage( `File encrypted: '${doc.fileName}'` ); } catch (e) { vscode.window.showErrorMessage( `Encryption of ${doc.fileName} failed: ${e}` ); } } else if (type === 'encrypted') { console.log('Decrypt entire file'); vscode.window.activeTextEditor?.document.save(); try { await decryptFile(doc.fileName, rootPath, config); vscode.window.showInformationMessage( `File decrypted: '${doc.fileName}'` ); } catch (e) { vscode.window.showErrorMessage( `Decryption of ${doc.fileName} failed: ${e}` ); } } vscode.commands.executeCommand('workbench.action.files.revert'); } }; // Returns whether the selected text is encrypted or in plain text. const getInlineTextType = (text: string) => { if (text.trim().startsWith('!vault |')) { text = text.replace('!vault |', ''); } return text.trim().startsWith('$ANSIBLE_VAULT;') ? 'encrypted' : 'plaintext'; }; // Returns whether the file is encrypted or in plain text. const getTextType = (text: string) => { return text.indexOf('$ANSIBLE_VAULT;') === 0 ? 'encrypted' : 'plaintext'; }; const encryptInline = async ( text: string, rootPath: string | undefined, vaultId: string | undefined, indentationLevel: number, tabSize = 0, config: vscode.WorkspaceConfiguration ) => { const encryptedText = await encryptText( handleMultiline(text, indentationLevel, tabSize), rootPath, vaultId, config ); console.debug(`encryptedText == '${encryptedText}'`); return encryptedText?.trim(); }; const decryptInline = async ( text: string, rootPath: string | undefined, indentationLevel: number, tabSize = 0, config: vscode.WorkspaceConfiguration ) => { // Delete inline vault prefix, then trim spaces and newline from the entire string and, at last, trim the spaces in the multiline string. text = text .replace('!vault |', '') .trim() .replace(/[^\S\r\n]+/gm, ''); const decryptedText = reindentText( await decryptText(text, rootPath, config), indentationLevel, tabSize ); return decryptedText; }; const pipeTextThrougCmd = ( text: string, rootPath: string | undefined, cmd: string ): Promise<string> => { return new Promise<string>((resolve, reject) => { const child = !!rootPath ? cp.exec(cmd, { cwd: rootPath }) : cp.exec(cmd); child.stdout?.setEncoding('utf8'); let outputText = ''; let errorText = ''; if (!child?.stdin || !child?.stdout || !child?.stderr) { return undefined; } child.stdout.on('data', (data) => (outputText += data)); child.stderr.on('data', (data) => (errorText += data)); child.on('close', (code) => { if (code !== 0) { console.log(`error when running ansible-vault: ${errorText}`); reject(errorText); } else { resolve(outputText); } }); child.stdin?.write(text); child.stdin?.end(); }); }; const encryptText = ( text: string, rootPath: string | undefined, vaultId: string | undefined, config: vscode.WorkspaceConfiguration ): Promise<string> => { const cmd = !!vaultId ? `${ansibleVaultPath(config)} encrypt_string --encrypt-vault-id="${vaultId}"` : `${ansibleVaultPath(config)} encrypt_string`; return pipeTextThrougCmd(text, rootPath, cmd); }; const decryptText = ( text: string, rootPath: string | undefined, config: vscode.WorkspaceConfiguration ): Promise<string> => { const cmd = `${ansibleVaultPath(config)} decrypt`; return pipeTextThrougCmd(text, rootPath, cmd); }; const encryptFile = ( f: string, rootPath: string | undefined, vaultId: string | undefined, config: vscode.WorkspaceConfiguration ) => { console.log(`Encrypt file: ${f}`); const cmd = !!vaultId ? `${ansibleVaultPath(config)} encrypt --encrypt-vault-id="${vaultId}" "${f}"` : `${ansibleVaultPath(config)} encrypt "${f}"`; return execCwd(cmd, rootPath); }; const decryptFile = ( f: string, rootPath: string | undefined, config: vscode.WorkspaceConfiguration ) => { console.log(`Decrypt file: ${f}`); const cmd = `${ansibleVaultPath(config)} decrypt "${f}"`; return execCwd(cmd, rootPath); }; const exec = (cmd: string, opt = {}) => { console.log(`> ${cmd}`); return execAsync(cmd, opt); }; const execCwd = (cmd: string, cwd: string | undefined) => { if (!cwd) { return exec(cmd); } return exec(cmd, { cwd: cwd }); }; const getIndentationLevel = ( editor: vscode.TextEditor, selection: vscode.Selection ): number => { if (!editor.options.tabSize) { // according to VS code docs, tabSize is always defined when getting options of an editor throw new Error( 'The `tabSize` option is not defined, this should never happen.' ); } const startLine = editor.document.lineAt(selection.start.line).text; const indentationMatches = startLine.match(/^\s*/); const leadingWhitespaces = indentationMatches?.[0]?.length || 0; return leadingWhitespaces / Number(editor.options.tabSize); }; const foldedMultilineReducer = ( accumulator: string, currentValue: string, currentIndex: number, array: string[] ): string => { if ( currentValue === '' || currentValue.match(/^\s/) || array[currentIndex - 1].match(/^\s/) ) { return `${accumulator}\n${currentValue}`; } if (accumulator.charAt(accumulator.length - 1) !== '\n') { return `${accumulator} ${currentValue}`; } return `${accumulator}${currentValue}`; }; const handleLiteralMultiline = ( lines: string[], leadingSpacesCount: number ) => { const text = prepareMultiline(lines, leadingSpacesCount).join('\n'); const chompingStyle = getChompingStyle(lines); if (chompingStyle === ChompingStyle.Strip) { return text.replace(/\n*$/, ''); } else if (chompingStyle === ChompingStyle.Keep) { return `${text}\n`; } else { return text.replace(/\n*$/, '\n'); } }; const handleFoldedMultiline = (lines: string[], leadingSpacesCount: number) => { const text = prepareMultiline(lines, leadingSpacesCount).reduce( foldedMultilineReducer ); const chompingStyle = getChompingStyle(lines); if (chompingStyle === ChompingStyle.Strip) { return text.replace(/\n*$/g, ''); } else if (chompingStyle === ChompingStyle.Keep) { return `${text}\n`; } else { return `${text.replace(/\n$/gm, '')}\n`; } }; const handleMultiline = ( text: string, indentationLevel: number, tabSize: number ) => { const lines = text.replace(/\r\n/g, '\n').split('\n'); if (lines.length > 1) { const leadingSpacesCount = (indentationLevel + 1) * tabSize; const multilineStyle = getMultilineStyle(lines); if (multilineStyle === MultilineStyle.Literal) { return handleLiteralMultiline(lines, leadingSpacesCount); } else if (multilineStyle === MultilineStyle.Folding) { return handleFoldedMultiline(lines, leadingSpacesCount); } else { throw new Error('this type of multiline text is not suppored'); } } return text; }; const reindentText = ( text: string, indentationLevel: number, tabSize: number ) => { const leadingSpacesCount = (indentationLevel + 1) * tabSize; const lines = text.split('\n'); let trailingNewlines = 0; for (const line of lines.reverse()) { if (line === '') { trailingNewlines++; } else { break; } } lines.reverse(); if (lines.length > 1) { const leadingWhitespaces = ' '.repeat(leadingSpacesCount); const rejoinedLines = lines .map((line) => `${leadingWhitespaces}${line}`) .join('\n'); rejoinedLines.replace(/\n$/, ''); if (trailingNewlines > 1) { return `${MultilineStyle.Literal}${ChompingStyle.Keep}\n${rejoinedLines}`; } else if (trailingNewlines === 0) { return `${MultilineStyle.Literal}${ChompingStyle.Strip}\n${rejoinedLines}`; } return `${MultilineStyle.Literal}\n${rejoinedLines}`; } return text; }; const prepareMultiline = (lines: string[], leadingSpacesCount: number) => { const re = new RegExp(`^\\s{${leadingSpacesCount}}`, ''); return lines.slice(1, lines.length).map((line) => line.replace(re, '')); }; function getMultilineStyle(lines: string[]) { return lines[0].charAt(0); } function getChompingStyle(lines: string[]) { return lines[0].charAt(1); }
the_stack
import { DestinyActivityModeType, DestinyStatsGroupType, PeriodType, DestinyComponentType } from './destiny2'; /** * Enum for the global alert level * @enum */ export enum GlobalAlertLevel { Unkown = 0, Blue = 1, Yellow = 2, Red = 3 } /** * Enum for the global alert type * @enum */ export enum GlobalAlertType { GlobalAlert = 0, StreamingAlert = 1 } /** * Enum for different stat IDs * @enum */ export enum StatId { ActivitiesClearedabilityKills = 'DestinyInventoryItemDefinition', ActivitiesEntered = 'ActivitiesEntered', ActivitiesWon = 'ActivitiesWon', Assists = 'Assists', AverageDeathDistance = 'AverageDeathDistance', AverageKillDistance = 'AverageKillDistance', AverageLifespan = 'AverageLifespan', AverageScorePerKill = 'AverageScorePerKill', AverageScorePerLife = 'AverageScorePerLife', BestSingleGameKills = 'BestSingleGameKills', BestSingleGameScore = 'BestSingleGameScore', Completed = 'Completed', FastestCompletionMsForActivity = 'FastestCompletionMsForActivity', ActivityCompletions = 'ActivityCompletions', ActivityDeaths = 'ActivityDeaths', ActivityKills = 'ActivityKills', ActivitySecondsPlayed = 'ActivitySecondsPlayed', ActivityWins = 'ActivityWins', ActivityGoalsMissed = 'ActivityGoalsMissed', ActivityCompletedFailures = 'ActivityCompletedFailures', ActivitySpecialActions = 'ActivitySpecialActions', ActivityBestGoalsHit = 'ActivityBestGoalsHit', ActivitySpecialScore = 'ActivitySpecialScore', ActivityFastestObjectiveCompletionMs = 'ActivityFastestObjectiveCompletionMs', ActivityBestSingleGameScore = 'ActivityBestSingleGameScore', ActivityKillsDeathsRatio = 'ActivityKillsDeathsRatio', ActivityKillsDeathsAssists = 'ActivityKillsDeathsAssists', Deaths = 'Deaths', Kills = 'Kills', KillsDeathsRatio = 'KillsDeathsRatio', KillsDeathsAssists = 'KillsDeathsAssists', LbSingleGameKills = 'LbSingleGameKills', LbPrecisionKills = 'LbPrecisionKills', LbAssists = 'LbAssists', LbDeaths = 'LbDeaths', LbKills = 'LbKills', LbObjectivesCompleted = 'LbObjectivesCompleted', LbSingleGameScore = 'LbSingleGameScore', MaximumPowerLevel = 'MaximumPowerLevel', MedalAbilityDawnbladeAerial = 'MedalAbilityDawnbladeAerial', MedalAbilityDawnbladeSlam = 'MedalAbilityDawnbladeSlam', MedalAbilityFlowwalkerMulti = 'MedalAbilityFlowwalkerMulti', MedalAbilityFlowwalkerQuick = 'MedalAbilityFlowwalkerQuick', MedalAbilityGunslingerMulti = 'MedalAbilityGunslingerMulti', MedalAbilityGunslingerQuick = 'MedalAbilityGunslingerQuick', MedalAbilityJuggernautCombo = 'MedalAbilityJuggernautCombo', MedalAbilityJuggernautSlam = 'MedalAbilityJuggernautSlam', MedalAbilityNightstalkerLongRange = 'MedalAbilityNightstalkerLongRange', MedalAbilityNightstalkerTetherQuick = 'MedalAbilityNightstalkerTetherQuick', MedalAbilitySentinelCombo = 'MedalAbilitySentinelCombo', MedalAbilitySentinelWard = 'MedalAbilitySentinelWard', MedalAbilityStormcallerLandfall = 'MedalAbilityStormcallerLandfall', MedalAbilityStormcallerMulti = 'MedalAbilityStormcallerMulti', MedalAbilitySunbreakerLongRange = 'MedalAbilitySunbreakerLongRange', MedalAbilitySunbreakerMulti = 'MedalAbilitySunbreakerMulti', MedalAbilityVoidwalkerDistance = 'MedalAbilityVoidwalkerDistance', MedalAbilityVoidwalkerVortex = 'MedalAbilityVoidwalkerVortex', MedalAvenger = 'MedalAvenger', MedalControlAdvantageHold = 'MedalControlAdvantageHold', MedalControlAdvantageStreak = 'MedalControlAdvantageStreak', MedalControlCaptureAllZones = 'MedalControlCaptureAllZones', MedalControlMostAdvantage = 'MedalControlMostAdvantage', MedalControlPerimeterKill = 'MedalControlPerimeterKill', MedalControlPowerPlayWipe = 'MedalControlPowerPlayWipe', MedalCountdownDefense = 'MedalCountdownDefense', MedalCountdownDefusedLastStand = 'MedalCountdownDefusedLastStand', MedalCountdownDefusedMulti = 'MedalCountdownDefusedMulti', MedalCountdownDetonated = 'MedalCountdownDetonated', MedalCountdownPerfect = 'MedalCountdownPerfect', MedalCountdownRoundAllAlive = 'MedalCountdownRoundAllAlive', MedalCycle = 'MedalCycle', MedalDefeatHunterDodge = 'MedalDefeatHunterDodge', MedalDefeatTitanBrace = 'MedalDefeatTitanBrace', MedalDefeatWarlockSigil = 'MedalDefeatWarlockSigil', MedalDefense = 'MedalDefense', MedalMatchBlowout = 'MedalMatchBlowout', MedalMatchComeback = 'MedalMatchComeback', MedalMatchMostDamage = 'MedalMatchMostDamage', MedalMatchNeverTrailed = 'MedalMatchNeverTrailed', MedalMatchOvertime = 'MedalMatchOvertime', MedalMatchUndefeated = 'MedalMatchUndefeated', MedalMulti2x = 'MedalMulti2x', MedalMulti3x = 'MedalMulti3x', MedalMulti4x = 'MedalMulti4x', MedalMultiEntireTeam = 'MedalMultiEntireTeam', MedalPayback = 'MedalPayback', MedalQuickStrike = 'MedalQuickStrike', MedalStreak10x = 'MedalStreak10x', MedalStreak5x = 'MedalStreak5x', MedalStreakAbsurd = 'MedalStreakAbsurd', MedalStreakCombined = 'MedalStreakCombined', MedalStreakShutdown = 'MedalStreakShutdown', MedalStreakTeam = 'MedalStreakTeam', MedalSuperShutdown = 'MedalSuperShutdown', MedalSupremacyCrestCreditStreak = 'MedalSupremacyCrestCreditStreak', MedalSupremacyFirstCrest = 'MedalSupremacyFirstCrest', MedalSupremacyNeverCollected = 'MedalSupremacyNeverCollected', MedalSupremacyPerfectSecureRate = 'MedalSupremacyPerfectSecureRate', MedalSupremacyRecoverStreak = 'MedalSupremacyRecoverStreak', MedalSupremacySecureStreak = 'MedalSupremacySecureStreak', MedalSurvivalComeback = 'MedalSurvivalComeback', MedalSurvivalKnockout = 'MedalSurvivalKnockout', MedalSurvivalQuickWipe = 'MedalSurvivalQuickWipe', MedalSurvivalTeamUndefeated = 'MedalSurvivalTeamUndefeated', MedalSurvivalUndefeated = 'MedalSurvivalUndefeated', MedalSurvivalWinLastStand = 'MedalSurvivalWinLastStand', MedalWeaponAuto = 'MedalWeaponAuto', MedalWeaponFusion = 'MedalWeaponFusion', MedalWeaponGrenade = 'MedalWeaponGrenade', MedalWeaponHandCannon = 'MedalWeaponHandCannon', MedalWeaponPulse = 'MedalWeaponPulse', MedalWeaponRocket = 'MedalWeaponRocket', MedalWeaponScout = 'MedalWeaponScout', MedalWeaponShotgun = 'MedalWeaponShotgun', MedalWeaponSidearm = 'MedalWeaponSidearm', MedalWeaponSmg = 'MedalWeaponSmg', MedalWeaponSniper = 'MedalWeaponSniper', MedalWeaponSword = 'MedalWeaponSword', MedalsUnknown = 'MedalsUnknown', AllMedalsScore = 'AllMedalsScore', AllMedalsEarned = 'AllMedalsEarned', ObjectivesCompleted = 'ObjectivesCompleted', PrecisionKills = 'PrecisionKills', ResurrectionsPerformed = 'ResurrectionsPerformed', ResurrectionsReceived = 'ResurrectionsReceived', Score = 'Score', SecondsPlayed = 'SecondsPlayed', ActivityDurationSeconds = 'ActivityDurationSeconds', Standing = 'ActivityDurationSeconds', Suicides = 'Suicides', Team = 'Team', TotalDeathDistance = 'TotalDeathDistance', TotalKillDistance = 'TotalKillDistance', WeaponPrecisionKillsAutoRifle = 'WeaponPrecisionKillsAutoRifle', WeaponPrecisionKillsFusionRifle = 'WeaponPrecisionKillsFusionRifle', WeaponPrecisionKillsGrenade = 'WeaponPrecisionKillsGrenade', WeaponPrecisionKillsHandCannon = 'WeaponPrecisionKillsHandCannon', WeaponPrecisionKillsMachinegun = 'WeaponPrecisionKillsMachinegun', WeaponPrecisionKillsMelee = 'WeaponPrecisionKillsMelee', WeaponPrecisionKillsPulseRifle = 'WeaponPrecisionKillsPulseRifle', WeaponPrecisionKillsRocketLauncher = 'WeaponPrecisionKillsRocketLauncher', WeaponPrecisionKillsScoutRifle = 'WeaponPrecisionKillsScoutRifle', WeaponPrecisionKillsShotgun = 'WeaponPrecisionKillsShotgun', WeaponPrecisionKillsSniper = 'WeaponPrecisionKillsSniper', WeaponPrecisionKillsSubmachinegun = 'WeaponPrecisionKillsSubmachinegun', WeaponPrecisionKillsSuper = 'WeaponPrecisionKillsSuper', WeaponPrecisionKillsRelic = 'WeaponPrecisionKillsRelic', WeaponPrecisionKillsSideArm = 'WeaponPrecisionKillsSideArm', WeaponKillsAutoRifle = 'WeaponKillsAutoRifle', WeaponKillsFusionRifle = 'WeaponKillsFusionRifle', WeaponKillsGrenade = 'WeaponKillsGrenade', WeaponKillsHandCannon = 'WeaponKillsHandCannon', WeaponKillsMachinegun = 'WeaponKillsMachinegun', WeaponKillsMelee = 'WeaponKillsMelee', WeaponKillsPulseRifle = 'WeaponKillsPulseRifle', WeaponKillsRocketLauncher = 'WeaponKillsRocketLauncher', WeaponKillsScoutRifle = 'WeaponKillsScoutRifle', WeaponKillsShotgun = 'WeaponKillsShotgun', WeaponKillsSniper = 'WeaponKillsSniper', WeaponKillsSubmachinegun = 'WeaponKillsSubmachinegun', WeaponKillsSuper = 'WeaponKillsSuper', WeaponKillsRelic = 'WeaponKillsRelic', WeaponKillsSideArm = 'WeaponKillsSideArm', WeaponKillsSword = 'WeaponKillsSword', WeaponKillsAbility = 'WeaponKillsAbility', WeaponBestType = 'WeaponBestType', WeaponKillsPrecisionKillsAutoRifle = 'WeaponKillsPrecisionKillsAutoRifle', WeaponKillsPrecisionKillsFusionRifle = 'WeaponKillsPrecisionKillsFusionRifle', WeaponKillsPrecisionKillsGrenade = 'WeaponKillsPrecisionKillsGrenade', WeaponKillsPrecisionKillsHandCannon = 'WeaponKillsPrecisionKillsHandCannon', WeaponKillsPrecisionKillsMachinegun = 'WeaponKillsPrecisionKillsMachinegun', WeaponKillsPrecisionKillsMelee = 'WeaponKillsPrecisionKillsMelee', WeaponKillsPrecisionKillsPulseRifle = 'WeaponKillsPrecisionKillsPulseRifle', WeaponKillsPrecisionKillsRocketLauncher = 'WeaponKillsPrecisionKillsRocketLauncher', WeaponKillsPrecisionKillsScoutRifle = 'WeaponKillsPrecisionKillsScoutRifle', WeaponKillsPrecisionKillsShotgun = 'WeaponKillsPrecisionKillsShotgun', WeaponKillsPrecisionKillsSniper = 'WeaponKillsPrecisionKillsSniper', WeaponKillsPrecisionKillsSubmachinegun = 'WeaponKillsPrecisionKillsSubmachinegun', WeaponKillsPrecisionKillsSuper = 'WeaponKillsPrecisionKillsSuper', WeaponKillsPrecisionKillsRelic = 'WeaponKillsPrecisionKillsRelic', WeaponKillsPrecisionKillsSideArm = 'WeaponKillsPrecisionKillsSideArm', WinLossRatio = 'WinLossRatio', UniqueWeaponAssists = 'UniqueWeaponAssists', UniqueWeaponAssistDamage = 'UniqueWeaponAssistDamage', UniqueWeaponKills = 'UniqueWeaponKills', UniqueWeaponPrecisionKills = 'UniqueWeaponPrecisionKills', UniqueWeaponKillsPrecisionKills = 'UniqueWeaponKillsPrecisionKills', AllParticipantsCount = 'AllParticipantsCount', AllParticipantsScore = 'AllParticipantsScore', AllParticipantsTimePlayed = 'AllParticipantsTimePlayed', ActivityAssists = 'ActivityAssists', CompletionReason = 'CompletionReason', FireteamId = 'FireteamId', LongestKillSpree = 'LongestKillSpree', LongestSingleLife = 'LongestSingleLife', MostPrecisionKills = 'MostPrecisionKills', OrbsDropped = 'OrbsDropped', OrbsGathered = 'OrbsGathered', StartSeconds = 'StartSeconds', TimePlayedSeconds = 'TimePlayedSeconds', PlayerCount = 'PlayerCount', ActivityPrecisionKills = 'ActivityPrecisionKills', PublicEventsCompleted = 'PublicEventsCompleted', PublicEventsJoined = 'PublicEventsJoined', RemainingTimeAfterQuitSeconds = 'RemainingTimeAfterQuitSeconds', TeamScore = 'TeamScore', TotalActivityDurationSeconds = 'TotalActivityDurationSeconds', DailyMedalsEarned = 'DailyMedalsEarned', CombatRating = 'CombatRating', LbMostPrecisionKills = 'LbMostPrecisionKills', LbLongestKillSpree = 'LbLongestKillSpree', LbLongestKillDistance = 'LbLongestKillDistance', LbFastestCompletionMs = 'LbFastestCompletionMs', LbLongestSingleLife = 'LbLongestSingleLife', FastestCompletionMs = 'FastestCompletionMs', LongestKillDistance = 'LongestKillDistance', HighestCharacterLevel = 'HighestCharacterLevel', HighestLightLevel = 'HighestLightLevel', HighestSandboxLevel = 'HighestSandboxLevel', SparksCaptured = 'SparksCaptured', SlamDunks = 'SlamDunks', StyleDunks = 'StyleDunks', DunkKills = 'DunkKills', CarrierKills = 'CarrierKills', ActivityGatesHit = 'ActivityGatesHit', RaceCompletionSeconds = 'RaceCompletionSeconds', GatesHit = 'GatesHit', RaceCompletionMilliseconds = 'RaceCompletionMilliseconds' } export enum TypeDefinition { DestinyActivityGraphDefinition = 'DestinyActivityGraphDefinition', DestinyActivityModeDefinition = 'DestinyActivityModeDefinition', DestinyActivityModifierDefinition = 'DestinyActivityModifierDefinition', DestinyActivityTypeDefinition = 'DestinyActivityTypeDefinition', DestinyBondDefinition = 'DestinyBondDefinition', DestinyClassDefinition = 'DestinyClassDefinition', DestinyDamageTypeDefinition = 'DestinyDamageTypeDefinition', DestinyDestinationDefinition = 'DestinyDestinationDefinition', DestinyEnemyRaceDefinition = 'DestinyEnemyRaceDefinition', DestinyFactionDefinition = 'DestinyFactionDefinition', DestinyGenderDefinition = 'DestinyGenderDefinition', DestinyHistoricalStatsDefinition = 'DestinyHistoricalStatsDefinition', DestinyInventoryBucketDefinition = 'DestinyInventoryBucketDefinition', DestinyInventoryItemDefinition = 'DestinyInventoryItemDefinition', DestinyItemCategoryDefinition = 'DestinyItemCategoryDefinition', DestinyItemTierTypeDefinition = 'DestinyItemTierTypeDefinition', DestinyLocationDefinition = 'DestinyLocationDefinition', DestinyLoreDefinition = 'DestinyLoreDefinition', DestinyMedalTierDefinition = 'DestinyMedalTierDefinition', DestinyMilestoneDefinition = 'DestinyMilestoneDefinition', DestinyObjectiveDefinition = 'DestinyObjectiveDefinition', DestinyPlaceDefinition = 'DestinyPlaceDefinition', DestinyProgressionDefinition = 'DestinyProgressionDefinition', DestinyProgressionLevelRequirementDefinition = 'DestinyProgressionLevelRequirementDefinition', DestinyRaceDefinition = 'DestinyRaceDefinition', DestinyRewardSourceDefinition = 'DestinyRewardSourceDefinition', DestinySackRewardItemListDefinition = 'DestinySackRewardItemListDefinition', DestinySandboxPerkDefinition = 'DestinySandboxPerkDefinition', DestinySocketCategoryDefinition = 'DestinySocketCategoryDefinition', DestinySocketTypeDefinition = 'DestinySocketTypeDefinition', DestinyStatDefinition = 'DestinyStatDefinition', DestinyStatGroupDefinition = 'DestinyStatGroupDefinition', DestinyTalentGridDefinition = 'DestinyTalentGridDefinition', DestinyUnlockDefinition = 'DestinyUnlockDefinition', DestinyVendorCategoryDefinition = 'DestinyVendorCategoryDefinition', DestinyVendorDefinition = 'DestinyVendorDefinition' } /** * Interface for defining an object for the Traveler class * @interface */ export interface TravelerConfig { apikey: string; userAgent: string; oauthClientId?: string; oauthClientSecret?: string; debug?: boolean; } export interface StreamInfo { ChannelName: string; } export interface GlobalAlert { AlertKey: string; AlertHtml: string; AlerTimestamp: Date; AlertLink: string; AlertLevel: GlobalAlertLevel; AlertType: GlobalAlertType; StreamInfo: StreamInfo; } export interface DictionaryResponse<S> { [key: string]: S; } /** * Interface for defining an object for the endpoint query strings * @interface */ export interface QueryStringParameters { components?: DestinyComponentType[]; modes?: DestinyActivityModeType[]; mode?: DestinyActivityModeType; maxtop?: number; statid?: string; page?: number; dayend?: string; daystart?: string; groups?: DestinyStatsGroupType[]; periodType?: PeriodType; count?: number; [key: string]: any; } /** * Interface for defining an object for the OAuth response * @interface */ export interface OAuthResponse { access_token: string; token_type: string; expires_in: number; refresh_token?: string; refresh_expires_in?: number; membership_id: string; }
the_stack
import { NVRAM } from "./nvram"; import * as resource from "./resource"; import { Buffer } from "buffer"; import * as drcs from "./drcs"; import { Interpreter } from "./interpreter/interpreter"; import { EventDispatcher, EventQueue } from "./event_queue"; import { Content } from "./content"; import { ResponseMessage } from "../server/ws_api"; import { playRomSound } from "./romsound"; import { AudioNodeProvider, Indicator, IP, Reg } from "./bml_browser"; import { decodeEUCJP, encodeEUCJP, stripStringEUCJP } from "./euc_jp"; // browser疑似オブジェクト export type LockedModuleInfo = [moduleName: string, func: number, status: number]; export interface Browser { // Ureg関連機能 Ureg: string[]; Greg: string[]; // EPG関連機能 epgGetEventStartTime(event_ref: string): Date | null; epgGetEventDuration(event_ref: string): number; epgTune(service_ref: string): number; epgTuneToComponent(component_ref: string): number; // epgTuneToDocument(documentName: string): number; epgIsReserved(event_ref: string, startTime?: Date): number; epgReserve(event_ref: string, startTime?: Date): number; epgCancelReservation(event_ref: string): string; epgRecIsReserved(event_ref: string, startTime?: Date): number; epgRecReserve(event_ref: string, startTime?: Date): number; epgRecCancelReservation(event_ref: string): number; setCurrentDateMode(time_mode: number): number; // 番組群インデックス関連機能 // 非運用 // シリーズ予約機能 // シリーズ予約機能をもつ受信機では実装することが望ましい。 // 永続記憶機能 // readPersistentString(filename: string): string; // readPersistentNumber(filename: string): number; readPersistentArray(filename: string, structure: string): any[] | null; // writePersistentString(filename: string, buf: string, period?: Date): number; // writePersistentNumber(filename: string, data: number, period?: Date): number; writePersistentArray(filename: string, structure: string, data: any[], period?: Date): number; // copyPersistent(srcUri: string, dstUri: string): number; // getPersistentInfoList(type: string): any[]; // deletePersistent(filename: string): number; // getFreeSpace(type: string): number; // 永続記憶機能-アクセス制御付領域の制御機能 // 非運用 // setAccessInfoOfPersistentArray(filename: string, permissionType: 1, permissionData: [original_network_id: string, transport_stream_id: string, service_id: string]): number; // setAccessInfoOfPersistentArray(filename: string, permissionType: number, permissionData: any[]): number; checkAccessInfoOfPersistentArray(filename: string): number; writePersistentArrayWithAccessCheck(filename: string, structure: string, data: any[], period?: Date): number; readPersistentArrayWithAccessCheck(filename: string, structure: string): any[] | null; // 双方向機能-遅延発呼 // 非運用 // 双方向機能-BASIC手順 非対応であればエラーを返すこと connect(tel: string, speed: number, timeout: number): number; connect(tel: string, hostNo: string, bProvider: boolean, speed: number, timeout: number): number; disconnect(): number; // sendBinaryData(uri: string, timeout: number): number; // receiveBinaryData(uri: string, timeout: number): number; sendTextData(text: string, timeout: number): number; receiveTextData(text: string, timeout: number): number; // 双方向機能-TCP/IP // 非対応であればエラーを返すこと setISPParams(ispname: string, tel: string, bProvider: boolean, uid: string, passwd: string, nameServer1: string, nameServer2: string, softCompression: boolean, headerCompression: boolean, idleTime: number, status: number, lineType?: number): number; getISPParams(): any[] | null; connectPPP(tel: string, bProvider: boolean, uid: string, passwd: string, nameServer1: string, nameServer2: string, softCompression: boolean, headerCompression: boolean, idleTime: number): number; connectPPPWithISPParams(idleTime?: number): number; disconnectPPP(): number; getConnectionType(): number; isIPConnected(): number; // async confirmIPNetwork(destination: string, confirmType: number, timeout?: number): [boolean, string | null, number | null] | null; // async transmitTextDataOverIP(uri: string, text: string, charset: string): [number, string, string]; // 非運用 // saveHttpServerFileAs // saveHttpServerFile // sendHttpServerFileAs // saveFtpServerFileAs // saveFtpServerFile // sendFtpServerFileAs // setDelayedTransmissionData // オプション sendTextMail(subject: string, body: string, toAddress: string, ...ccAddress: string[]): [number, number]; sendMIMEMail(subject: string, src_module: string, toAddress: string, ...ccAddress: string[]): [number, number]; setCacheResourceOverIP(resources: string[]): number; // 双方向機能-回線接続状態を取得する機能 // 非対応であれば[1]-[4]に空文字列を返すこと getPrefixNumber(): [number, string, string, string, string]; // 双方向機能-大量呼受付サービスを利用する通信機能 // 非対応であればエラーを返す vote(tel: string, timeout: number): number; // 双方向機能-CASを用いた暗号化通信のための機能 // startCASEncryption(provider: number, centerID: number): number; // endCASEncryption(): number; // transmitWithCASEncryption(sendData: string, timeout: number): any[]; // 双方向機能-CAS を用いない共通鍵暗号による通信 // 非運用 reloadActiveDocument(): number; getNPT(): number; getProgramRelativeTime(): number; isBeingBroadcast(event_ref: string): boolean; // lockExecution(): number; // unlockExecution(): number; lockModuleOnMemory(module: string | null | undefined): number unlockModuleOnMemory(module: string | null | undefined): number setCachePriority(module: string, priority: number): number; // getTuningLinkageSource(): string; // getTuningLinkageType(): number; // getLinkSourceServiceStr(): string; // getLinkSourceEventStr(): string; getIRDID(type: number): string | null; getBrowserVersion(): string[]; getProgramID(type: number): string | null; getActiveDocument(): string | null; lockScreen(): number; unlockScreen(): number; getBrowserSupport(sProvider: string, functionname: string, ...additionalinfo: string[]): number; launchDocument(documentName: string, transitionStyle?: string): number; // option // launchDocumentRestricted(documentName: string, transitionStyle: string): number; quitDocument(): number; // option // launchExApp(uriname: string, MIME_type?: string, ...Ex_info: string[]): number; getFreeContentsMemory(number_of_resource?: number): number; isSupportedMedia(mediaName: string): number; detectComponent(component_ref: string): number; lockModuleOnMemoryEx(module: string | null | undefined): number unlockModuleOnMemoryEx(module: string | null | undefined): number; unlockAllModulesOnMemory(): number; getLockedModuleInfo(): LockedModuleInfo[] | null; getBrowserStatus(sProvider: string, statusname: string, additionalinfo: string): number; getResidentAppVersion(appName: string): any[] | null; isRootCertificateExisting(root_certificate_type: number, root_certificate_id: number, root_certificate_version?: number): number; getRootCertificateInfo(): any[] | null; // option // startResidentApp(appName: string, showAV: number, returnURI: string, ...Ex_info: string[]): number; // startExtraBrowser(browserName: string, showAV: number, returnURI: string, uri: string): number; // transmitDataToSmartDevice(profile: string, data: string, additionalinfo?: string): number; // 受信機音声制御 playRomSound(soundID: string): number; // タイマ機能 // async sleep(interval: number): number | null; // setTimeout(func: string, interval: number): number; setInterval(func: string, interval: number, iteration: number): number; clearTimer(timerID: number): number; pauseTimer(timerID: number): number; resumeTimer(timerID: number): number; setCurrentDateMode(time_mode: number): number; // 外字機能 // async loadDRCS(DRCS_ref: string): number; // unloadDRCS(): number; // 外部機器制御機能 // 運用しない // その他の機能 random(num: number): number; subDate(target: Date, base: Date, unit: number): number; addDate(base: Date, time: number, unit: number): Date | number; formatNumber(value: number): string | null; // 字幕表示制御機能 // setCCStreamReference(stream_ref: string): number; // getCCStreamReference(): string | null; setCCDisplayStatus(language: number, status: boolean): number; getCCDisplayStatus(language: number): number; getCCLanguageStatus(language: number): number; // ディレクトリ操作関数 ファイル操作関数 ファイル入出力関数 // 非運用 // 問い合わせ関数 // 非運用/オプション // データカルーセル蓄積関数 // 非運用 // ブックマーク制御機能 writeBookmarkArray(filename: string, title: string, dstURI: string, expire_str: string, bmType: string, linkMedia: string, usageFlag: string, extendedStructure?: string, extendedData?: any[]): number; readBookmarkArray(filename: string, bmType?: string, extendedStructure?: string): any[] | null; deleteBookmark(filename: string): number; lockBookmark(filename: string): number; unlockBookmark(filename: string): number; getBookmarkInfo(): [number, number, string]; getBookmarkInfo2(region_name: string): [number, number, string]; // オプション // startResidentBookmarkList(): number; // 印刷 // オプション // IPTV連携機能 // オプション // AITコントロールドアプリケーション連携機能 // オプション // CS事業者専用領域に対する放送用拡張関数 (TR-B15 第四分冊) // async X_CSP_setAccessInfoToProviderArea(filename: string, structure: string): number; } export interface AsyncBrowser { loadDRCS(DRCS_ref: string): Promise<number>; transmitTextDataOverIP(uri: string, text: string, charset: string): Promise<[number, string, string]>; confirmIPNetwork(destination: string, confirmType: number, timeout?: number): Promise<[boolean, string | null, number | null] | null>; sleep(interval: number): Promise<number | null>; unlockScreen(): Promise<number>; X_CSP_setAccessInfoToProviderArea(filename: string, structure: string): Promise<number>; } const apiGroup: Map<string, number> = new Map([ ["Class.BinaryTable", 1], ["Class.CSVTable", 0], ["Class.XMLDoc", 0], ["EPG.Basic", 1], // FIXME: 未実装あり ["EPG.Basic2", 0], // FIXME: 未実装 ["EPG.Ext", 0], // epgTuneToDocument ["EPG.Group", 0], ["EPG.Series", 0], ["CC.Stream", 0], ["CC.Control", 0], // FIXME: 未実装 ["Persistent.Ext", 0], ["Persistent.Basic", 1], ["Persistent.MediaSupport", 1], // FIXME: setAccessInfoOfPersistentArray ["Storage.Dir.Dest", 0], ["Storage.Dir", 0], ["Storage.Dir.Ext", 0], ["Storage.File.Dest", 0], ["Storage.File", 0], ["Storage.File.Ext", 0], ["Storage.IO", 0], ["Storage.Basic", 0], ["Storage.Carousel", 0], ["Storage.Module", 0], ["Storage.Carousel.Ext", 0], ["Storage.Module.Ext", 0], ["Storage.Resource.Ext", 0], ["Storage.Resource", 0], ["Com.BASIC.Basic", 0], // FIXME: 対応は不可能だけどエラーを返すように実装すべき ["Com.BASIC.Ext", 0], ["Com.BASIC.Delay", 0], ["Com.BASIC.Delayed", 0], ["Com.BASIC.Vote", 0], // FIXME: 対応は不可能だけどエラーを返すように実装すべき ["Com.BASIC.CAS", 0], ["Com.BASIC.Enc", 0], ["Com.IP.Params", 0], // FIXME: 対応は不可能だけどエラーを返すように実装すべき ["Com.IP.Connect", 0], // FIXME: 対応は不可能だけどエラーを返すように実装すべき ["Com.IP.Connect.Ext", 0], // FIXME: 対応は不可能だけどエラーを返すように実装すべき ["Com.IP.GetType", 1], ["Com.IP", 1], ["Com.IP.Http.Ext", 0], ["Com.IP.Http", 0], ["Com.IP.Ftp.Ext", 0], ["Com.IP.Ftp", 0], ["Com.IP.Sendmail", 0], // FIXME? ["Com.IP.Transmit", 1], ["Com.IP.Delayed", 0], ["Com.IP.SetCache", 0], // FIXME? ["Com.IP.confirmIP", 1], ["Com.Common.Delayed", 0], ["Com.Line.Prefix", 0], // FIXME: 対応は不可能だけどエラーを返すように実装すべき ["Com.Certificate", 0], // FIXME ["Ctrl.Basic", 1], ["Ctrl.NPT", 1], // FIXME ["Ctrl.Time", 1], ["Ctrl.Exec", 0], ["Ctrl.Cache", 1], // FIXME: setCachePriority ["Ctrl.Link", 0], ["Ctrl.PgmHyperlink", 0], ["Ctrl.Version", 1], ["Ctrl.Screen", 1], ["Ctrl.Com", 0], // オプション扱い ["Ctrl.Quit", 0], // FIXME ["Ctrl.ExtApp", 0], // オプション扱い ["Ctrl.Cache.Ext", 0], // FIXME ["Ctrl.Media", 0], // FIXME ["Ctrl.Basic2", 1], ["Ctrl.Cache2", 1], ["Ctrl.MobileDisplay", 0], ["Ctrl.AppVersion", 1], ["Ctrl.startResidentApp", 0], ["Ctrl.startExtraBrowser", 0], ["Misc.SmartDevice.transmitData", 0], ["RomSound.Basic", 1], ["Timer.Basic", 1], ["Timer.Ext", 0], ["Timer.DateMode", 1], ["Misc.DRCS", 1], ["Misc.DRCS.unload", 0], ["Misc.Peripheral", 0], ["Misc.Peripheral.pass", 0], ["Misc.Peripheral.Array", 0], ["Bookmark.Basic", 0], // FIXME ["Bookmark.Extended", 0], // FIXME ["Bookmark.Resident", 0], ["Misc.Basic", 1], ["Misc.Ureg", 1], ["Misc.Greg", 1], ["Print.Basic", 0], ["Print.MemoryCard", 0], ["Iptv.Vod", 0], ["Iptv.Download", 0], ["AITControlledApp.Start", 0], // TR-B14 第二分冊 ["Bookmark.Basic2", 0], // getBookmarkInfo2 ["Ctrl.Status", 1], // getBrowserStatus ["Storage.Source", 0], // getContentSource ]); const residentApp = new Map<string, number>([ ["JapaneseInput", 0], ["netTVBrowser", 0], ["IPTVBMLBrowser", 0], ["VOD", 0], ["Download", 0], ["webBrowserMode1", 0], ["webBrowserMode2", 0], ["HTMLBrowser", 0], ["ReservedTransmission", 0], ["MailClient", 0], ["Bookmark", 0], ]); const transmissionProtocol = new Map<string, number | Map<string, number | Map<string | undefined, number>>>([ ["datalink", new Map<string, number>([["PPP.modem", 0]])], ["application", new Map<string, number | Map<string | undefined, number>>([ ["HTTP", new Map<string | undefined, number>([ [undefined, 1], ["1.0", 1], ["1.1", 1], ])], ["FTP", 0], ["TLS", new Map<string | undefined, number>([ [undefined, 1], ["1.0", 1], ["1.1", 1], ["1.2", 1], ["1.3", 1], ])], ["physical", new Map<string, number>([["basic", 0]])], ])], ]); const extraBrowserFunction = new Map<string, number>([ ["netTVVOD", 0], ["netTVDownload", 0], ["IPTVBMLVOD", 0], ["IPTVBMLDownload", 0], ]); const unsupported = new Map<string, number>([ ["Misc.Unlink", 1], // 非リンク状態未実装 ["Com.BASIC.Basic", 1], ["Com.BASIC.Vote", 0], ]); const caSystem = new Map<string, number>([ ["0x0005", 1], // [BA]-CAS番号 ["0x000D", 0], ]); const iptvFunction = new Map<string, number | Map<string, number>>([ ["VOD", new Map<string, number>([ ["HTTP", 0], ["RTSP", 0], ])], ]); const irdid = new Map<string, number>([ ["0xF001", 0], ]); const smartDeviceProfile = new Map<string, number>([ ["SmartDeviceMode1", 0], ["SmartDeviceMode2", 0], ]); const aitControlledAppEngineFunction = new Map([ ["IPTV-F", new Map([ // フェーズ0運用のみ実装 ["HTML5_ph0", 0], // フェーズ1運用を実装 ["HTML5_ph1", 0], ])] ]); const aitTransferMethod = new Map([ ["XML", new Map([ ["HTTP", 0], ])] ]); const aitTransportMethod = new Map([ ["XML", new Map([ ["HTTP", 0], ])], ["Section", new Map([ ["DataCarousel", 0], ])], ]); const nvram = new Map([ ["BSspecifiedExtension", new Map([["48", 1]])], ["NumberOfBSBroadcasters", new Map([["23", 1]])], ["NumberOfCSBroadcasters", new Map([["23", 1]])], ]); const characterEncoding = new Map([ ["Shift-JIS", 0], ["UTF-8", 0], ["UTF-16", 0], ["EUC-JP", 1], ["JIS8TEXT", 0], ]); const osdResolution = new Map([ ["1920x1080", 1], ["1280x720", 1], ["960x540", 1], ["720x480", 1], ]); const arib = new Map<string, any>([ ["APIGroup", apiGroup], ["ResidentApp", residentApp], ["TransmissionProtocol", transmissionProtocol], ["ExtraBrowserFunction", extraBrowserFunction], ["Unsupported", unsupported], ["CASystem", caSystem], ["IPTVFunction", iptvFunction], ["IRDID", irdid], ["SmartDeviceProfile", smartDeviceProfile], ["AITControlledAppEngineFunction", aitControlledAppEngineFunction], ["AITTransferMethod", aitTransferMethod], ["AITTransportMethod", aitTransportMethod], ["nvram", nvram], ["ResidentBookmark", 0], ["BookmarkButton", 0], ["KanaInput", 1], ["CharacterEncoding", characterEncoding], ["OSDResolution", osdResolution], ]); const bpa = new Map([ ["APIGroup", new Map([ ["Persistent.Media.Support.Ext", 0], // X_BPA_setAccessInfoOfPersistentArrayForAnotherProvider ])] ]); export class BrowserAPI { private readonly resources: resource.Resources; private readonly eventQueue: EventQueue; private readonly eventDispatcher: EventDispatcher; private readonly content: Content; private readonly nvram: NVRAM; private readonly interpreter: Interpreter; private readonly audioNodeProvider: AudioNodeProvider; private readonly ip: IP; private readonly indicator?: Indicator; private readonly ureg: Reg; private readonly greg: Reg; constructor( resources: resource.Resources, eventQueue: EventQueue, eventDispatcher: EventDispatcher, content: Content, nvram: NVRAM, interpreter: Interpreter, audioNodeProvider: AudioNodeProvider, ip: IP, indicator: Indicator | undefined, ureg: Reg | undefined, greg: Reg | undefined, ) { this.resources = resources; this.eventQueue = eventQueue; this.eventDispatcher = eventDispatcher; this.content = content; this.nvram = nvram; this.interpreter = interpreter; this.audioNodeProvider = audioNodeProvider; this.ip = ip; this.indicator = indicator; this.ureg = ureg ?? { getReg: (index) => this.browser.Ureg[index], setReg: (index, value) => this.browser.Ureg[index] = value, }; this.greg = greg ?? { getReg: (index) => this.browser.Greg[index], setReg: (index, value) => this.browser.Greg[index] = value, }; } asyncBrowser: AsyncBrowser = { loadDRCS: async (DRCS_ref: string): Promise<number> => { console.log("loadDRCS", DRCS_ref); const res = this.resources.fetchLockedResource(DRCS_ref) ?? await this.resources.fetchResourceAsync(DRCS_ref); if (res?.data == null) { return NaN; } for (const [id, fontFamily] of [ [1, "丸ゴシック"], [2, "角ゴシック"], [3, "太丸ゴシック"], ]) { const glyph = drcs.loadDRCS(Buffer.from(res.data), id as number); const { ttf, unicodeCharacters } = drcs.toTTF(glyph); if (unicodeCharacters.length === 0) { continue; } this.content.addDRCSFont(new FontFace(fontFamily as string, ttf, { unicodeRange: unicodeCharacters.map(x => "U+" + x.toString(16)).join(","), })); } return 1; }, transmitTextDataOverIP: async (uri: string, text: string, charset: string): Promise<[number, string, string]> => { console.info("transmitTextDataOverIP"); if (this.ip.transmitTextDataOverIP == null) { return [NaN, "", ""]; } function encodeBinary(data: Uint8Array): string { const encoded: string[] = []; for (const c of data) { const s = String.fromCharCode(c); if ((s >= "A" && s <= "Z") || (s >= "a" && s <= "z") || (s >= "0" && s <= "9") || "-_.!~*'()".indexOf(s) !== -1) { encoded.push(s); } else { encoded.push("%"); encoded.push(c.toString(16).padStart(2, "0")); } } return encoded.join(""); } if (charset === "EUC-JP") { this.indicator?.setNetworkingPostStatus(true); const { resultCode, statusCode, response } = await this.ip.transmitTextDataOverIP(uri, new TextEncoder().encode("Denbun=" + encodeBinary(encodeEUCJP(text)))); this.indicator?.setNetworkingPostStatus(false); return [resultCode, statusCode, decodeEUCJP(response)]; } else { return [NaN, "", ""]; } }, confirmIPNetwork: async (destination: string, confirmType: number, timeout?: number): Promise<[boolean, string | null, number | null] | null> => { console.info("confirmIPNetwork"); if (this.ip.confirmIPNetwork == null) { return null; } const result = await this.ip.confirmIPNetwork(destination, Number(confirmType) === 1, Number(timeout ?? 4000)); if (result == null) { return null; } return [result.success, result.ipAddress, result.responseTimeMillis]; }, sleep: async (interval: number): Promise<number | null> => { return new Promise<number | null>((resolve) => { console.log("SLEEP ", interval); setTimeout(() => { console.log("END SLEEP ", interval); resolve(1); }, interval); }); }, unlockScreen: async (): Promise<number> => { return new Promise<number>((resolve) => { requestAnimationFrame(() => { resolve(1); }); }); }, X_CSP_setAccessInfoToProviderArea: async (filename: string, structure: string): Promise<number> => { if (structure !== "S:1V,U:2B") { return NaN; } const res = await this.resources.fetchResourceAsync(filename) if (res?.data == null) { return NaN } else if (this.nvram.cspSetAccessInfoToProviderArea(res.data)) { return 1; } else { return NaN; } } }; public getGreg(index: number): string | undefined { if (index >= 0 && index < this.browser.Greg.length) { return this.greg.getReg(index); } else { return undefined; } } public setGreg(index: number, value: string) { if (index > 0 && index < this.browser.Greg.length) { this.greg.setReg(index, stripStringEUCJP(value, 256)); } } public getUreg(index: number): string | undefined { if (index >= 0 && index < this.browser.Ureg.length) { return this.ureg.getReg(index); } else { return undefined; } } public setUreg(index: number, value: string) { if (index > 0 && index < this.browser.Ureg.length) { this.ureg.setReg(index, stripStringEUCJP(value, 256)); } } browser: Browser = { Ureg: [...new Array(64)].map(_ => ""), Greg: [...new Array(64)].map(_ => ""), epgGetEventStartTime: (event_ref: string): Date | null => { if (event_ref == this.resources.eventURI) { console.log("epgGetEventStartTime", event_ref); const time = this.resources.startTimeUnixMillis; if (time == null) { return null; } return new Date(time); } console.error("epgGetEventStartTime: not implemented", event_ref, this.resources.eventId); return null; }, epgGetEventDuration: (event_ref: string): number => { if (event_ref == this.resources.eventURI) { console.log("epgGetEventDuration", event_ref); return this.resources.durationSeconds ?? NaN; } console.error("epgGetEventDuration", event_ref); return NaN; }, setCurrentDateMode: (time_mode: number): number => { console.log("setCurrentDateMode", time_mode); if (time_mode == 0) { this.content.currentDateMode = 0; } else if (time_mode == 1) { this.content.currentDateMode = 1; } else { return NaN; } return 1; // 成功 }, getProgramRelativeTime: (): number => { console.log("getProgramRelativeTime"); const ct = this.resources.currentTimeUnixMillis; const st = this.resources.startTimeUnixMillis; if (ct == null || st == null) { return NaN; } else { return Math.floor((ct - st) / 1000); // 秒 } }, subDate(target: Date, base: Date, unit: number) { if (target == null || base == null) { return NaN; } const sub = target.getTime() - base.getTime(); let result if (unit == 1) { result = Math.trunc(sub / 1000); } else if (unit == 2) { result = Math.trunc(sub / (1000 * 60)); } else if (unit == 3) { result = Math.trunc(sub / (1000 * 60 * 60)); } else if (unit == 4) { result = Math.trunc(sub / (1000 * 60 * 60 * 24)); } else if (unit == 5) { result = Math.trunc(sub / (1000 * 60 * 60 * 24 * 7)); } else { result = sub; } if (result < -2147483648 || result > 2147483647) { return NaN; } return result; }, addDate(base: Date, time: number, unit: number): Date | number { if (Number.isNaN(time)) { return base; } if (unit == 0) { return new Date(base.getTime() + time); } else if (unit == 1) { return new Date(base.getTime() + (time * 1000)); } else if (unit == 2) { return new Date(base.getTime() + (time * 1000 * 60)); } else if (unit == 3) { return new Date(base.getTime() + (time * 1000 * 60 * 60)); } else if (unit == 4) { return new Date(base.getTime() + (time * 1000 * 60 * 60 * 24)); } else if (unit == 5) { return new Date(base.getTime() + (time * 1000 * 60 * 60 * 24 * 7)); } return NaN; }, formatNumber(value: number): string | null { const number = Number(value); if (Number.isNaN(number)) { return null; } return number.toLocaleString("en-US"); }, unlockModuleOnMemory: (module: string | null | undefined): number => { console.log("unlockModuleOnMemory", module); const { componentId, moduleId } = this.resources.parseURLEx(module); if (componentId == null || moduleId == null) { return NaN; } return this.resources.unlockModule(componentId, moduleId, "lockModuleOnMemory") ? 1 : NaN; }, unlockModuleOnMemoryEx: (module: string | null | undefined): number => { console.log("unlockModuleOnMemoryEx", module); const { componentId, moduleId } = this.resources.parseURLEx(module); if (componentId == null || moduleId == null) { return NaN; } return this.resources.unlockModule(componentId, moduleId, "lockModuleOnMemoryEx") ? 1 : NaN; }, unlockAllModulesOnMemory: (): number => { console.log("unlockAllModulesOnMemory"); this.resources.unlockModules(); return 1; // NaN => fail }, lockModuleOnMemory: (module: string | null | undefined): number => { console.log("lockModuleOnMemory", module); const { componentId, moduleId } = this.resources.parseURLEx(module); if (componentId == null || moduleId == null || module == null) { return NaN; } // lockModuleOnMemoryExでロックされているモジュールをlockModuleOnMemoryでロックできない if (this.resources.getModuleLockedBy(componentId, moduleId) === "lockModuleOnMemoryEx") { return NaN; } if (!this.resources.getPMTComponent(componentId)) { console.error("lockModuleOnMemory: component does not exist in PMT", module); return -1; } if (this.resources.componentExistsInDownloadInfo(componentId)) { if (!this.resources.moduleExistsInDownloadInfo(componentId, moduleId)) { console.error("lockModuleOnMemory: component does not exist in DII", module); return -1; } } const cachedModule = this.resources.lockCachedModule(componentId, moduleId, "lockModuleOnMemory"); if (!cachedModule) { console.warn("lockModuleOnMemory: module not cached", module); this.resources.fetchResourceAsync(module).then(() => { const cachedModule = this.resources.lockCachedModule(componentId, moduleId, "lockModuleOnMemory"); if (cachedModule == null) { // 発生しない? return; } this.eventDispatcher.dispatchModuleLockedEvent(module, false, 0); }); return 1; } // イベントハンドラではモジュール名の大文字小文字がそのままである必要がある? this.eventDispatcher.dispatchModuleLockedEvent(module, false, 0); return 1; }, lockModuleOnMemoryEx: (module: string | null | undefined): number => { console.log("lockModuleOnMemoryEx", module); const { componentId, moduleId } = this.resources.parseURLEx(module); if (componentId == null || moduleId == null || module == null) { return NaN; } // TR-B14 第二分冊 5.12.6.9 (6) 参照 if (componentId !== 0x40 && componentId !== 0x50 && componentId !== 0x60) { return NaN; } // lockModuleOnMemoryでロックされているモジュールをlockModuleOnMemoryExでロックできない if (this.resources.getModuleLockedBy(componentId, moduleId) === "lockModuleOnMemory") { return NaN; } if (!this.resources.getPMTComponent(componentId)) { console.error("lockModuleOnMemoryEx: component does not exist in PMT", module); return -3; } if (this.resources.componentExistsInDownloadInfo(componentId)) { if (!this.resources.moduleExistsInDownloadInfo(componentId, moduleId)) { console.error("lockModuleOnMemoryEx: component does not exist in DII", module); this.eventDispatcher.dispatchModuleLockedEvent(module, true, -2); return 1; } } const cachedModule = this.resources.lockCachedModule(componentId, moduleId, "lockModuleOnMemoryEx"); if (!cachedModule) { const dataEventId = this.resources.getDownloadComponentInfo(componentId)?.dataEventId; console.warn("lockModuleOnMemoryEx: module not cached", module); this.resources.fetchResourceAsync(module).then(() => { if (dataEventId != null) { const eid = this.resources.getDownloadComponentInfo(componentId)?.dataEventId; if (eid != null && eid !== dataEventId) { // ロック対象のESのデータイベントが更新された場合 -1 TR-B14 第二分冊 5.12.6.9 (6) this.eventDispatcher.dispatchModuleLockedEvent(module, true, -1); return; } } const cachedModule = this.resources.lockCachedModule(componentId, moduleId, "lockModuleOnMemoryEx"); this.eventDispatcher.dispatchModuleLockedEvent(module, true, cachedModule == null ? -2 : 0); }); return 1; } // イベントハンドラではモジュール名の大文字小文字がそのままである必要がある? this.eventDispatcher.dispatchModuleLockedEvent(module, true, 0); return 1; }, lockScreen() { console.log("lockScreen"); return 1; }, unlockScreen() { console.log("unlockScreen"); return 1; }, getBrowserSupport: (sProvider: string, functionname: string, ...additionalinfoList: string[]): number => { console.log("getBrowserSupport", sProvider, functionname, ...additionalinfoList); const additionalinfo: string | undefined = additionalinfoList[0] ?? undefined; const additionalinfo2: string | undefined = additionalinfoList[1] ?? undefined; const additionalinfo3: string | undefined = additionalinfoList[2] ?? undefined; if (sProvider === "ARIB") { if (functionname === "BMLversion") { if (additionalinfo == null) { return 1; } else { const [major, minor] = additionalinfo.split(".").map(x => Number.parseInt(x)); if (major == null || minor == null) { return 0; } if ((major < 3 && major >= 0) || (major === 3 && minor === 0)) { return 1; } return 0; } } else if (functionname === "BXMLversion") { // B-XML return 0; } else if (functionname === "MediaDecoder") { // TODO } else if (functionname === "Storage" && additionalinfo === "cachesize") { // filesizeのキャッシュを備えているかどうか const filesize = Number(additionalinfo2); // ひとまず10 MiB return filesize <= 1024 * 1024 * 10 ? 1 : 0; } else if (functionname === "AudioFile") { // filesizeの音声ファイルを再生可能かどうか const filesize = Number(additionalinfo); // ひとまず10 MiB return filesize <= 1024 * 1024 * 10 ? 1 : 0; } else if (functionname === "APIGroup" && additionalinfo === "Com.IP.confirmIP") { return this.ip.confirmIPNetwork != null ? 1 : 0; } const f = arib.get(functionname); if (f == null) { console.error("unknown getBrowserSupport functionname", sProvider, functionname, ...additionalinfoList); return 0; } const a1 = f.get(additionalinfo); if (a1 == null) { console.error("unknown getBrowserSupport additionalinfo", sProvider, functionname, ...additionalinfoList); return 0; } if (typeof a1 === "number") { return a1; } const a2 = a1.get(additionalinfo2); if (a2 == null) { console.error("unknown getBrowserSupport additionalinfo2", sProvider, functionname, ...additionalinfoList); return 0; } if (typeof a2 === "number") { return a2; } const a3 = a2.get(additionalinfo3); if (a3 == null) { console.error("unknown getBrowserSupport additionalinfo2", sProvider, functionname, ...additionalinfoList); return 0; } return a3; } else if (sProvider === "BPA") { const f = bpa.get(functionname); if (f == null) { console.error("unknown getBrowserSupport functionname", sProvider, functionname, ...additionalinfoList); return 0; } const a1 = f.get(additionalinfo); if (a1 == null) { console.error("unknown getBrowserSupport additionalinfo", sProvider, functionname, ...additionalinfoList); return 0; } return a1; } console.error("unknown getBrowserSupport", sProvider, functionname, ...additionalinfoList); return 0; }, getBrowserStatus: (sProvider: string, statusname: string, additionalinfo: string): number => { console.log("getBrowserStatus", sProvider, statusname, additionalinfo); if (sProvider === "TerrP") { if (statusname === "IRDState") { if (additionalinfo === "Link") { // リンク状態のみ実装 return 1; } else if (additionalinfo === "UnLink") { // リンク状態のみ実装 return 0; } else if (additionalinfo === "Broadcast") { return this.resources.isInternetContent ? 0 : 1; } } } console.error("unknown getBrowserStatus", sProvider, statusname, additionalinfo); return NaN; }, launchDocument: (documentName: string, transitionStyle?: string): number => { console.log("%claunchDocument", "font-size: 4em", documentName, transitionStyle); this.content.launchDocument(documentName); this.interpreter.destroyStack(); throw new Error("unreachable!!"); }, reloadActiveDocument: (): number => { console.log("reloadActiveDocument"); return this.browser.launchDocument(this.browser.getActiveDocument()!); }, readPersistentArray: (filename: string, structure: string): any[] | null => { console.log("readPersistentArray", filename, structure); return this.nvram.readPersistentArray(filename, structure); }, writePersistentArray: (filename: string, structure: string, data: any[], period?: Date): number => { console.log("writePersistentArray", filename, structure, data, period); return this.nvram.writePersistentArray(filename, structure, data, period); }, checkAccessInfoOfPersistentArray: (filename: string): number => { console.log("checkAccessInfoOfPersistentArray", filename); return this.nvram.checkAccessInfoOfPersistentArray(filename); }, writePersistentArrayWithAccessCheck: (filename: string, structure: string, data: any[], period?: Date): number => { console.log("writePersistentArrayWithAccessCheck", filename, structure, data, period); return this.nvram.writePersistentArrayWithAccessCheck(filename, structure, data, period); }, readPersistentArrayWithAccessCheck: (filename: string, structure: string): any[] | null => { console.log("readPersistentArrayWithAccessCheck", filename, structure); return this.nvram.readPersistentArrayWithAccessCheck(filename, structure); }, random(num: number): number { return Math.floor(Math.random() * num) + 1; }, getActiveDocument: (): string | null => { const activeDocument = this.resources.activeDocument; if (activeDocument == null) { return null; } // TR-B14 第二分冊 5.14.6.9 if (activeDocument.startsWith("http://") || activeDocument.startsWith("https://")) { const url = new URL(activeDocument); return url.pathname + url.search + url.hash; } return activeDocument; }, getResidentAppVersion(appName: string): any[] | null { console.log("getResidentAppVersion", appName); return null; }, getLockedModuleInfo: (): LockedModuleInfo[] | null => { console.log("getLockedModuleInfo"); const l: LockedModuleInfo[] = []; for (const { module, isEx } of this.resources.getLockedModules()) { l.push([module, isEx ? 2 : 1, 1]); } return l; }, detectComponent: (component_ref: string) => { const { componentId } = this.resources.parseURLEx(component_ref); if (componentId == null) { return NaN; } if (this.resources.getPMTComponent(componentId)) { console.log("detectComponent", componentId, true); return 1; } else { console.log("detectComponent", componentId, false); return 0; } }, getProgramID: (type: number): string | null => { function toHex(n: number | null | undefined, d: number): string | null { if (n == null) { return null; } return "0x" + n.toString(16).padStart(d, "0"); } if (type == 1) { return toHex(this.resources.eventId, 4); } else if (type == 2) { return toHex(this.resources.serviceId, 4); } else if (type == 3) { return toHex(this.resources.originalNetworkId, 4); } else if (type == 4) { return toHex(this.resources.transportStreamId, 4); } else if (type == 6) { // STD-B24 第二分冊 (1/2) 9.2.6 return this.resources.eventURI; } else if (type == 7) { // STD-B24 第二分冊 (1/2) 9.2.5 return this.resources.serviceURI; } console.error("getProgramID", type); return null; }, playRomSound: (soundID: string): number => { console.log("playRomSound", soundID); const groups = /romsound:\/\/(?<soundID>\d+)/.exec(soundID)?.groups; if (groups != null) { playRomSound(Number.parseInt(groups.soundID), this.audioNodeProvider.getAudioDestinationNode()); } return 1; }, getBrowserVersion(): string[] { return ["BMLHTML", "BMLHTML", "001", "000"]; }, getIRDID(type: number): string | null { console.log("getIRDID", type); if (type === 5) { // 20桁のB-CAS番号のうち後ろ5桁のチェックサムを除去したもの // const cardID = "000012345678901"; // 16進表記に変換 // return BigInt(cardID.substring(0, 20 - 5)).toString(16).padStart(12, "0"); } return null; }, isIPConnected: (): number => { console.log("isIPConnected"); return this.ip.isIPConnected?.() ?? 0; }, getConnectionType: (): number => { console.log("getConnectionType"); return this.ip.getConnectionType?.() ?? 403; // Ethernet DHCP }, setInterval: (evalCode: string, msec: number, iteration: number): number => { const handle = this.eventQueue.setInterval(() => { iteration--; if (iteration === 0) { this.eventQueue.clearInterval(handle); } this.eventQueue.queueAsyncEvent(async () => { return await this.eventQueue.executeEventHandler(evalCode); }); this.eventQueue.processEventQueue(); }, msec); console.log("setInterval", evalCode, msec, iteration, handle); return handle; }, clearTimer: (timerID: number): number => { console.log("clearTimer", timerID); return this.eventQueue.clearInterval(timerID) ? 1 : NaN; }, pauseTimer: (timerID: number): number => { console.log("pauseTimer", timerID); return this.eventQueue.pauseTimer(timerID) ? 1 : NaN; }, resumeTimer: (timerID: number): number => { console.log("resumeTimer", timerID); return this.eventQueue.resumeTimer(timerID) ? 1 : NaN; }, getNPT: (): number => { const npt = Math.floor((this.content.getNPT90kHz() ?? NaN) / 90); console.log("getNPT", npt); return npt; }, } as Browser; serviceId?: number; public onMessage(msg: ResponseMessage) { if (msg.type === "programInfo") { if (msg.serviceId != null && msg.serviceId !== this.serviceId) { // TR-B14 第二分冊 5.12.6.1 if (this.serviceId != null) { console.log("serviceId changed", msg.serviceId, this.serviceId) for (let i = 1; i < 64; i++) { // FIXME this.setUreg(i, ""); } } this.setUreg(0, "0x" + msg.serviceId.toString(16).padStart(4)); } } } }
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 Braket extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Braket.Types.ClientConfiguration) config: Config & Braket.Types.ClientConfiguration; /** * Cancels an Amazon Braket job. */ cancelJob(params: Braket.Types.CancelJobRequest, callback?: (err: AWSError, data: Braket.Types.CancelJobResponse) => void): Request<Braket.Types.CancelJobResponse, AWSError>; /** * Cancels an Amazon Braket job. */ cancelJob(callback?: (err: AWSError, data: Braket.Types.CancelJobResponse) => void): Request<Braket.Types.CancelJobResponse, AWSError>; /** * Cancels the specified task. */ cancelQuantumTask(params: Braket.Types.CancelQuantumTaskRequest, callback?: (err: AWSError, data: Braket.Types.CancelQuantumTaskResponse) => void): Request<Braket.Types.CancelQuantumTaskResponse, AWSError>; /** * Cancels the specified task. */ cancelQuantumTask(callback?: (err: AWSError, data: Braket.Types.CancelQuantumTaskResponse) => void): Request<Braket.Types.CancelQuantumTaskResponse, AWSError>; /** * Creates an Amazon Braket job. */ createJob(params: Braket.Types.CreateJobRequest, callback?: (err: AWSError, data: Braket.Types.CreateJobResponse) => void): Request<Braket.Types.CreateJobResponse, AWSError>; /** * Creates an Amazon Braket job. */ createJob(callback?: (err: AWSError, data: Braket.Types.CreateJobResponse) => void): Request<Braket.Types.CreateJobResponse, AWSError>; /** * Creates a quantum task. */ createQuantumTask(params: Braket.Types.CreateQuantumTaskRequest, callback?: (err: AWSError, data: Braket.Types.CreateQuantumTaskResponse) => void): Request<Braket.Types.CreateQuantumTaskResponse, AWSError>; /** * Creates a quantum task. */ createQuantumTask(callback?: (err: AWSError, data: Braket.Types.CreateQuantumTaskResponse) => void): Request<Braket.Types.CreateQuantumTaskResponse, AWSError>; /** * Retrieves the devices available in Amazon Braket. */ getDevice(params: Braket.Types.GetDeviceRequest, callback?: (err: AWSError, data: Braket.Types.GetDeviceResponse) => void): Request<Braket.Types.GetDeviceResponse, AWSError>; /** * Retrieves the devices available in Amazon Braket. */ getDevice(callback?: (err: AWSError, data: Braket.Types.GetDeviceResponse) => void): Request<Braket.Types.GetDeviceResponse, AWSError>; /** * Retrieves the specified Amazon Braket job. */ getJob(params: Braket.Types.GetJobRequest, callback?: (err: AWSError, data: Braket.Types.GetJobResponse) => void): Request<Braket.Types.GetJobResponse, AWSError>; /** * Retrieves the specified Amazon Braket job. */ getJob(callback?: (err: AWSError, data: Braket.Types.GetJobResponse) => void): Request<Braket.Types.GetJobResponse, AWSError>; /** * Retrieves the specified quantum task. */ getQuantumTask(params: Braket.Types.GetQuantumTaskRequest, callback?: (err: AWSError, data: Braket.Types.GetQuantumTaskResponse) => void): Request<Braket.Types.GetQuantumTaskResponse, AWSError>; /** * Retrieves the specified quantum task. */ getQuantumTask(callback?: (err: AWSError, data: Braket.Types.GetQuantumTaskResponse) => void): Request<Braket.Types.GetQuantumTaskResponse, AWSError>; /** * Shows the tags associated with this resource. */ listTagsForResource(params: Braket.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Braket.Types.ListTagsForResourceResponse) => void): Request<Braket.Types.ListTagsForResourceResponse, AWSError>; /** * Shows the tags associated with this resource. */ listTagsForResource(callback?: (err: AWSError, data: Braket.Types.ListTagsForResourceResponse) => void): Request<Braket.Types.ListTagsForResourceResponse, AWSError>; /** * Searches for devices using the specified filters. */ searchDevices(params: Braket.Types.SearchDevicesRequest, callback?: (err: AWSError, data: Braket.Types.SearchDevicesResponse) => void): Request<Braket.Types.SearchDevicesResponse, AWSError>; /** * Searches for devices using the specified filters. */ searchDevices(callback?: (err: AWSError, data: Braket.Types.SearchDevicesResponse) => void): Request<Braket.Types.SearchDevicesResponse, AWSError>; /** * Searches for Amazon Braket jobs that match the specified filter values. */ searchJobs(params: Braket.Types.SearchJobsRequest, callback?: (err: AWSError, data: Braket.Types.SearchJobsResponse) => void): Request<Braket.Types.SearchJobsResponse, AWSError>; /** * Searches for Amazon Braket jobs that match the specified filter values. */ searchJobs(callback?: (err: AWSError, data: Braket.Types.SearchJobsResponse) => void): Request<Braket.Types.SearchJobsResponse, AWSError>; /** * Searches for tasks that match the specified filter values. */ searchQuantumTasks(params: Braket.Types.SearchQuantumTasksRequest, callback?: (err: AWSError, data: Braket.Types.SearchQuantumTasksResponse) => void): Request<Braket.Types.SearchQuantumTasksResponse, AWSError>; /** * Searches for tasks that match the specified filter values. */ searchQuantumTasks(callback?: (err: AWSError, data: Braket.Types.SearchQuantumTasksResponse) => void): Request<Braket.Types.SearchQuantumTasksResponse, AWSError>; /** * Add a tag to the specified resource. */ tagResource(params: Braket.Types.TagResourceRequest, callback?: (err: AWSError, data: Braket.Types.TagResourceResponse) => void): Request<Braket.Types.TagResourceResponse, AWSError>; /** * Add a tag to the specified resource. */ tagResource(callback?: (err: AWSError, data: Braket.Types.TagResourceResponse) => void): Request<Braket.Types.TagResourceResponse, AWSError>; /** * Remove tags from a resource. */ untagResource(params: Braket.Types.UntagResourceRequest, callback?: (err: AWSError, data: Braket.Types.UntagResourceResponse) => void): Request<Braket.Types.UntagResourceResponse, AWSError>; /** * Remove tags from a resource. */ untagResource(callback?: (err: AWSError, data: Braket.Types.UntagResourceResponse) => void): Request<Braket.Types.UntagResourceResponse, AWSError>; } declare namespace Braket { export interface AlgorithmSpecification { /** * The container image used to create an Amazon Braket job. */ containerImage?: ContainerImage; /** * Configures the paths to the Python scripts used for entry and training. */ scriptModeConfig?: ScriptModeConfig; } export interface CancelJobRequest { /** * The ARN of the Amazon Braket job to cancel. */ jobArn: JobArn; } export interface CancelJobResponse { /** * The status of the job cancellation request. */ cancellationStatus: CancellationStatus; /** * The ARN of the Amazon Braket job. */ jobArn: JobArn; } export interface CancelQuantumTaskRequest { /** * The client token associated with the request. */ clientToken: String64; /** * The ARN of the task to cancel. */ quantumTaskArn: QuantumTaskArn; } export interface CancelQuantumTaskResponse { /** * The status of the cancellation request. */ cancellationStatus: CancellationStatus; /** * The ARN of the task. */ quantumTaskArn: QuantumTaskArn; } export type CancellationStatus = "CANCELLING"|"CANCELLED"|string; export type CompressionType = "NONE"|"GZIP"|string; export interface ContainerImage { /** * The URI locating the container image. */ uri: Uri; } export interface CreateJobRequest { /** * Definition of the Amazon Braket job to be created. Specifies the container image the job uses and information about the Python scripts used for entry and training. */ algorithmSpecification: AlgorithmSpecification; /** * Information about the output locations for job checkpoint data. */ checkpointConfig?: JobCheckpointConfig; /** * A unique token that guarantees that the call to this API is idempotent. */ clientToken: String64; /** * The quantum processing unit (QPU) or simulator used to create an Amazon Braket job. */ deviceConfig: DeviceConfig; /** * Algorithm-specific parameters used by an Amazon Braket job that influence the quality of the training job. The values are set with a string of JSON key:value pairs, where the key is the name of the hyperparameter and the value is the value of th hyperparameter. */ hyperParameters?: HyperParameters; /** * A list of parameters that specify the name and type of input data and where it is located. */ inputDataConfig?: CreateJobRequestInputDataConfigList; /** * Configuration of the resource instances to use while running the hybrid job on Amazon Braket. */ instanceConfig: InstanceConfig; /** * The name of the Amazon Braket job. */ jobName: CreateJobRequestJobNameString; /** * The path to the S3 location where you want to store job artifacts and the encryption key used to store them. */ outputDataConfig: JobOutputDataConfig; /** * The Amazon Resource Name (ARN) of an IAM role that Amazon Braket can assume to perform tasks on behalf of a user. It can access user resources, run an Amazon Braket job container on behalf of user, and output resources to the users' s3 buckets. */ roleArn: RoleArn; /** * The user-defined criteria that specifies when a job stops running. */ stoppingCondition?: JobStoppingCondition; /** * A tag object that consists of a key and an optional value, used to manage metadata for Amazon Braket resources. */ tags?: TagsMap; } export type CreateJobRequestInputDataConfigList = InputFileConfig[]; export type CreateJobRequestJobNameString = string; export interface CreateJobResponse { /** * The ARN of the Amazon Braket job created. */ jobArn: JobArn; } export interface CreateQuantumTaskRequest { /** * The action associated with the task. */ action: JsonValue; /** * The client token associated with the request. */ clientToken: String64; /** * The ARN of the device to run the task on. */ deviceArn: DeviceArn; /** * The parameters for the device to run the task on. */ deviceParameters?: CreateQuantumTaskRequestDeviceParametersString; /** * The token for an Amazon Braket job that associates it with the quantum task. */ jobToken?: JobToken; /** * The S3 bucket to store task result files in. */ outputS3Bucket: CreateQuantumTaskRequestOutputS3BucketString; /** * The key prefix for the location in the S3 bucket to store task results in. */ outputS3KeyPrefix: CreateQuantumTaskRequestOutputS3KeyPrefixString; /** * The number of shots to use for the task. */ shots: CreateQuantumTaskRequestShotsLong; /** * Tags to be added to the quantum task you're creating. */ tags?: TagsMap; } export type CreateQuantumTaskRequestDeviceParametersString = string; export type CreateQuantumTaskRequestOutputS3BucketString = string; export type CreateQuantumTaskRequestOutputS3KeyPrefixString = string; export type CreateQuantumTaskRequestShotsLong = number; export interface CreateQuantumTaskResponse { /** * The ARN of the task created by the request. */ quantumTaskArn: QuantumTaskArn; } export interface DataSource { /** * Information about the data stored in Amazon S3 used by the Amazon Braket job. */ s3DataSource: S3DataSource; } export type DeviceArn = string; export interface DeviceConfig { /** * The primary quantum processing unit (QPU) or simulator used to create and run an Amazon Braket job. */ device: String256; } export type DeviceStatus = "ONLINE"|"OFFLINE"|"RETIRED"|string; export interface DeviceSummary { /** * The ARN of the device. */ deviceArn: DeviceArn; /** * The name of the device. */ deviceName: String; /** * The status of the device. */ deviceStatus: DeviceStatus; /** * The type of the device. */ deviceType: DeviceType; /** * The provider of the device. */ providerName: String; } export type DeviceSummaryList = DeviceSummary[]; export type DeviceType = "QPU"|"SIMULATOR"|string; export interface GetDeviceRequest { /** * The ARN of the device to retrieve. */ deviceArn: DeviceArn; } export interface GetDeviceResponse { /** * The ARN of the device. */ deviceArn: DeviceArn; /** * Details about the capabilities of the device. */ deviceCapabilities: JsonValue; /** * The name of the device. */ deviceName: String; /** * The status of the device. */ deviceStatus: DeviceStatus; /** * The type of the device. */ deviceType: DeviceType; /** * The name of the partner company for the device. */ providerName: String; } export interface GetJobRequest { /** * The ARN of the job to retrieve. */ jobArn: JobArn; } export interface GetJobResponse { /** * Definition of the Amazon Braket job created. Specifies the container image the job uses, information about the Python scripts used for entry and training, and the user-defined metrics used to evaluation the job. */ algorithmSpecification: AlgorithmSpecification; /** * The billable time the Amazon Braket job used to complete. */ billableDuration?: Integer; /** * Information about the output locations for job checkpoint data. */ checkpointConfig?: JobCheckpointConfig; /** * The date and time that the Amazon Braket job was created. */ createdAt: SyntheticTimestamp_date_time; /** * The quantum processing unit (QPU) or simulator used to run the Amazon Braket job. */ deviceConfig?: DeviceConfig; /** * The date and time that the Amazon Braket job ended. */ endedAt?: SyntheticTimestamp_date_time; /** * Details about the type and time events occurred related to the Amazon Braket job. */ events?: JobEvents; /** * A description of the reason why an Amazon Braket job failed, if it failed. */ failureReason?: String1024; /** * Algorithm-specific parameters used by an Amazon Braket job that influence the quality of the traiing job. The values are set with a string of JSON key:value pairs, where the key is the name of the hyperparameter and the value is the value of th hyperparameter. */ hyperParameters?: HyperParameters; /** * A list of parameters that specify the name and type of input data and where it is located. */ inputDataConfig?: InputConfigList; /** * The resource instances to use while running the hybrid job on Amazon Braket. */ instanceConfig: InstanceConfig; /** * The ARN of the Amazon Braket job. */ jobArn: JobArn; /** * The name of the Amazon Braket job. */ jobName: GetJobResponseJobNameString; /** * The path to the S3 location where job artifacts are stored and the encryption key used to store them there. */ outputDataConfig: JobOutputDataConfig; /** * The Amazon Resource Name (ARN) of an IAM role that Amazon Braket can assume to perform tasks on behalf of a user. It can access user resources, run an Amazon Braket job container on behalf of user, and output resources to the s3 buckets of a user. */ roleArn: RoleArn; /** * The date and time that the Amazon Braket job was started. */ startedAt?: SyntheticTimestamp_date_time; /** * The status of the Amazon Braket job. */ status: JobPrimaryStatus; /** * The user-defined criteria that specifies when to stop a job running. */ stoppingCondition?: JobStoppingCondition; /** * A tag object that consists of a key and an optional value, used to manage metadata for Amazon Braket resources. */ tags?: TagsMap; } export type GetJobResponseJobNameString = string; export interface GetQuantumTaskRequest { /** * the ARN of the task to retrieve. */ quantumTaskArn: QuantumTaskArn; } export interface GetQuantumTaskResponse { /** * The time at which the task was created. */ createdAt: SyntheticTimestamp_date_time; /** * The ARN of the device the task was run on. */ deviceArn: DeviceArn; /** * The parameters for the device on which the task ran. */ deviceParameters: JsonValue; /** * The time at which the task ended. */ endedAt?: SyntheticTimestamp_date_time; /** * The reason that a task failed. */ failureReason?: String; /** * The ARN of the Amazon Braket job associated with the quantum task. */ jobArn?: JobArn; /** * The S3 bucket where task results are stored. */ outputS3Bucket: String; /** * The folder in the S3 bucket where task results are stored. */ outputS3Directory: String; /** * The ARN of the task. */ quantumTaskArn: QuantumTaskArn; /** * The number of shots used in the task. */ shots: Long; /** * The status of the task. */ status: QuantumTaskStatus; /** * The tags that belong to this task. */ tags?: TagsMap; } export type HyperParameters = {[key: string]: HyperParametersValueString}; export type HyperParametersValueString = string; export type InputConfigList = InputFileConfig[]; export interface InputFileConfig { /** * A named input source that an Amazon Braket job can consume. */ channelName: InputFileConfigChannelNameString; /** * The MIME type of the data. */ contentType?: String256; /** * The location of the channel data. */ dataSource: DataSource; } export type InputFileConfigChannelNameString = string; export interface InstanceConfig { /** * Configures the type resource instances to use while running an Amazon Braket hybrid job. */ instanceType: InstanceType; /** * The size of the storage volume, in GB, that user wants to provision. */ volumeSizeInGb: InstanceConfigVolumeSizeInGbInteger; } export type InstanceConfigVolumeSizeInGbInteger = number; export type InstanceType = "ml.m4.xlarge"|"ml.m4.2xlarge"|"ml.m4.4xlarge"|"ml.m4.10xlarge"|"ml.m4.16xlarge"|"ml.g4dn.xlarge"|"ml.g4dn.2xlarge"|"ml.g4dn.4xlarge"|"ml.g4dn.8xlarge"|"ml.g4dn.12xlarge"|"ml.g4dn.16xlarge"|"ml.m5.large"|"ml.m5.xlarge"|"ml.m5.2xlarge"|"ml.m5.4xlarge"|"ml.m5.12xlarge"|"ml.m5.24xlarge"|"ml.c4.xlarge"|"ml.c4.2xlarge"|"ml.c4.4xlarge"|"ml.c4.8xlarge"|"ml.p2.xlarge"|"ml.p2.8xlarge"|"ml.p2.16xlarge"|"ml.p3.2xlarge"|"ml.p3.8xlarge"|"ml.p3.16xlarge"|"ml.p3dn.24xlarge"|"ml.p4d.24xlarge"|"ml.c5.xlarge"|"ml.c5.2xlarge"|"ml.c5.4xlarge"|"ml.c5.9xlarge"|"ml.c5.18xlarge"|"ml.c5n.xlarge"|"ml.c5n.2xlarge"|"ml.c5n.4xlarge"|"ml.c5n.9xlarge"|"ml.c5n.18xlarge"|string; export type Integer = number; export type JobArn = string; export interface JobCheckpointConfig { /** * (Optional) The local directory where checkpoints are written. The default directory is /opt/braket/checkpoints/. */ localPath?: String4096; /** * Identifies the S3 path where you want Amazon Braket to store checkpoints. For example, s3://bucket-name/key-name-prefix. */ s3Uri: S3Path; } export interface JobEventDetails { /** * The type of event that occurred related to the Amazon Braket job. */ eventType?: JobEventType; /** * A message describing the event that occurred related to the Amazon Braket job. */ message?: JobEventDetailsMessageString; /** * TThe type of event that occurred related to the Amazon Braket job. */ timeOfEvent?: SyntheticTimestamp_date_time; } export type JobEventDetailsMessageString = string; export type JobEventType = "WAITING_FOR_PRIORITY"|"QUEUED_FOR_EXECUTION"|"STARTING_INSTANCE"|"DOWNLOADING_DATA"|"RUNNING"|"DEPRIORITIZED_DUE_TO_INACTIVITY"|"UPLOADING_RESULTS"|"COMPLETED"|"FAILED"|"MAX_RUNTIME_EXCEEDED"|"CANCELLED"|string; export type JobEvents = JobEventDetails[]; export interface JobOutputDataConfig { /** * The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to encrypt the job training artifacts at rest using Amazon S3 server-side encryption. */ kmsKeyId?: String2048; /** * Identifies the S3 path where you want Amazon Braket to store the job training artifacts. For example, s3://bucket-name/key-name-prefix. */ s3Path: S3Path; } export type JobPrimaryStatus = "QUEUED"|"RUNNING"|"COMPLETED"|"FAILED"|"CANCELLING"|"CANCELLED"|string; export interface JobStoppingCondition { /** * The maximum length of time, in seconds, that an Amazon Braket job can run. */ maxRuntimeInSeconds?: JobStoppingConditionMaxRuntimeInSecondsInteger; } export type JobStoppingConditionMaxRuntimeInSecondsInteger = number; export interface JobSummary { /** * The date and time that the Amazon Braket job was created. */ createdAt: SyntheticTimestamp_date_time; /** * Provides summary information about the primary device used by an Amazon Braket job. */ device: String256; /** * The date and time that the Amazon Braket job ended. */ endedAt?: SyntheticTimestamp_date_time; /** * The ARN of the Amazon Braket job. */ jobArn: JobArn; /** * The name of the Amazon Braket job. */ jobName: String; /** * The date and time that the Amazon Braket job was started. */ startedAt?: SyntheticTimestamp_date_time; /** * The status of the Amazon Braket job. */ status: JobPrimaryStatus; /** * A tag object that consists of a key and an optional value, used to manage metadata for Amazon Braket resources. */ tags?: TagsMap; } export type JobSummaryList = JobSummary[]; export type JobToken = string; export type JsonValue = string; export interface ListTagsForResourceRequest { /** * Specify the resourceArn for the resource whose tags to display. */ resourceArn: String; } export interface ListTagsForResourceResponse { /** * Displays the key, value pairs of tags associated with this resource. */ tags?: TagsMap; } export type Long = number; export type QuantumTaskArn = string; export type QuantumTaskStatus = "CREATED"|"QUEUED"|"RUNNING"|"COMPLETED"|"FAILED"|"CANCELLING"|"CANCELLED"|string; export interface QuantumTaskSummary { /** * The time at which the task was created. */ createdAt: SyntheticTimestamp_date_time; /** * The ARN of the device the task ran on. */ deviceArn: DeviceArn; /** * The time at which the task finished. */ endedAt?: SyntheticTimestamp_date_time; /** * The S3 bucket where the task result file is stored.. */ outputS3Bucket: String; /** * The folder in the S3 bucket where the task result file is stored. */ outputS3Directory: String; /** * The ARN of the task. */ quantumTaskArn: QuantumTaskArn; /** * The shots used for the task. */ shots: Long; /** * The status of the task. */ status: QuantumTaskStatus; /** * Displays the key, value pairs of tags associated with this quantum task. */ tags?: TagsMap; } export type QuantumTaskSummaryList = QuantumTaskSummary[]; export type RoleArn = string; export interface S3DataSource { /** * Depending on the value specified for the S3DataType, identifies either a key name prefix or a manifest that locates the S3 data source. */ s3Uri: S3Path; } export type S3Path = string; export interface ScriptModeConfig { /** * The type of compression used by the Python scripts for an Amazon Braket job. */ compressionType?: CompressionType; /** * The path to the Python script that serves as the entry point for an Amazon Braket job. */ entryPoint: String; /** * The URI that specifies the S3 path to the Python script module that contains the training script used by an Amazon Braket job. */ s3Uri: S3Path; } export interface SearchDevicesFilter { /** * The name to use to filter results. */ name: SearchDevicesFilterNameString; /** * The values to use to filter results. */ values: SearchDevicesFilterValuesList; } export type SearchDevicesFilterNameString = string; export type SearchDevicesFilterValuesList = String256[]; export interface SearchDevicesRequest { /** * The filter values to use to search for a device. */ filters: SearchDevicesRequestFiltersList; /** * The maximum number of results to return in the response. */ maxResults?: SearchDevicesRequestMaxResultsInteger; /** * A token used for pagination of results returned in the response. Use the token returned from the previous request continue results where the previous request ended. */ nextToken?: String; } export type SearchDevicesRequestFiltersList = SearchDevicesFilter[]; export type SearchDevicesRequestMaxResultsInteger = number; export interface SearchDevicesResponse { /** * An array of DeviceSummary objects for devices that match the specified filter values. */ devices: DeviceSummaryList; /** * A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. */ nextToken?: String; } export interface SearchJobsFilter { /** * The name to use for the jobs filter. */ name: String64; /** * An operator to use for the jobs filter. */ operator: SearchJobsFilterOperator; /** * The values to use for the jobs filter. */ values: SearchJobsFilterValuesList; } export type SearchJobsFilterOperator = "LT"|"LTE"|"EQUAL"|"GT"|"GTE"|"BETWEEN"|"CONTAINS"|string; export type SearchJobsFilterValuesList = String256[]; export interface SearchJobsRequest { /** * The filter values to use when searching for a job. */ filters: SearchJobsRequestFiltersList; /** * The maximum number of results to return in the response. */ maxResults?: SearchJobsRequestMaxResultsInteger; /** * A token used for pagination of results returned in the response. Use the token returned from the previous request to continue results where the previous request ended. */ nextToken?: String; } export type SearchJobsRequestFiltersList = SearchJobsFilter[]; export type SearchJobsRequestMaxResultsInteger = number; export interface SearchJobsResponse { /** * An array of JobSummary objects for devices that match the specified filter values. */ jobs: JobSummaryList; /** * A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. */ nextToken?: String; } export interface SearchQuantumTasksFilter { /** * The name of the device used for the task. */ name: String64; /** * An operator to use in the filter. */ operator: SearchQuantumTasksFilterOperator; /** * The values to use for the filter. */ values: SearchQuantumTasksFilterValuesList; } export type SearchQuantumTasksFilterOperator = "LT"|"LTE"|"EQUAL"|"GT"|"GTE"|"BETWEEN"|string; export type SearchQuantumTasksFilterValuesList = String256[]; export interface SearchQuantumTasksRequest { /** * Array of SearchQuantumTasksFilter objects. */ filters: SearchQuantumTasksRequestFiltersList; /** * Maximum number of results to return in the response. */ maxResults?: SearchQuantumTasksRequestMaxResultsInteger; /** * A token used for pagination of results returned in the response. Use the token returned from the previous request continue results where the previous request ended. */ nextToken?: String; } export type SearchQuantumTasksRequestFiltersList = SearchQuantumTasksFilter[]; export type SearchQuantumTasksRequestMaxResultsInteger = number; export interface SearchQuantumTasksResponse { /** * A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. */ nextToken?: String; /** * An array of QuantumTaskSummary objects for tasks that match the specified filters. */ quantumTasks: QuantumTaskSummaryList; } export type String = string; export type String1024 = string; export type String2048 = string; export type String256 = string; export type String4096 = string; export type String64 = string; export type SyntheticTimestamp_date_time = Date; export type TagKeys = String[]; export interface TagResourceRequest { /** * Specify the resourceArn of the resource to which a tag will be added. */ resourceArn: String; /** * Specify the tags to add to the resource. */ tags: TagsMap; } export interface TagResourceResponse { } export type TagsMap = {[key: string]: String}; export interface UntagResourceRequest { /** * Specify the resourceArn for the resource from which to remove the tags. */ resourceArn: String; /** * Specify the keys for the tags to remove from the resource. */ tagKeys: TagKeys; } export interface UntagResourceResponse { } export type Uri = 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 = "2019-09-01"|"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 Braket client. */ export import Types = Braket; } export = Braket;
the_stack
import { getRecommendsTags } from '@/api/common'; import { Component, PropSync, Ref, Watch } from 'vue-property-decorator'; import { createModel, getModelInfo, updateModel, validateModelName } from '../../Api/index'; import { DataModelStorage } from '../../Controller/DataModelStorage'; import { DataModelManage } from './IStepsManage'; @Component({ name: 'ModelInfo', components: {}, }) export default class ModelInfo extends DataModelManage.IStepsManage { @Ref() public readonly modelInfoForm; @PropSync('isLoading', { default: false }) public syncIsLoading; private storageKey = 'modelFormInfo'; public tags = { visible: { results: [], }, }; public defaultFormData = { model_name: '', model_alias: '', model_type: '', description: '', tags: [], project_id: 0, }; public formData = { model_name: '', model_alias: '', model_type: '', description: '', tags: [], project_id: 0, }; public rules = { model_name: [ { required: true, message: '必填项', trigger: 'blur', }, { min: 1, message(val) { return `${val}不能小于1个字符`; }, trigger: 'blur', }, { max: 50, message: '不能多于50个字符', trigger: 'blur', }, { regex: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '只能是英文字母、下划线和数字组成,且字母开头', trigger: 'blur', }, { validator: this.validateModelName, message: '数据模型名称已存在,请修改数据模型名称', trigger: 'blur', }, ], model_alias: [ { required: true, message: '必填项', trigger: 'blur', }, { min: 1, message(val) { return `${val}不能小于1个字符`; }, trigger: 'blur', }, { max: 50, message: '不能多于50个字符', trigger: 'blur', }, ], model_type: [ { required: true, message: '请选择项目', trigger: 'blur', }, ], tags: [ { required: true, message: '请选择标签', trigger: 'blur', }, { validator(val) { return val.length >= 1; }, message: '请选择标签', trigger: 'blur', }, ], }; public timer = null; /** 是否为新增模型 */ get isNewForm() { return !this.formData.created_at; } get tagList() { return this.tags.visible.results || []; } get tagCount() { return this.formData.tags.length; } @Watch('modelId', { immediate: true }) public handleModelIdChanged() { this.loadModelInfo(); } @Watch('updateEvents', { deep: true }) public handleUpdateEventFired(val: IUpdateEvent) { /** /* updateModelName : 事件来自右侧顶部工具栏更新模型名称 */ if (val && val.name === 'updateModelName') { this.handleUpdateModel(val.params[0]); } } /** /* 切换 tab,如果 modelId 为 0,通过监听 activeModelTabItem 触发 loadModelInfo */ @Watch('activeModelTabItem', { deep: true }) public handleActiveModelTabItemChange() { this.activeModelTabItem && this.activeModelTabItem.modelId === 0 && this.loadModelInfo(); } /** /* 暂存新建表填入的数据 */ @Watch('formData', { deep: true }) public handleStorageFormData() { if (this.activeModelTabItem && this.modelId === 0) { if (this.timer) { clearTimeout(this.timer); this.timer = null; } this.timer = setTimeout(() => { DataModelStorage.update(this.storageKey + this.activeModelTabItem.id, this.formData); }, 400); } } public handleModelTypeSelected(type: string) { this.formData.model_type = type; } public handleTags(tagCodes: any[]) { const result: object[] = []; this.tagList.forEach((item: any) => { if (tagCodes.includes(item.code)) { result.push({ tag_code: item.code, tag_alias: item.alias, }); tagCodes.splice(tagCodes.indexOf(item.code), 1); } }); if (tagCodes.length) { tagCodes.forEach((item: any) => { result.push({ tag_code: '', tag_alias: item, }); }); } return result; } public submitForm() { return this.modelInfoForm .validate() .then(res => { const tagCodes = this.handleTags(JSON.parse(JSON.stringify(this.formData.tags))); if (this.isNewForm) { const { model_name, model_alias, model_type, description } = this.formData; return createModel(model_name, model_alias, model_type, this.projectId, description, tagCodes) .then(res => { return res.setData(this, 'formData').then(r => { const activeTabIndex = this.DataModelTabManage.getActiveItemIndex(); if (activeTabIndex >= 0) { const activeTab = this.DataModelTabManage.tabManage.items[activeTabIndex]; activeTab.name = this.formData.model_name; activeTab.displayName = this.formData.model_alias; activeTab.id = this.formData.model_id; activeTab.modelId = this.formData.model_id; activeTab.lastStep = this.formData.step_id; activeTab.publishStatus = this.formData.publish_status; activeTab.isNew = false; this.DataModelTabManage.updateTabItem(activeTab, activeTabIndex); this.DataModelTabManage.dispatchEvent('updateModel', [this.formData]); // 保存后,新建表单缓存数据清空 DataModelStorage.update(this.storageKey + 0, null); // this.appendRouter({ modelId: this.formData.model_id }) this.changeRouterWithParams( 'dataModelEdit', { project_id: this.activeModelTabItem.projectId }, { modelId: this.formData.model_id } ); } this.showMessage(this.$t('创建成功'), 'success'); this.backFillTags(res.data.tags); this.syncPreNextBtnManage.isPreNextBtnConfirm = false; return Promise.resolve(true); }); }); } else { const { model_id, model_alias, description } = this.formData; return updateModel(model_id, model_alias, description, tagCodes).then(res => { if (res.validateResult()) { const activeTabIndex = this.DataModelTabManage.getActiveItemIndex(); if (activeTabIndex >= 0) { const activeTab = this.DataModelTabManage.tabManage.items[activeTabIndex]; activeTab.displayName = this.formData.model_alias; activeTab.publishStatus = res.data.publish_status; this.formData.publish_status = res.data.publish_status; this.DataModelTabManage.updateTabItem(activeTab, activeTabIndex); this.DataModelTabManage.dispatchEvent('updateModel', [this.formData]); } this.showMessage(this.$t('更新成功'), 'success'); this.backFillTags(res.data.tags); this.initPreNextManage(false); this.syncPreNextBtnManage.isPreNextBtnConfirm = false; return Promise.resolve(true); } else { return Promise.reject(res.message); } }); } }) ['catch'](err => console.log(err)); } public backFillTags(tags: object[]) { const tagsMap = {}; tags.forEach(item => { tagsMap[item.tag_code] = item.tag_alias; }); const tagsArr = Object.keys(tagsMap); this.tags.visible.results.forEach(item => { if (tagsArr.includes(item.code)) { tagsArr.splice(tagsArr.indexOf(item.code), 1); } }); tagsArr.forEach(item => { this.tags.visible.results.push({ code: item, alias: tagsMap[item], }); }); } public handleFormItemChanged() { if (this.modelId > 0) { this.syncPreNextBtnManage.isPreNextBtnConfirm = true; } } public handleCreateTagValidator(value: string) { return !this.tagList.find(tag => tag.alias === value); } public handleTagFilterCallback(value: string, searchKey: string, list: any[]) { let filterData = []; if (Array.isArray(searchKey)) { // 数组,过滤多个关键字 const filterDataList = searchKey.map(key => { return list.filter(item => item[key].toLowerCase().indexOf(value) !== -1); }); filterData = Array.from(new Set(filterDataList.flat())); } else { filterData = list.filter(item => item[searchKey].toLowerCase().indexOf(value) !== -1); } // 完全匹配放在第一个 let index = -1; for (let i = 0, len = filterData.length; i < len; i++) { const item = filterData[i]; if (item.alias === value) { index = i; break; } } if (index > -1) { const firstItem = filterData[index]; filterData.splice(index, 1); filterData.splice(0, 0, firstItem); } return filterData; } public handleCancelClick() { this.loadModelInfo(); } public loadModelInfo() { /** 设置Cancel请求 */ this.handleCancelRequest(this.cancelKey); /** 重置FormData */ this.$set(this, 'formData', JSON.parse(JSON.stringify(this.defaultFormData))); this.$nextTick(() => { this.modelInfoForm && this.modelInfoForm.clearError(); }); if (this.modelId > 0) { this.initPreNextManage(false); this.syncIsLoading = true; getModelInfo(this.modelId, [], this.getCancelToken(this.cancelKey)) .then(res => { res.setData(this, 'formData'); this.formData.tags = this.formData.tags.map(item => item.tag_code); }) ['finally'](() => { this.syncIsLoading = false; }); } if (this.modelId === 0) { // 确保刷新的时候可以取到type this.$nextTick(() => { /** 新增模型时,保存之前下一步不可用 */ this.initPreNextManage(false, false); const storageData = DataModelStorage.get(this.storageKey + this.activeModelTabItem.id); if (storageData) { Object.assign(this.formData, storageData); } else { const item = this.DataModelTabManage.getActiveItem()[0]; this.formData.model_type = item.modelType; } }); } } public handleUpdateModel(item: any) { this.formData.model_alias = item.model_alias; } public getTagList() { getRecommendsTags().then(res => { res.setData(this, 'tags'); }); } public async validateModelName() { if (!this.isNewForm) { return true; } const res = await validateModelName(this.formData.model_name); return !res.data; } public mounted() { this.initPreNextManage(false, !!this.modelId); this.getTagList(); } }
the_stack
import { autoinject, PLATFORM } from 'aurelia-framework'; import { I18N } from 'aurelia-i18n'; import { AureliaGridInstance, AureliaUtilService, Column, EditCommand, Editors, FieldType, Filters, Formatters, GridOption, OnEventArgs, OperatorType, } from '../../aurelia-slickgrid'; import { CustomAureliaViewModelEditor } from './custom-aureliaViewModelEditor'; import { CustomAureliaViewModelFilter } from './custom-aureliaViewModelFilter'; // using external non-typed js libraries declare const Slick: any; const NB_ITEMS = 100; @autoinject() export class Example26 { title = 'Example 26: Use of Aurelia Custom Elements'; subTitle = ` <h3>Filters, Editors, AsyncPostRender with Aurelia Custom Elements</h3> Grid with usage of Aurelia Custom Elements as Editor &amp; AsyncPostRender (similar to Formatter). <ul> <li>Support of Aurelia Custom Element as Custom Editor (click on any "Assignee" name cell)</li> <ul> <li>That column uses a simple select drodown wrapped in an Aurelia Custom Element <li>Increased Grid Options "rowHeight" &amp; "headerRowHeight" to 45 so that the Custom Element fits in the cell.</li> </ul> <li>Support of Aurelia Custom Element as Custom Filter ("Assignee" columns), which also uses Custom Element <li>The 2nd "Assignee" column (showing in bold text) uses "asyncPostRender" with an Aurelia Custom Element</li> <ul> <li>Why can't we use Aurelia Custom Element as Customer Formatter and why do I see a slight delay in loading the data?</li> <li>It's totally normal since SlickGrid Formatters only accept strings (synchronously), so we cannot use that (Aurelia requires at least 1 full cycle to render the element), so we are left with SlickGrid "asyncPostRender" and it works but as the name suggest it's async users might see noticeable delay in loading the data </li> </ul> </ul> `; private _commandQueue: EditCommand[] = []; aureliaGrid!: AureliaGridInstance; gridOptions!: GridOption; columnDefinitions: Column[] = []; dataset: any[] = []; updatedObject: any; isAutoEdit = true; alertWarning: any; selectedLanguage: string; assignees = [ { id: '', name: '' }, { id: '1', name: 'John' }, { id: '2', name: 'Pierre' }, { id: '3', name: 'Paul' }, ]; selectedItem: any; selectedId = ''; constructor(private aureliaUtilService: AureliaUtilService, private i18n: I18N) { // define the grid options & columns and then create the grid itself this.defineGrid(); this.selectedLanguage = this.i18n.getLocale(); } attached() { // populate the dataset once the grid is ready this.dataset = this.mockData(NB_ITEMS); } /* Define grid Options and Columns */ defineGrid() { this.columnDefinitions = [ { id: 'title', name: 'Title', field: 'title', filterable: true, sortable: true, type: FieldType.string, editor: { model: Editors.longText, minLength: 5, maxLength: 255, }, minWidth: 100, onCellChange: (_e: Event, args: OnEventArgs) => { console.log(args); this.alertWarning = `Updated Title: ${args.dataContext.title}`; } }, { id: 'assignee', name: 'Assignee', field: 'assignee', minWidth: 100, filterable: true, sortable: true, filter: { model: new CustomAureliaViewModelFilter(), collection: this.assignees, params: { aureliaUtilService: this.aureliaUtilService, // pass the aureliaUtilService here OR in the grid option params templateUrl: PLATFORM.moduleName('examples/slickgrid/filter-select') // FilterSelect, } }, queryFieldFilter: 'assignee.id', // for a complex object it's important to tell the Filter which field to query and our CustomAureliaComponentFilter returns the "id" property queryFieldSorter: 'assignee.name', formatter: Formatters.complexObject, params: { complexFieldLabel: 'assignee.name', }, exportWithFormatter: true, editor: { model: CustomAureliaViewModelEditor, collection: this.assignees, params: { aureliaUtilService: this.aureliaUtilService, // pass the aureliaUtilService here OR in the grid option params templateUrl: PLATFORM.moduleName('examples/slickgrid/editor-select') // EditorSelect, } }, onCellChange: (_e: Event, args: OnEventArgs) => { console.log(args); this.alertWarning = `Updated Title: ${args.dataContext.title}`; } }, { id: 'assignee2', name: 'Assignee with Aurelia Component', field: 'assignee', minWidth: 125, filterable: true, sortable: true, filter: { model: new CustomAureliaViewModelFilter(), collection: this.assignees, params: { aureliaUtilService: this.aureliaUtilService, // pass the aureliaUtilService here OR in the grid option params templateUrl: PLATFORM.moduleName('examples/slickgrid/filter-select') // FilterSelect, } }, queryFieldFilter: 'assignee.id', // for a complex object it's important to tell the Filter which field to query and our CustomAureliaComponentFilter returns the "id" property queryFieldSorter: 'assignee.name', // loading formatter, text to display while Post Render gets processed formatter: () => '...', // to load an Aurelia Custom Element, you cannot use a Formatter since Aurelia needs at least 1 cycle to render everything // you can use a PostRenderer but you will visually see the data appearing, // which is why it's still better to use regular Formatter (with jQuery if need be) instead of Aurelia Custom Element asyncPostRender: this.renderAureliaComponent.bind(this), params: { templateUrl: PLATFORM.moduleName('examples/slickgrid/custom-title-formatter'), // CustomTitleFormatterCustomElement, complexFieldLabel: 'assignee.name' // for the exportCustomFormatter }, exportCustomFormatter: Formatters.complexObject, }, { id: 'duration', name: 'Duration (days)', field: 'duration', filterable: true, minWidth: 100, sortable: true, type: FieldType.number, filter: { model: Filters.slider, params: { hideSliderNumber: false } }, editor: { model: Editors.slider, minValue: 0, maxValue: 100, // params: { hideSliderNumber: true }, }, /* editor: { // default is 0 decimals, if no decimals is passed it will accept 0 or more decimals // however if you pass the "decimalPlaces", it will validate with that maximum model: Editors.float, minValue: 0, maxValue: 365, // the default validation error message is in English but you can override it by using "errorMessage" // errorMessage: this.i18n.tr('INVALID_FLOAT', { maxDecimal: 2 }), params: { decimalPlaces: 2 }, }, */ }, { id: 'complete', name: '% Complete', field: 'percentComplete', filterable: true, formatter: Formatters.multiple, type: FieldType.number, editor: { // We can also add HTML text to be rendered (any bad script will be sanitized) but we have to opt-in, else it will be sanitized enableRenderHtml: true, collection: Array.from(Array(101).keys()).map(k => ({ value: k, label: k, symbol: '<i class="fa fa-percent" style="color:cadetblue"></i>' })), customStructure: { value: 'value', label: 'label', labelSuffix: 'symbol' }, collectionSortBy: { property: 'label', sortDesc: true }, collectionFilterBy: { property: 'value', value: 0, operator: OperatorType.notEqual }, model: Editors.singleSelect, }, minWidth: 100, params: { formatters: [Formatters.collectionEditor, Formatters.percentCompleteBar], } }, { id: 'start', name: 'Start', field: 'start', filterable: true, filter: { model: Filters.compoundDate }, formatter: Formatters.dateIso, sortable: true, minWidth: 100, type: FieldType.date, editor: { model: Editors.date }, }, { id: 'finish', name: 'Finish', field: 'finish', filterable: true, filter: { model: Filters.compoundDate }, formatter: Formatters.dateIso, sortable: true, minWidth: 100, type: FieldType.date, editor: { model: Editors.date }, } ]; this.gridOptions = { asyncEditorLoading: false, autoEdit: this.isAutoEdit, autoCommitEdit: false, autoResize: { container: '#demo-container', rightPadding: 10 }, rowHeight: 45, // increase row height so that the custom elements fits in the cell editable: true, enableCellNavigation: true, enableColumnPicker: true, enableExcelCopyBuffer: true, enableFiltering: true, enableAsyncPostRender: true, // for the Aurelia PostRenderer, don't forget to enable it asyncPostRenderDelay: 0, // also make sure to remove any delay to render it editCommandHandler: (_item, _column, editCommand) => { this._commandQueue.push(editCommand); editCommand.execute(); }, i18n: this.i18n, params: { aureliaUtilService: this.aureliaUtilService // provide the service to all at once (Editor, Filter, AsyncPostRender) } }; } mockData(itemCount: number, startingIndex = 0) { // mock a dataset const tempDataset = []; for (let i = startingIndex; i < (startingIndex + itemCount); i++) { const randomYear = 2000 + Math.floor(Math.random() * 10); const randomMonth = Math.floor(Math.random() * 11); const randomDay = Math.floor((Math.random() * 29)); const randomPercent = Math.round(Math.random() * 100); tempDataset.push({ id: i, title: 'Task ' + i, assignee: i % 3 ? this.assignees[2] : i % 2 ? this.assignees[1] : this.assignees[0], duration: Math.round(Math.random() * 100) + '', percentComplete: randomPercent, percentCompleteNumber: randomPercent, start: new Date(randomYear, randomMonth, randomDay), finish: new Date(randomYear, (randomMonth + 1), randomDay), effortDriven: (i % 5 === 0), }); } return tempDataset; } onCellChanged(_e: Event, args: any) { console.log('onCellChange', args); this.updatedObject = { ...args.item }; } onCellClicked(_e: Event, args: any) { const metadata = this.aureliaGrid.gridService.getColumnFromEventArguments(args); console.log(metadata); if (metadata.columnDef.id === 'edit') { this.alertWarning = `open a modal window to edit: ${metadata.dataContext.title}`; // highlight the row, to customize the color, you can change the SASS variable $row-highlight-background-color this.aureliaGrid.gridService.highlightRow(args.row, 1500); // you could also select the row, when using "enableCellNavigation: true", it automatically selects the row // this.aureliaGrid.gridService.setSelectedRow(args.row); } else if (metadata.columnDef.id === 'delete') { if (confirm('Are you sure?')) { this.aureliaGrid.gridService.deleteItemById(metadata.dataContext.id); this.alertWarning = `Deleted: ${metadata.dataContext.title}`; } } } onCellValidation(_e: Event, args: any) { alert(args.validationResults.msg); } changeAutoCommit() { this.gridOptions.autoCommitEdit = !this.gridOptions.autoCommitEdit; this.aureliaGrid.slickGrid.setOptions({ autoCommitEdit: this.gridOptions.autoCommitEdit }); return true; } renderAureliaComponent(cellNode: JQuery<HTMLElement>, _row: number, dataContext: any, colDef: Column) { if (colDef.params.templateUrl && cellNode.length) { this.aureliaUtilService.createAureliaViewModelAddToSlot(colDef.params.templateUrl, { model: dataContext }, cellNode[0], true); } } setAutoEdit(isAutoEdit: boolean) { this.isAutoEdit = isAutoEdit; this.aureliaGrid.slickGrid.setOptions({ autoEdit: isAutoEdit }); return true; } switchLanguage() { this.selectedLanguage = (this.selectedLanguage === 'en') ? 'fr' : 'en'; this.i18n.setLocale(this.selectedLanguage); } undo() { const command = this._commandQueue.pop(); if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) { command.undo(); this.aureliaGrid.slickGrid.gotoCell(command.row, command.cell, false); } } }
the_stack
import { HealthState } from './health'; import { Mqtt as IoTHubTransport } from 'azure-iot-device-mqtt'; import { DeviceMethodRequest, DeviceMethodResponse, Client as IoTDeviceClient, Twin, Message as IoTMessage } from 'azure-iot-device'; import * as moment from 'moment'; import { ICameraDeviceProvisionInfo, ModuleService } from './module'; import { AmsGraph } from './amsGraph'; import { bind, defer, emptyObj } from '../utils'; export type DevicePropertiesHandler = (desiredChangedSettings: any) => Promise<void>; export interface IClientConnectResult { clientConnectionStatus: boolean; clientConnectionMessage: string; } export interface IoTDeviceInformation { manufacturer: string; model: string; swVersion: string; osName: string; processorArchitecture: string; processorManufacturer: string; totalStorage: number; totalMemory: number; } const defaultVideoPlaybackHost = 'http://localhost:8094'; export enum IoTCameraSettings { VideoPlaybackHost = 'wpVideoPlaybackHost' } interface IoTCameraSettingsInterface { [IoTCameraSettings.VideoPlaybackHost]: string; } export const AmsDeviceTag = 'rpAmsDeviceTag'; export const AmsDeviceTagValue = 'AmsInferenceDevice.v1'; export enum IoTCentralClientState { Disconnected = 'disconnected', Connected = 'connected' } export enum CameraState { Inactive = 'inactive', Active = 'active' } export const IoTCameraInterface = { Telemetry: { SystemHeartbeat: 'tlSystemHeartbeat' }, State: { IoTCentralClientState: 'stIoTCentralClientState', CameraState: 'stCameraState' }, Property: { CameraName: 'rpCameraName', RtspUrl: 'rpRtspUrl', RtspAuthUsername: 'rpRtspAuthUsername', RtspAuthPassword: 'rpRtspAuthPassword', AmsDeviceTag }, Setting: { VideoPlaybackHost: IoTCameraSettings.VideoPlaybackHost } }; const defaultMaxVideoInferenceTime = 10; export enum LvaEdgeOperationsSettings { AutoStart = 'wpAutoStart', MaxVideoInferenceTime = 'wpMaxVideoInferenceTime' } interface LvaEdgeOperationsSettingsInterface { [LvaEdgeOperationsSettings.AutoStart]: boolean; [LvaEdgeOperationsSettings.MaxVideoInferenceTime]: number; } const LvaEdgeOperationsInterface = { Event: { GraphInstanceCreated: 'evGraphInstanceCreated', GraphInstanceDeleted: 'evGraphInstanceDeleted', GraphInstanceStarted: 'evGraphInstanceStarted', GraphInstanceStopped: 'evGraphInstanceStopped', RecordingStarted: 'evRecordingStarted', RecordingStopped: 'evRecordingStopped', RecordingAvailable: 'evRecordingAvailable', StartLvaGraphCommandReceived: 'evStartLvaGraphCommandReceived', StopLvaGraphCommandReceived: 'evStopLvaGraphCommandReceived' }, Setting: { AutoStart: LvaEdgeOperationsSettings.AutoStart, MaxVideoInferenceTime: LvaEdgeOperationsSettings.MaxVideoInferenceTime }, Command: { StartLvaProcessing: 'cmStartLvaProcessing', StopLvaProcessing: 'cmStopLvaProcessing' } }; export enum LvaEdgeDiagnosticsSettings { DebugTelemetry = 'wpDebugTelemetry' } interface LvaEdgeDiagnosticsSettingsInterface { [LvaEdgeDiagnosticsSettings.DebugTelemetry]: boolean; } export const LvaEdgeDiagnosticsInterface = { Event: { RuntimeError: 'evRuntimeError', AuthenticationError: 'evAuthenticationError', AuthorizationError: 'evAuthorizationError', DataDropped: 'evDataDropped', MediaFormatError: 'evMediaFormatError', MediaSessionEstablished: 'evMediaSessionEstablished', NetworkError: 'evNetworkError', ProtocolError: 'evProtocolError', StorageError: 'evStorageError' }, Setting: { DebugTelemetry: LvaEdgeDiagnosticsSettings.DebugTelemetry } }; const defaultInferenceTimeout = 5; export enum AiInferenceSettings { InferenceTimeout = 'wpInferenceTimeout' } interface AiInferenceSettingsInterface { [AiInferenceSettings.InferenceTimeout]: number; } export const AiInferenceInterface = { Telemetry: { InferenceCount: 'tlInferenceCount', Inference: 'tlInference' }, Event: { InferenceEventVideoUrl: 'evInferenceEventVideoUrl' }, Property: { InferenceVideoUrl: 'rpInferenceVideoUrl', InferenceImageUrl: 'rpInferenceImageUrl' }, Setting: { InferenceTimeout: AiInferenceSettings.InferenceTimeout } }; export abstract class AmsCameraDevice { protected lvaGatewayModule: ModuleService; protected amsGraph: AmsGraph; protected cameraInfo: ICameraDeviceProvisionInfo; protected deviceClient: IoTDeviceClient; protected deviceTwin: Twin; protected deferredStart = defer(); protected healthState = HealthState.Good; protected lastInferenceTime: moment.Moment = moment.utc(0); protected videoInferenceStartTime: moment.Moment = moment.utc(); protected iotCameraSettings: IoTCameraSettingsInterface = { [IoTCameraSettings.VideoPlaybackHost]: defaultVideoPlaybackHost }; protected lvaEdgeOperationsSettings: LvaEdgeOperationsSettingsInterface = { [LvaEdgeOperationsSettings.AutoStart]: false, [LvaEdgeOperationsSettings.MaxVideoInferenceTime]: defaultMaxVideoInferenceTime }; protected lvaEdgeDiagnosticsSettings: LvaEdgeDiagnosticsSettingsInterface = { [LvaEdgeDiagnosticsSettings.DebugTelemetry]: false }; protected aiInferenceSettings: AiInferenceSettingsInterface = { [AiInferenceSettings.InferenceTimeout]: defaultInferenceTimeout }; private inferenceInterval: NodeJS.Timeout; private createVideoLinkForInferenceTimeout = false; constructor(lvaGatewayModule: ModuleService, amsGraph: AmsGraph, cameraInfo: ICameraDeviceProvisionInfo) { this.lvaGatewayModule = lvaGatewayModule; this.amsGraph = amsGraph; this.cameraInfo = cameraInfo; } public abstract setGraphParameters(): any; public abstract deviceReady(): Promise<void>; public abstract processLvaInferences(inferenceData: any): Promise<void>; public abstract getCameraProps(): Promise<IoTDeviceInformation>; public async connectDeviceClient(dpsHubConnectionString: string): Promise<IClientConnectResult> { let clientConnectionResult: IClientConnectResult = { clientConnectionStatus: false, clientConnectionMessage: '' }; try { clientConnectionResult = await this.connectDeviceClientInternal(dpsHubConnectionString, this.onHandleDeviceProperties); if (clientConnectionResult.clientConnectionStatus === true) { await this.deferredStart.promise; await this.deviceReady(); } if (this.lvaEdgeOperationsSettings[LvaEdgeOperationsSettings.AutoStart] === true) { try { await this.startLvaProcessingInternal(true); } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Error while trying to auto-start Lva graph: ${ex.message}`); } } } catch (ex) { clientConnectionResult.clientConnectionStatus = false; clientConnectionResult.clientConnectionMessage = `An error occurred while accessing the device twin properties`; this.lvaGatewayModule.logger(['ModuleService', 'error'], clientConnectionResult.clientConnectionMessage); } return clientConnectionResult; } @bind public async getHealth(): Promise<number> { await this.sendMeasurement({ [IoTCameraInterface.Telemetry.SystemHeartbeat]: this.healthState }); return this.healthState; } public async deleteCamera(): Promise<void> { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Deleting camera device instance for cameraId: ${this.cameraInfo.cameraId}`); try { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Deactiving graph instance: ${this.amsGraph.getInstanceName()}`); await this.amsGraph.deleteLvaGraph(); const clientInterface = this.deviceClient; this.deviceClient = null; await clientInterface.close(); await this.sendMeasurement({ [IoTCameraInterface.State.CameraState]: CameraState.Inactive }); } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Error while deleting camera: ${this.cameraInfo.cameraId}`); } } public async sendLvaEvent(lvaEvent: string, messageJson?: any): Promise<void> { let eventField; let eventValue = this.cameraInfo.cameraId; switch (lvaEvent) { case 'Microsoft.Media.Graph.Operational.RecordingStarted': eventField = LvaEdgeOperationsInterface.Event.RecordingStarted; eventValue = messageJson?.outputLocation || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Operational.RecordingStopped': eventField = LvaEdgeOperationsInterface.Event.RecordingStopped; eventValue = messageJson?.outputLocation || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Operational.RecordingAvailable': eventField = LvaEdgeOperationsInterface.Event.RecordingAvailable; eventValue = messageJson?.outputLocation || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Edge.Diagnostics.RuntimeError': eventField = LvaEdgeDiagnosticsInterface.Event.RuntimeError; eventValue = messageJson?.code || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.AuthenticationError': eventField = LvaEdgeDiagnosticsInterface.Event.AuthenticationError; eventValue = messageJson?.errorCode || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.AuthorizationError': eventField = LvaEdgeDiagnosticsInterface.Event.AuthorizationError; eventValue = messageJson?.errorCode || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.DataDropped': eventField = LvaEdgeDiagnosticsInterface.Event.DataDropped; eventValue = messageJson?.dataType || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.MediaFormatError': eventField = LvaEdgeDiagnosticsInterface.Event.MediaFormatError; eventValue = messageJson?.code || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.MediaSessionEstablished': eventField = LvaEdgeDiagnosticsInterface.Event.MediaSessionEstablished; eventValue = this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.NetworkError': eventField = LvaEdgeDiagnosticsInterface.Event.NetworkError; eventValue = messageJson?.errorCode || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.ProtocolError': eventField = LvaEdgeDiagnosticsInterface.Event.ProtocolError; eventValue = `${messageJson?.protocol}: ${messageJson?.errorCode}` || this.cameraInfo.cameraId; break; case 'Microsoft.Media.Graph.Diagnostics.StorageError': eventField = LvaEdgeDiagnosticsInterface.Event.StorageError; eventValue = messageJson?.storageAccountName || this.cameraInfo.cameraId; break; default: this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'warning'], `Received Unknown Lva event telemetry: ${lvaEvent}`); break; } if (lvaEvent) { await this.sendMeasurement({ [eventField]: eventValue }); } else { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'warning'], `Received Unknown Lva event telemetry: ${lvaEvent}`); } } protected abstract onHandleDeviceProperties(desiredChangedSettings: any): Promise<void>; protected async onHandleDevicePropertiesInternal(desiredChangedSettings: any): Promise<void> { try { this.lvaGatewayModule.logger(['ModuleService', 'info'], `onHandleDeviceProperties`); if (this.lvaEdgeDiagnosticsSettings[LvaEdgeDiagnosticsSettings.DebugTelemetry] === true) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], JSON.stringify(desiredChangedSettings, null, 4)); } const patchedProperties = {}; for (const setting in desiredChangedSettings) { if (!Object.prototype.hasOwnProperty.call(desiredChangedSettings, setting)) { continue; } if (setting === '$version') { continue; } const value = Object.prototype.hasOwnProperty.call(desiredChangedSettings[setting], 'value') ? desiredChangedSettings[setting].value : desiredChangedSettings[setting]; switch (setting) { case IoTCameraInterface.Setting.VideoPlaybackHost: patchedProperties[setting] = (this.iotCameraSettings[setting] as any) = value || defaultVideoPlaybackHost; break; case LvaEdgeOperationsInterface.Setting.AutoStart: patchedProperties[setting] = (this.lvaEdgeOperationsSettings[setting] as any) = value || false; break; case LvaEdgeOperationsInterface.Setting.MaxVideoInferenceTime: patchedProperties[setting] = (this.lvaEdgeOperationsSettings[setting] as any) = value || defaultMaxVideoInferenceTime; break; case LvaEdgeDiagnosticsInterface.Setting.DebugTelemetry: patchedProperties[setting] = (this.lvaEdgeDiagnosticsSettings[setting] as any) = value || false; break; case AiInferenceInterface.Setting.InferenceTimeout: patchedProperties[setting] = (this.aiInferenceSettings[setting] as any) = value || defaultInferenceTimeout; break; default: break; } } if (!emptyObj(patchedProperties)) { await this.updateDeviceProperties(patchedProperties); } } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Exception while handling desired properties: ${ex.message}`); } } protected async updateDeviceProperties(properties: any): Promise<void> { if (!properties || !this.deviceTwin) { return; } try { await new Promise((resolve, reject) => { this.deviceTwin.properties.reported.update(properties, (error) => { if (error) { return reject(error); } return resolve(''); }); }); if (this.lvaEdgeDiagnosticsSettings[LvaEdgeDiagnosticsSettings.DebugTelemetry] === true) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Device live properties updated: ${JSON.stringify(properties, null, 4)}`); } } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Error while updating client properties: ${ex.message}`); } } protected async sendMeasurement(data: any): Promise<void> { if (!data || !this.deviceClient) { return; } try { const iotcMessage = new IoTMessage(JSON.stringify(data)); await this.deviceClient.sendEvent(iotcMessage); if (this.lvaEdgeDiagnosticsSettings[LvaEdgeDiagnosticsSettings.DebugTelemetry] === true) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `sendEvent: ${JSON.stringify(data, null, 4)}`); } } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `sendMeasurement: ${ex.message}`); this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `inspect the error: ${JSON.stringify(ex, null, 4)}`); // TODO: // Detect DPS/Hub reprovisioning scenarios - sample exeption: // // [12:41:54 GMT+0000], [log,[this.cameraInfo.cameraId, error]] data: inspect the error: { // "name": "UnauthorizedError", // "transportError": { // "name": "NotConnectedError", // "transportError": { // "code": 5 // } // } // } } } protected async startLvaProcessingInternal(autoStart: boolean): Promise<boolean> { await this.sendMeasurement({ [LvaEdgeOperationsInterface.Event.StartLvaGraphCommandReceived]: autoStart ? 'AutoStart' : 'Command' }); const startLvaGraphResult = await this.amsGraph.startLvaGraph(this.setGraphParameters()); if (this.lvaEdgeDiagnosticsSettings[LvaEdgeDiagnosticsSettings.DebugTelemetry] === true) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Graph Instance Name: ${JSON.stringify(this.amsGraph.getInstanceName(), null, 4)}`); this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Graph Instance: ${JSON.stringify(this.amsGraph.getInstance(), null, 4)}`); this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Graph Topology Name: ${JSON.stringify(this.amsGraph.getInstanceName(), null, 4)}`); this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Graph Topology: ${JSON.stringify(this.amsGraph.getTopology(), null, 4)}`); } await this.sendMeasurement({ [IoTCameraInterface.State.CameraState]: startLvaGraphResult === true ? CameraState.Active : CameraState.Inactive }); return startLvaGraphResult; } private async inferenceTimer(): Promise<void> { try { if (this.lvaEdgeDiagnosticsSettings[LvaEdgeDiagnosticsSettings.DebugTelemetry] === true) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Inference timer`); } const videoInferenceDuration = moment.duration(moment.utc().diff(this.videoInferenceStartTime)); if (moment.duration(moment.utc().diff(this.lastInferenceTime)) >= moment.duration(this.aiInferenceSettings[AiInferenceSettings.InferenceTimeout], 'seconds')) { if (this.createVideoLinkForInferenceTimeout) { this.createVideoLinkForInferenceTimeout = false; this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `InferenceTimeout reached`); await this.sendMeasurement({ [AiInferenceInterface.Event.InferenceEventVideoUrl]: this.amsGraph.createInferenceVideoLink( this.iotCameraSettings[IoTCameraSettings.VideoPlaybackHost], this.videoInferenceStartTime, Math.trunc(videoInferenceDuration.asSeconds())) }); await this.updateDeviceProperties({ [AiInferenceInterface.Property.InferenceImageUrl]: this.lvaGatewayModule.getSampleImageUrls().ANALYZE }); } this.videoInferenceStartTime = moment.utc(); } else { this.createVideoLinkForInferenceTimeout = true; if (videoInferenceDuration >= moment.duration(this.lvaEdgeOperationsSettings[LvaEdgeOperationsSettings.MaxVideoInferenceTime], 'seconds')) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `MaxVideoInferenceTime reached`); await this.sendMeasurement({ [AiInferenceInterface.Event.InferenceEventVideoUrl]: this.amsGraph.createInferenceVideoLink( this.iotCameraSettings[IoTCameraSettings.VideoPlaybackHost], this.videoInferenceStartTime, Math.trunc(videoInferenceDuration.asSeconds())) }); this.videoInferenceStartTime = moment.utc(); } } } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Inference timer error: ${ex.message}`); } } private async connectDeviceClientInternal( dpsHubConnectionString: string, devicePropertiesHandler: DevicePropertiesHandler): Promise<IClientConnectResult> { const result: IClientConnectResult = { clientConnectionStatus: false, clientConnectionMessage: '' }; if (this.deviceClient) { await this.deviceClient.close(); this.deviceClient = null; } try { this.deviceClient = await IoTDeviceClient.fromConnectionString(dpsHubConnectionString, IoTHubTransport); if (!this.deviceClient) { result.clientConnectionStatus = false; result.clientConnectionMessage = `Failed to connect device client interface from connection string - device: ${this.cameraInfo.cameraId}`; } else { result.clientConnectionStatus = true; result.clientConnectionMessage = `Successfully connected to IoT Central - device: ${this.cameraInfo.cameraId}`; } } catch (ex) { result.clientConnectionStatus = false; result.clientConnectionMessage = `Failed to instantiate client interface from configuraiton: ${ex.message}`; this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `${result.clientConnectionMessage}`); } if (result.clientConnectionStatus === false) { return result; } try { await this.deviceClient.open(); this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `Device client is connected`); this.deviceTwin = await this.deviceClient.getTwin(); this.deviceTwin.on('properties.desired', devicePropertiesHandler); this.deviceClient.on('error', this.onDeviceClientError); this.deviceClient.onDeviceMethod(LvaEdgeOperationsInterface.Command.StartLvaProcessing, this.startLvaProcessing); this.deviceClient.onDeviceMethod(LvaEdgeOperationsInterface.Command.StopLvaProcessing, this.stopLvaProcessing); result.clientConnectionStatus = true; } catch (ex) { result.clientConnectionStatus = false; result.clientConnectionMessage = `IoT Central connection error: ${ex.message}`; this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], result.clientConnectionMessage); } return result; } @bind private onDeviceClientError(error: Error) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Device client connection error: ${error.message}`); this.healthState = HealthState.Critical; } @bind // @ts-ignore private async startLvaProcessing(commandRequest: DeviceMethodRequest, commandResponse: DeviceMethodResponse) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `${LvaEdgeOperationsInterface.Command.StartLvaProcessing} command received`); try { const startLvaGraphResult = await this.startLvaProcessingInternal(false); const responseMessage = `LVA Edge start graph request: ${startLvaGraphResult ? 'succeeded' : 'failed'}`; this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], responseMessage); await commandResponse.send(200, { message: responseMessage }); if (startLvaGraphResult) { this.lastInferenceTime = moment.utc(0); this.videoInferenceStartTime = moment.utc(); this.createVideoLinkForInferenceTimeout = false; this.inferenceInterval = setInterval(async () => { await this.inferenceTimer(); }, 1000); } } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `startLvaProcessing error: ${ex.message}`); } } @bind // @ts-ignore private async stopLvaProcessing(commandRequest: DeviceMethodRequest, commandResponse: DeviceMethodResponse) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], `${LvaEdgeOperationsInterface.Command.StopLvaProcessing} command received`); try { clearInterval(this.inferenceInterval); await this.sendMeasurement({ [LvaEdgeOperationsInterface.Event.StopLvaGraphCommandReceived]: this.cameraInfo.cameraId }); const stopLvaGraphResult = await this.amsGraph.stopLvaGraph(); if (stopLvaGraphResult) { await this.sendMeasurement({ [IoTCameraInterface.State.CameraState]: CameraState.Inactive }); } const responseMessage = `LVA Edge stop graph request: ${stopLvaGraphResult ? 'succeeded' : 'failed'}`; this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'info'], responseMessage); await commandResponse.send(200, { message: responseMessage }); } catch (ex) { this.lvaGatewayModule.logger([this.cameraInfo.cameraId, 'error'], `Stop LVA error ${ex.message}`); } } }
the_stack
import path from 'path'; import { Harmony } from '@teambit/harmony'; import { difference } from 'ramda'; import { compact } from 'ramda-adjunct'; import { Consumer, loadConsumer } from '../../consumer'; import { ScopeExtension } from '../scope'; import { Component, ComponentFactory, ComponentID } from '../component'; import ComponentsList from '../../consumer/component/components-list'; import { BitIds, BitId } from '../../bit-id'; import { IsolatorExtension } from '../isolator'; import ConsumerComponent from '../../consumer/component'; import { ResolvedComponent } from '../utils/resolved-component/resolved-component'; import AddComponents from '../../consumer/component-ops/add-components'; import { PathOsBasedRelative, PathOsBased } from '../../utils/path'; import { AddActionResults } from '../../consumer/component-ops/add-components/add-components'; import { IExtensionConfigList } from '../../consumer/config'; import { DependencyResolverExtension } from '../dependency-resolver'; import { WorkspaceExtConfig } from './types'; import { ComponentHost, LogPublisher } from '../types'; import { loadResolvedExtensions } from '../utils/load-extensions'; import { Variants } from '../variants'; import LegacyComponentConfig from '../../consumer/config'; import { ComponentScopeDirMap } from '../config/workspace-config'; import legacyLogger from '../../logger/logger'; import { removeExistingLinksInNodeModules, symlinkCapsulesInNodeModules } from './utils'; /** * API of the Bit Workspace */ export default class Workspace implements ComponentHost { owner?: string; componentsScopeDirsMap: ComponentScopeDirMap; constructor( private config: WorkspaceExtConfig, /** * private access to the legacy consumer instance. */ public consumer: Consumer, /** * access to the Workspace's `Scope` instance */ readonly scope: ScopeExtension, /** * access to the `ComponentProvider` instance */ private componentFactory: ComponentFactory, readonly isolateEnv: IsolatorExtension, private dependencyResolver: DependencyResolverExtension, private variants: Variants, private logger: LogPublisher, private componentList: ComponentsList = new ComponentsList(consumer), /** * private reference to the instance of Harmony. */ private harmony: Harmony ) { this.owner = this.config?.defaultOwner; this.componentsScopeDirsMap = this.config?.components || []; } /** * root path of the Workspace. */ get path() { return this.consumer.getPath(); } /** * provides status of all components in the workspace. */ status() {} /** * list all workspace components. */ async list(): Promise<Component[]> { const consumerComponents = await this.componentList.getAuthoredAndImportedFromFS(); return this.transformLegacyComponents(consumerComponents); } private async transformLegacyComponents(consumerComponents: ConsumerComponent[]) { const transformP = consumerComponents.map(consumerComponent => { return this.componentFactory.fromLegacyComponent(consumerComponent); }); return Promise.all(transformP); } /** * list all modified components in the workspace. */ async modified() { const consumerComponents = await this.componentList.listModifiedComponents(true); // @ts-ignore return this.transformLegacyComponents(consumerComponents); } /** * list all new components in the workspace. */ async newComponents() { const consumerComponents = await this.componentList.listNewComponents(true); // @ts-ignore return this.transformLegacyComponents(consumerComponents); } async loadCapsules(bitIds: string[]) { // throw new Error("Method not implemented."); const components = await this.load(bitIds); return components.map(comp => comp.capsule); } /** * fully load components, including dependency resolution and prepare them for runtime. * @todo: remove the string option, use only BitId * fully load components, including dependency resolution and prepare them for runtime. */ async load(ids: Array<BitId | string>): Promise<ResolvedComponent[]> { const components = await this.getMany(ids); const isolatedEnvironment = await this.isolateEnv.createNetworkFromConsumer( components.map(c => c.id.toString()), this.consumer, { packageManager: 'npm' } ); const capsulesMap = isolatedEnvironment.capsules.reduce((accum, curr) => { accum[curr.id.toString()] = curr.capsule; return accum; }, {}); const ret = components.map(component => new ResolvedComponent(component, capsulesMap[component.id.toString()])); return ret; } /** * @todo: remove the string option, use only BitId * get a component from workspace * @param id component ID */ async get(id: string | BitId | ComponentID): Promise<Component | undefined> { const getBitId = (): BitId => { if (id instanceof ComponentID) return id._legacy; if (typeof id === 'string') return this.consumer.getParsedId(id); return id; }; const componentId = getBitId(); if (!componentId) return undefined; const legacyComponent = await this.consumer.loadComponent(componentId); return this.componentFactory.fromLegacyComponent(legacyComponent); } // @gilad needs to implment on variants // eslint-disable-next-line @typescript-eslint/no-unused-vars async byPattern(pattern: string): Promise<Component[]> { // @todo: this is a naive implementation, replace it with a real one. const all = await this.list(); return all.filter(c => c.id.toString() === pattern); } /** * @todo: remove the string option, use only BitId */ async getMany(ids: Array<BitId | string>) { const componentIds = ids.map(id => (typeof id === 'string' ? this.consumer.getParsedId(id) : id)); const idsWithoutEmpty = compact(componentIds); const legacyComponents = await this.consumer.loadComponents(BitIds.fromArray(idsWithoutEmpty)); // @ts-ignore return this.transformLegacyComponents(legacyComponents.components); } /** * track a new component. (practically, add it to .bitmap). * * @param componentPaths component paths relative to the workspace dir * @param id if not set, will be concluded from the filenames * @param main if not set, will try to guess according to some strategies and throws if failed * @param override whether add details to an existing component or re-define it */ async add( componentPaths: PathOsBasedRelative[], id?: string, main?: string, override = false ): Promise<AddActionResults> { const addComponent = new AddComponents({ consumer: this.consumer }, { componentPaths, id, main, override }); const addResults = await addComponent.add(); // @todo: the legacy commands have `consumer.onDestroy()` on command completion, it writes the // .bitmap file. workspace needs a similar mechanism. once done, remove the next line. await this.consumer.bitMap.write(); return addResults; } /** * Get the component root dir in the file system (relative to workspace or full) * @param componentId * @param relative return the path relative to the workspace or full path */ componentDir(componentId: BitId, relative = false): PathOsBased | undefined { const componentMap = this.consumer.bitMap.getComponent(componentId); const relativeComponentDir = componentMap.getComponentDir(); if (relative) { return relativeComponentDir; } if (relativeComponentDir) { return path.join(this.path, relativeComponentDir); } return undefined; } // TODO: gilad - add return value /** * Calculate the component config based on the component.json file in the component folder and the matching * pattern in the variants config * @param componentId */ // componentConfig(componentId: BitId) { // TODO: read the component.json file and merge it inside // const inlineConfig = this.inlineComponentConfig(componentId); // const variantConfig = this.variants.getComponentConfig(componentId); // For legacy configs it will be undefined. // This should be changed once we have basic dependnecy-resolver and pkg extensions see more at src/extensions/config/workspace-config.ts // under transformLegacyPropsToExtensions // if (!variantConfig) { // } // } // TODO: gilad - add return value /** * return the component config from its folder (bit.json / package.json / component.json) * @param componentId */ private inlineComponentConfig(componentId: BitId) { // TODO: Load from component.json file const legacyConfigProps = LegacyComponentConfig.loadConfigFromFolder({ workspaceDir: this.path, componentDir: this.componentDir(componentId) }); // TODO: make sure it's a new format return legacyConfigProps; } // async loadComponentExtensions(componentId: BitId): Promise<void> { // const config = this.componentConfig(componentId); // const extensions = config.extensions // ? ExtensionConfigList.fromObject(config.extensions) // : ExtensionConfigList.fromArray([]); // return this.loadExtensions(extensions); // } /** * Load all unloaded extensions from a list * @param extensions list of extensions with config to load */ async loadExtensions(extensions: IExtensionConfigList): Promise<void> { const extensionsIds = extensions.ids; const loadedExtensions = this.harmony.extensionsIds; const extensionsToLoad = difference(extensionsIds, loadedExtensions); if (!extensionsToLoad.length) return; let resolvedExtensions: ResolvedComponent[] = []; resolvedExtensions = await this.load(extensionsToLoad); // TODO: change to use the new reporter API, in order to implement this // we would have to have more than 1 instance of the Reporter extension (one for the workspace and one for the CLI command) // // We need to think of a facility to show "system messages that do not stop execution" like this. We might want to (for example) // have each command query the logger for such messages and decide whether to display them or not (according to the verbosity // level passed to it). await loadResolvedExtensions(this.harmony, resolvedExtensions, legacyLogger); } /** * Install dependencies for all components in the workspace * * @returns * @memberof Workspace */ async install() { // this.reporter.info('Installing component dependencies'); // this.reporter.setStatusText('Installing'); const components = await this.list(); // this.reporter.info('Isolating Components'); const isolatedEnvs = await this.load(components.map(c => c.id.toString())); // this.reporter.info('Installing workspace dependencies'); await removeExistingLinksInNodeModules(isolatedEnvs); await this.dependencyResolver.folderInstall(process.cwd()); await symlinkCapsulesInNodeModules(isolatedEnvs); // this.reporter.end(); return isolatedEnvs; } /** * this should be rarely in-use. * it's currently used by watch extension as a quick workaround to load .bitmap and the components */ async _reloadConsumer() { this.consumer = await loadConsumer(this.path, true); } // TODO: should we return here the dir as it defined (aka components) or with /{name} prefix (as it used in legacy) get defaultDirectory(): string { return this.config.defaultDirectory; } get legacyDefaultDirectory(): string { if (this.defaultDirectory && !this.defaultDirectory.includes('{name}')) { return `${this.defaultDirectory}/{name}`; } return this.defaultDirectory; } }
the_stack
export declare type Vec3 = [number, number, number]; export interface UVW { u: number; v: number; w: number; } export interface TextureMapData { colorCorrection: boolean; horizontalBlending: boolean; verticalBlending: boolean; boostMipMapSharpness: number; modifyTextureMap: { brightness: number; contrast: number; }; offset: UVW; scale: UVW; turbulence: UVW; clamp: boolean; textureResolution: number | null; bumpMultiplier: number; imfChan: string | null; filename: string; reflectionType?: string; texture?: HTMLImageElement; } /** * The Material class. */ export declare class Material { name: string; /** * Constructor * @param {String} name the unique name of the material */ ambient: Vec3; diffuse: Vec3; specular: Vec3; emissive: Vec3; transmissionFilter: Vec3; dissolve: number; specularExponent: number; transparency: number; illumination: number; refractionIndex: number; sharpness: number; mapDiffuse: TextureMapData; mapAmbient: TextureMapData; mapSpecular: TextureMapData; mapSpecularExponent: TextureMapData; mapDissolve: TextureMapData; antiAliasing: boolean; mapBump: TextureMapData; mapDisplacement: TextureMapData; mapDecal: TextureMapData; mapEmissive: TextureMapData; mapReflections: TextureMapData[]; constructor(name: string); } /** * https://en.wikipedia.org/wiki/Wavefront_.obj_file * http://paulbourke.net/dataformats/mtl/ */ export declare class MaterialLibrary { data: string; /** * Constructs the Material Parser * @param mtlData the MTL file contents */ currentMaterial: Material; materials: { [k: string]: Material; }; constructor(data: string); /** * Creates a new Material object and adds to the registry. * @param tokens the tokens associated with the directive */ parse_newmtl(tokens: string[]): void; /** * See the documenation for parse_Ka below for a better understanding. * * Given a list of possible color tokens, returns an array of R, G, and B * color values. * * @param tokens the tokens associated with the directive * @return {*} a 3 element array containing the R, G, and B values * of the color. */ parseColor(tokens: string[]): Vec3; /** * Parse the ambient reflectivity * * A Ka directive can take one of three forms: * - Ka r g b * - Ka spectral file.rfl * - Ka xyz x y z * These three forms are mutually exclusive in that only one * declaration can exist per material. It is considered a syntax * error otherwise. * * The "Ka" form specifies the ambient reflectivity using RGB values. * The "g" and "b" values are optional. If only the "r" value is * specified, then the "g" and "b" values are assigned the value of * "r". Values are normally in the range 0.0 to 1.0. Values outside * of this range increase or decrease the reflectivity accordingly. * * The "Ka spectral" form specifies the ambient reflectivity using a * spectral curve. "file.rfl" is the name of the ".rfl" file containing * the curve data. "factor" is an optional argument which is a multiplier * for the values in the .rfl file and defaults to 1.0 if not specified. * * The "Ka xyz" form specifies the ambient reflectivity using CIEXYZ values. * "x y z" are the values of the CIEXYZ color space. The "y" and "z" arguments * are optional and take on the value of the "x" component if only "x" is * specified. The "x y z" values are normally in the range of 0.0 to 1.0 and * increase or decrease ambient reflectivity accordingly outside of that * range. * * @param tokens the tokens associated with the directive */ parse_Ka(tokens: string[]): void; /** * Diffuse Reflectivity * * Similar to the Ka directive. Simply replace "Ka" with "Kd" and the rules * are the same * * @param tokens the tokens associated with the directive */ parse_Kd(tokens: string[]): void; /** * Spectral Reflectivity * * Similar to the Ka directive. Simply replace "Ks" with "Kd" and the rules * are the same * * @param tokens the tokens associated with the directive */ parse_Ks(tokens: string[]): void; /** * Emissive * * The amount and color of light emitted by the object. * * @param tokens the tokens associated with the directive */ parse_Ke(tokens: string[]): void; /** * Transmission Filter * * Any light passing through the object is filtered by the transmission * filter, which only allows specific colors to pass through. For example, Tf * 0 1 0 allows all of the green to pass through and filters out all of the * red and blue. * * Similar to the Ka directive. Simply replace "Ks" with "Tf" and the rules * are the same * * @param tokens the tokens associated with the directive */ parse_Tf(tokens: string[]): void; /** * Specifies the dissolve for the current material. * * Statement: d [-halo] `factor` * * Example: "d 0.5" * * The factor is the amount this material dissolves into the background. A * factor of 1.0 is fully opaque. This is the default when a new material is * created. A factor of 0.0 is fully dissolved (completely transparent). * * Unlike a real transparent material, the dissolve does not depend upon * material thickness nor does it have any spectral character. Dissolve works * on all illumination models. * * The dissolve statement allows for an optional "-halo" flag which indicates * that a dissolve is dependent on the surface orientation relative to the * viewer. For example, a sphere with the following dissolve, "d -halo 0.0", * will be fully dissolved at its center and will appear gradually more opaque * toward its edge. * * "factor" is the minimum amount of dissolve applied to the material. The * amount of dissolve will vary between 1.0 (fully opaque) and the specified * "factor". The formula is: * * dissolve = 1.0 - (N*v)(1.0-factor) * * @param tokens the tokens associated with the directive */ parse_d(tokens: string[]): void; /** * The "illum" statement specifies the illumination model to use in the * material. Illumination models are mathematical equations that represent * various material lighting and shading effects. * * The illumination number can be a number from 0 to 10. The following are * the list of illumination enumerations and their summaries: * 0. Color on and Ambient off * 1. Color on and Ambient on * 2. Highlight on * 3. Reflection on and Ray trace on * 4. Transparency: Glass on, Reflection: Ray trace on * 5. Reflection: Fresnel on and Ray trace on * 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on * 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on * 8. Reflection on and Ray trace off * 9. Transparency: Glass on, Reflection: Ray trace off * 10. Casts shadows onto invisible surfaces * * Example: "illum 2" to specify the "Highlight on" model * * @param tokens the tokens associated with the directive */ parse_illum(tokens: string[]): void; /** * Optical Density (AKA Index of Refraction) * * Statement: Ni `index` * * Example: Ni 1.0 * * Specifies the optical density for the surface. `index` is the value * for the optical density. The values can range from 0.001 to 10. A value of * 1.0 means that light does not bend as it passes through an object. * Increasing the optical_density increases the amount of bending. Glass has * an index of refraction of about 1.5. Values of less than 1.0 produce * bizarre results and are not recommended * * @param tokens the tokens associated with the directive */ parse_Ni(tokens: string[]): void; /** * Specifies the specular exponent for the current material. This defines the * focus of the specular highlight. * * Statement: Ns `exponent` * * Example: "Ns 250" * * `exponent` is the value for the specular exponent. A high exponent results * in a tight, concentrated highlight. Ns Values normally range from 0 to * 1000. * * @param tokens the tokens associated with the directive */ parse_Ns(tokens: string[]): void; /** * Specifies the sharpness of the reflections from the local reflection map. * * Statement: sharpness `value` * * Example: "sharpness 100" * * If a material does not have a local reflection map defined in its material * defintions, sharpness will apply to the global reflection map defined in * PreView. * * `value` can be a number from 0 to 1000. The default is 60. A high value * results in a clear reflection of objects in the reflection map. * * Tip: sharpness values greater than 100 introduce aliasing effects in * flat surfaces that are viewed at a sharp angle. * * @param tokens the tokens associated with the directive */ parse_sharpness(tokens: string[]): void; /** * Parses the -cc flag and updates the options object with the values. * * @param values the values passed to the -cc flag * @param options the Object of all image options */ parse_cc(values: string[], options: TextureMapData): void; /** * Parses the -blendu flag and updates the options object with the values. * * @param values the values passed to the -blendu flag * @param options the Object of all image options */ parse_blendu(values: string[], options: TextureMapData): void; /** * Parses the -blendv flag and updates the options object with the values. * * @param values the values passed to the -blendv flag * @param options the Object of all image options */ parse_blendv(values: string[], options: TextureMapData): void; /** * Parses the -boost flag and updates the options object with the values. * * @param values the values passed to the -boost flag * @param options the Object of all image options */ parse_boost(values: string[], options: TextureMapData): void; /** * Parses the -mm flag and updates the options object with the values. * * @param values the values passed to the -mm flag * @param options the Object of all image options */ parse_mm(values: string[], options: TextureMapData): void; /** * Parses and sets the -o, -s, and -t u, v, and w values * * @param values the values passed to the -o, -s, -t flag * @param {Object} option the Object of either the -o, -s, -t option * @param {Integer} defaultValue the Object of all image options */ parse_ost(values: string[], option: UVW, defaultValue: number): void; /** * Parses the -o flag and updates the options object with the values. * * @param values the values passed to the -o flag * @param options the Object of all image options */ parse_o(values: string[], options: TextureMapData): void; /** * Parses the -s flag and updates the options object with the values. * * @param values the values passed to the -s flag * @param options the Object of all image options */ parse_s(values: string[], options: TextureMapData): void; /** * Parses the -t flag and updates the options object with the values. * * @param values the values passed to the -t flag * @param options the Object of all image options */ parse_t(values: string[], options: TextureMapData): void; /** * Parses the -texres flag and updates the options object with the values. * * @param values the values passed to the -texres flag * @param options the Object of all image options */ parse_texres(values: string[], options: TextureMapData): void; /** * Parses the -clamp flag and updates the options object with the values. * * @param values the values passed to the -clamp flag * @param options the Object of all image options */ parse_clamp(values: string[], options: TextureMapData): void; /** * Parses the -bm flag and updates the options object with the values. * * @param values the values passed to the -bm flag * @param options the Object of all image options */ parse_bm(values: string[], options: TextureMapData): void; /** * Parses the -imfchan flag and updates the options object with the values. * * @param values the values passed to the -imfchan flag * @param options the Object of all image options */ parse_imfchan(values: string[], options: TextureMapData): void; /** * This only exists for relection maps and denotes the type of reflection. * * @param values the values passed to the -type flag * @param options the Object of all image options */ parse_type(values: string[], options: TextureMapData): void; /** * Parses the texture's options and returns an options object with the info * * @param tokens all of the option tokens to pass to the texture * @return {Object} a complete object of objects to apply to the texture */ parseOptions(tokens: string[]): TextureMapData; /** * Parses the given texture map line. * * @param tokens all of the tokens representing the texture * @return a complete object of objects to apply to the texture */ parseMap(tokens: string[]): TextureMapData; /** * Parses the ambient map. * * @param tokens list of tokens for the map_Ka direcive */ parse_map_Ka(tokens: string[]): void; /** * Parses the diffuse map. * * @param tokens list of tokens for the map_Kd direcive */ parse_map_Kd(tokens: string[]): void; /** * Parses the specular map. * * @param tokens list of tokens for the map_Ks direcive */ parse_map_Ks(tokens: string[]): void; /** * Parses the emissive map. * * @param tokens list of tokens for the map_Ke direcive */ parse_map_Ke(tokens: string[]): void; /** * Parses the specular exponent map. * * @param tokens list of tokens for the map_Ns direcive */ parse_map_Ns(tokens: string[]): void; /** * Parses the dissolve map. * * @param tokens list of tokens for the map_d direcive */ parse_map_d(tokens: string[]): void; /** * Parses the anti-aliasing option. * * @param tokens list of tokens for the map_aat direcive */ parse_map_aat(tokens: string[]): void; /** * Parses the bump map. * * @param tokens list of tokens for the map_bump direcive */ parse_map_bump(tokens: string[]): void; /** * Parses the bump map. * * @param tokens list of tokens for the bump direcive */ parse_bump(tokens: string[]): void; /** * Parses the disp map. * * @param tokens list of tokens for the disp direcive */ parse_disp(tokens: string[]): void; /** * Parses the decal map. * * @param tokens list of tokens for the map_decal direcive */ parse_decal(tokens: string[]): void; /** * Parses the refl map. * * @param tokens list of tokens for the refl direcive */ parse_refl(tokens: string[]): void; /** * Parses the MTL file. * * Iterates line by line parsing each MTL directive. * * This function expects the first token in the line * to be a valid MTL directive. That token is then used * to try and run a method on this class. parse_[directive] * E.g., the `newmtl` directive would try to call the method * parse_newmtl. Each parsing function takes in the remaining * list of tokens and updates the currentMaterial class with * the attributes provided. */ parse(): void; }
the_stack
import { Draft, produce } from 'immer'; import { clamp } from 'lodash-es'; import { DiagramMakerAction } from 'diagramMaker/state/actions'; import { EditorActionsType, FitAction, FocusNodeAction } from 'diagramMaker/state/editor/editorActions'; import { NodeActionsType } from 'diagramMaker/state/node/nodeActions'; import { DiagramMakerWorkspace, Position, Size } from 'diagramMaker/state/types'; import { createDragWorkspaceAction, createResizeWorkspaceCanvasAction } from 'diagramMaker/state/workspace/workspaceActionDispatcher'; import { DragWorkspaceAction, ResizeWorkspaceAction, ResizeWorkspaceCanvasAction, WorkspaceActionsType, ZoomWorkspaceAction } from 'diagramMaker/state/workspace/workspaceActions'; const ZoomDefaults = { MAX: 3, MIN: 0.3, SPEED: 0.006 }; const FIT_BUFFER = 50; export function getDefaultWorkspaceState(): DiagramMakerWorkspace { return { position: { x: 0, y: 0 }, scale: 1, canvasSize: { width: 3200, height: 1600 }, viewContainerSize: { width: 1600, height: 800 } }; } const clampPosition = (position: Position, size: Size, zoom: number, containerSize: Size): Position => { const x = clamp(position.x, -1 * Math.max(0, size.width * zoom - containerSize.width), 0); const y = clamp(position.y, -1 * Math.max(0, size.height * zoom - containerSize.height), 0); return { x, y }; }; const clampZoom = (zoom: number, size: Size, containerSize: Size): number => { const zoomMin = Math.max(ZoomDefaults.MIN, containerSize.width / size.width, containerSize.height / size.height); const clampedZoom = Math.max(zoomMin, Math.min(ZoomDefaults.MAX, zoom)); return Number(clampedZoom.toPrecision(4)); }; const getNewZoomLevel = (currentState: Draft<DiagramMakerWorkspace>, action: ZoomWorkspaceAction): number => { const zoom = currentState.scale; const zoomFactor = Math.max(-1, Math.min(1, zoom)) * ZoomDefaults.SPEED; const containerSize = currentState.viewContainerSize; const newZoom = clampZoom(zoom + action.payload.zoom * zoomFactor, currentState.canvasSize, containerSize); return newZoom; }; const getNewZoomPosition = ( position: Position, workspacePosition: Position, zoom: number, newZoom: number ): Position => { const zoomTargetX = (position.x - workspacePosition.x) / zoom; const zoomTargetY = (position.y - workspacePosition.y) / zoom; const x = Math.round(-1 * zoomTargetX * newZoom + position.x); const y = Math.round(-1 * zoomTargetY * newZoom + position.y); return { x, y }; }; const getNewDragPosition = ( currentState: Draft<DiagramMakerWorkspace>, action: DragWorkspaceAction ): Position => { const x = action.payload.position.x; const y = action.payload.position.y; const containerSize = currentState.viewContainerSize; const newPosition = clampPosition({ x, y }, currentState.canvasSize, currentState.scale, containerSize); return newPosition; }; const zoomReducer = (draftState: Draft<DiagramMakerWorkspace>, action: ZoomWorkspaceAction) => { const currentWorkspace = draftState; const { position } = action.payload; const workspaceSize = currentWorkspace.canvasSize; const containerSize = draftState.viewContainerSize; const newScale = getNewZoomLevel(currentWorkspace, action); const { x, y } = getNewZoomPosition( position, currentWorkspace.position, currentWorkspace.scale, newScale ); const newPosition = clampPosition({ x, y }, workspaceSize, newScale, containerSize); currentWorkspace.scale = newScale; currentWorkspace.position = newPosition; }; const dragReducer = (draftState: Draft<DiagramMakerWorkspace>, action: DragWorkspaceAction) => { const currentWorkspace = draftState; currentWorkspace.position = getNewDragPosition(currentWorkspace, action); }; const resizeReducer = (draftState: Draft<DiagramMakerWorkspace>, action: ResizeWorkspaceAction) => { const currentWorkspace = draftState; currentWorkspace.viewContainerSize = action.payload.containerSize; currentWorkspace.scale = clampZoom( currentWorkspace.scale, currentWorkspace.canvasSize, currentWorkspace.viewContainerSize ); currentWorkspace.position = clampPosition( currentWorkspace.position, currentWorkspace.canvasSize, currentWorkspace.scale, currentWorkspace.viewContainerSize ); }; const canvasResizeReducer = (draftState: Draft<DiagramMakerWorkspace>, action: ResizeWorkspaceCanvasAction) => { const currentWorkspace = draftState; currentWorkspace.canvasSize = action.payload.canvasSize; }; const focusReducer = (draftState: Draft<DiagramMakerWorkspace>, action: FocusNodeAction) => { draftState.scale = 1; const { position, size, id } = action.payload; const nodeCenter = { x: position.x + (size.width / 2), y: position.y + (size.height / 2) }; const { canvasSize, viewContainerSize } = draftState; const leftOffset = action.payload.leftPanelWidth || 0; const rightOffset = action.payload.rightPanelWidth || 0; const updatedViewContainer: Size = { width: viewContainerSize.width - leftOffset - rightOffset, height: viewContainerSize.height }; const workspacePosition = { x: (updatedViewContainer.width / 2) - nodeCenter.x + leftOffset, y: (updatedViewContainer.height / 2) - nodeCenter.y }; draftState.position = clampPosition(workspacePosition, canvasSize, 1, updatedViewContainer); }; const fitReducer = (draftState: Draft<DiagramMakerWorkspace>, action: FitAction) => { const { nodeRects } = action.payload; let minX = draftState.canvasSize.width; let minY = draftState.canvasSize.height; let maxX = 0; let maxY = 0; nodeRects.forEach((rect) => { minX = Math.min(minX, rect.position.x - FIT_BUFFER); minY = Math.min(minY, rect.position.y - FIT_BUFFER); maxX = Math.max(maxX, rect.position.x + rect.size.width + FIT_BUFFER); maxY = Math.max(maxY, rect.position.y + rect.size.height + FIT_BUFFER); }); const { canvasSize, viewContainerSize } = draftState; const expectedWidth = maxX - minX; const expctedHeight = maxY - minY; const leftOffset = action.payload.leftPanelWidth || 0; const rightOffset = action.payload.rightPanelWidth || 0; const updatedViewContainer: Size = { width: viewContainerSize.width - leftOffset - rightOffset, height: viewContainerSize.height }; const scaleForWidth = updatedViewContainer.width / expectedWidth; const scaleForHeight = updatedViewContainer.height / expctedHeight; const expectedScale = Math.min(scaleForHeight, scaleForWidth); const scale = clampZoom(expectedScale, canvasSize, updatedViewContainer); const expectedPosition = { x: (-minX * scale) + leftOffset, y: -minY * scale }; const position = clampPosition(expectedPosition, canvasSize, scale, updatedViewContainer); draftState.scale = scale; draftState.position = position; }; const resetZoomReducer = (draftState: Draft<DiagramMakerWorkspace>) => { const scale = 1; const { canvasSize, viewContainerSize } = draftState; const workspaceCenter = { x: canvasSize.width / 2, y: canvasSize.height / 2 }; const viewContainerCenter = { x: viewContainerSize.width / 2, y: viewContainerSize.height / 2 }; const position = { x: viewContainerCenter.x - workspaceCenter.x, y: viewContainerCenter.y - workspaceCenter.y }; draftState.scale = 1; draftState.position = clampPosition(position, canvasSize, 1, viewContainerSize); }; export default function workspaceReducer<NodeType, EdgeType>( state: DiagramMakerWorkspace | undefined, action: DiagramMakerAction<NodeType, EdgeType> ): DiagramMakerWorkspace { if (state === undefined) { return getDefaultWorkspaceState(); } switch (action.type) { case WorkspaceActionsType.WORKSPACE_DRAG: return produce(state, (draftState) => { dragReducer(draftState, action); }); case WorkspaceActionsType.WORKSPACE_ZOOM: return produce(state, (draftState) => { zoomReducer(draftState, action); }); case WorkspaceActionsType.WORKSPACE_RESIZE: return produce(state, (draftState) => { resizeReducer(draftState, action); }); case EditorActionsType.FOCUS_NODE: return produce(state, (draftState) => { focusReducer(draftState, action); }); case EditorActionsType.FIT: return produce(state, (draftState) => { fitReducer(draftState, action); }); case WorkspaceActionsType.WORKSPACE_RESET_ZOOM: return produce(state, (draftState) => { resetZoomReducer(draftState); }); case NodeActionsType.NODE_DRAG: return produce(state, (draftState) => { const canvasSize = state.canvasSize; const workspacePos = state.position; const nodePos = action.payload.position; const nodeSize = action.payload.size; // Resize and move workspace when node is dragged outside right boundary if (nodePos.x + nodeSize.width > canvasSize.width) { const incrementWidth = nodePos.x + nodeSize.width - canvasSize.width; const newCanvasSize = { height: canvasSize.height, width: canvasSize.width + incrementWidth }; const newWokspacePos = { x: workspacePos.x - incrementWidth, y: workspacePos.y }; const resizeAction = createResizeWorkspaceCanvasAction(newCanvasSize); const dragAction = createDragWorkspaceAction(newWokspacePos); canvasResizeReducer(draftState, resizeAction); dragReducer(draftState, dragAction); } // Resize and move workspace when node is dragged outside bottom boundary if (nodePos.y + nodeSize.height > canvasSize.height) { const incrementHeight = nodePos.y + nodeSize.height - canvasSize.height; const newCanvasSize = { height: canvasSize.height + incrementHeight, width: canvasSize.width }; const newWokspacePos = { x: workspacePos.x, y: workspacePos.y - incrementHeight }; const resizeAction = createResizeWorkspaceCanvasAction(newCanvasSize); const dragAction = createDragWorkspaceAction(newWokspacePos); canvasResizeReducer(draftState, resizeAction); dragReducer(draftState, dragAction); } // Resize workspace when node is dragged outside top boundary if (nodePos.y < 0) { const incrementHeight = - nodePos.y; const newCanvasSize = { height: canvasSize.height + incrementHeight, width: canvasSize.width }; const resizeAction = createResizeWorkspaceCanvasAction(newCanvasSize); canvasResizeReducer(draftState, resizeAction); } // Resize workspace when node is dragged outside left boundary if (nodePos.x < 0) { const incrementWidth = - nodePos.x; const newCanvasSize = { height: canvasSize.height, width: canvasSize.width + incrementWidth }; const resizeAction = createResizeWorkspaceCanvasAction(newCanvasSize); canvasResizeReducer(draftState, resizeAction); } }); default: return state; } }
the_stack
import { NewExpression, Identifier, TemplateString, ArrayLiteral, CastExpression, BooleanLiteral, StringLiteral, NumericLiteral, CharacterLiteral, PropertyAccessExpression, Expression, ElementAccessExpression, BinaryExpression, UnresolvedCallExpression, ConditionalExpression, InstanceOfExpression, ParenthesizedExpression, RegexLiteral, UnaryExpression, UnaryType, MapLiteral, NullLiteral, AwaitExpression, UnresolvedNewExpression, UnresolvedMethodCallExpression, InstanceMethodCallExpression, NullCoalesceExpression, GlobalFunctionCallExpression, StaticMethodCallExpression, LambdaCallExpression, IMethodCallExpression } from "../One/Ast/Expressions"; import { Statement, ReturnStatement, UnsetStatement, ThrowStatement, ExpressionStatement, VariableDeclaration, BreakStatement, ForeachStatement, IfStatement, WhileStatement, ForStatement, DoStatement, ContinueStatement, TryStatement, Block } from "../One/Ast/Statements"; import { Class, SourceFile, IVariable, Lambda, Interface, IInterface, MethodParameter, IVariableWithInitializer, Visibility, Package, IHasAttributesAndTrivia, Method, ExportScopeRef } from "../One/Ast/Types"; import { VoidType, ClassType, InterfaceType, EnumType, AnyType, LambdaType, NullType, GenericsType, TypeHelper, IInterfaceType } from "../One/Ast/AstTypes"; import { ThisReference, EnumReference, ClassReference, MethodParameterReference, VariableDeclarationReference, ForVariableReference, ForeachVariableReference, SuperReference, StaticFieldReference, StaticPropertyReference, InstanceFieldReference, InstancePropertyReference, EnumMemberReference, CatchVariableReference, GlobalFunctionReference, StaticThisReference, VariableReference } from "../One/Ast/References"; import { GeneratedFile } from "./GeneratedFile"; import { NameUtils } from "./NameUtils"; import { IGenerator } from "./IGenerator"; import { IExpression, IType } from "../One/Ast/Interfaces"; import { IGeneratorPlugin } from "./IGeneratorPlugin"; import { ITransformer } from "../One/ITransformer"; import { ConvertNullCoalesce } from "../One/Transforms/ConvertNullCoalesce"; import { UseDefaultCallArgsExplicitly } from "../One/Transforms/UseDefaultCallArgsExplicitly"; import { ExpressionValue, LambdaValue, TemplateFileGeneratorPlugin, TypeValue } from "./TemplateFileGeneratorPlugin"; import { BooleanValue, IVMValue, StringValue } from "../VM/Values"; export class JavaGenerator implements IGenerator { imports = new Set<string>(); currentClass: IInterface; reservedWords: string[] = ["class", "interface", "throws", "package", "throw", "boolean"]; fieldToMethodHack: string[] = []; plugins: IGeneratorPlugin[] = []; constructor() { } getLangName(): string { return "Java"; } getExtension(): string { return "java"; } getTransforms(): ITransformer[] { return [<ITransformer>new ConvertNullCoalesce(), <ITransformer>new UseDefaultCallArgsExplicitly()]; } addInclude(include: string): void { this.imports.add(include); } isArray(arrayExpr: Expression) { // TODO: InstanceMethodCallExpression is a hack, we should introduce real stream handling return arrayExpr instanceof VariableReference && !arrayExpr.getVariable().mutability.mutated || arrayExpr instanceof StaticMethodCallExpression || arrayExpr instanceof InstanceMethodCallExpression; } arrayStream(arrayExpr: Expression) { const isArray = this.isArray(arrayExpr); const objR = this.expr(arrayExpr); if (isArray) this.imports.add("java.util.Arrays"); return isArray ? `Arrays.stream(${objR})` : `${objR}.stream()`; } toArray(arrayType: IType, typeArgIdx: number = 0) { const type = (<ClassType>arrayType).typeArguments[typeArgIdx]; return `toArray(${this.type(type)}[]::new)`; } escape(value: IVMValue): string { if (value instanceof ExpressionValue && value.value instanceof RegexLiteral) return JSON.stringify(value.value.pattern); else if (value instanceof StringValue) return JSON.stringify(value.value); throw new Error(`Not supported VMValue for escape()`); } escapeRepl(value: IVMValue): string { if (value instanceof ExpressionValue && value.value instanceof StringLiteral) return JSON.stringify(value.value.stringValue.replace(/\\/g, "\\\\").replace(/\$/g, "\\$")); throw new Error(`Not supported VMValue for escapeRepl()`); } addPlugin(plugin: IGeneratorPlugin) { this.plugins.push(plugin); // TODO: hack? if (plugin instanceof TemplateFileGeneratorPlugin) { plugin.modelGlobals["toStream"] = new LambdaValue(args => new StringValue(this.arrayStream((<ExpressionValue>args[0]).value))); plugin.modelGlobals["isArray"] = new LambdaValue(args => new BooleanValue(this.isArray((<ExpressionValue>args[0]).value))); plugin.modelGlobals["toArray"] = new LambdaValue(args => new StringValue(this.toArray((<TypeValue>args[0]).type))); plugin.modelGlobals["escape"] = new LambdaValue(args => new StringValue(this.escape(args[0]))); plugin.modelGlobals["escapeRepl"] = new LambdaValue(args => new StringValue(this.escapeRepl(args[0]))); } } name_(name: string) { if (this.reservedWords.includes(name)) name += "_"; if (this.fieldToMethodHack.includes(name)) name += "()"; const nameParts = name.split(/-/g); for (let i = 1; i < nameParts.length; i++) nameParts[i] = nameParts[i][0].toUpperCase() + nameParts[i].substr(1); name = nameParts.join(''); if (name === "_") name = "unused"; return name; } leading(item: Statement) { let result = ""; if (item.leadingTrivia !== null && item.leadingTrivia.length > 0) result += item.leadingTrivia; //if (item.attributes !== null) // result += Object.keys(item.attributes).map(x => `// @${x} ${item.attributes[x]}\n`).join(""); return result; } preArr(prefix: string, value: string[]) { return value.length > 0 ? `${prefix}${value.join(", ")}` : ""; } preIf(prefix: string, condition: boolean) { return condition ? prefix : ""; } pre(prefix: string, value: string) { return value !== null ? `${prefix}${value}` : ""; } typeArgs(args: string[]): string { return args !== null && args.length > 0 ? `<${args.join(", ")}>` : ""; } typeArgs2(args: IType[]): string { return this.typeArgs(args.map(x => this.type(x))); } unpackPromise(t: IType): IType { return t instanceof ClassType && t.decl === this.currentClass.parentFile.literalTypes.promise.decl ? t.typeArguments[0] : t; } type(t: IType, mutates = true, isNew = false): string { t = this.unpackPromise(t); if (t instanceof ClassType || t instanceof InterfaceType) { const decl = (<IInterfaceType>t).getDecl(); if (decl.parentFile.exportScope !== null) this.imports.add(this.toImport(decl.parentFile.exportScope) + "." + decl.name); } if (t instanceof ClassType) { const typeArgs = this.typeArgs(t.typeArguments.map(x => this.type(x))); if (t.decl.name === "TsString") return "String"; else if (t.decl.name === "TsBoolean") return "Boolean"; else if (t.decl.name === "TsNumber") return "Integer"; else if (t.decl.name === "TsArray") { const realType = isNew ? "ArrayList" : "List"; if (mutates) { this.imports.add(`java.util.${realType}`); return `${realType}<${this.type(t.typeArguments[0])}>`; } else return `${this.type(t.typeArguments[0])}[]`; } else if (t.decl.name === "Map") { const realType = isNew ? "LinkedHashMap" : "Map"; this.imports.add(`java.util.${realType}`); return `${realType}<${this.type(t.typeArguments[0])}, ${this.type(t.typeArguments[1])}>`; } else if (t.decl.name === "Set") { const realType = isNew ? "LinkedHashSet" : "Set"; this.imports.add(`java.util.${realType}`); return `${realType}<${this.type(t.typeArguments[0])}>`; } else if (t.decl.name === "Object") { //this.imports.add("System"); return `Object`; } else if (t.decl.name === "TsMap") { const realType = isNew ? "LinkedHashMap" : "Map"; this.imports.add(`java.util.${realType}`); return `${realType}<String, ${this.type(t.typeArguments[0])}>`; } return this.name_(t.decl.name) + typeArgs; } else if (t instanceof InterfaceType) return `${this.name_(t.decl.name)}${this.typeArgs(t.typeArguments.map(x => this.type(x)))}`; else if (t instanceof VoidType) return "void"; else if (t instanceof EnumType) return `${this.name_(t.decl.name)}`; else if (t instanceof AnyType) return `Object`; else if (t instanceof NullType) return `null`; else if (t instanceof GenericsType) return `${t.typeVarName}`; else if (t instanceof LambdaType) { const retType = this.unpackPromise(t.returnType); const isFunc = !(retType instanceof VoidType); const paramTypes = t.parameters.map(x => this.type(x.type, false)); if (isFunc) paramTypes.push(this.type(retType, false)); this.imports.add("java.util.function." + (isFunc ? "Function" : "Consumer")); return `${isFunc ? "Function" : "Consumer"}<${paramTypes.join(", ")}>`; } else if (t === null) { return "/* TODO */ object"; } else { debugger; return "/* MISSING */"; } } isTsArray(type: IType) { return type instanceof ClassType && type.decl.name == "TsArray"; } vis(v: Visibility) { return v === Visibility.Private ? "private" : v === Visibility.Protected ? "protected" : v === Visibility.Public ? "public" : "/* TODO: not set */public"; } varType(v: IVariable, attr: IHasAttributesAndTrivia) { let type: string; if (attr !== null && attr.attributes !== null && "java-type" in attr.attributes) type = attr.attributes["java-type"]; else if (v.type instanceof ClassType && v.type.decl.name === "TsArray") { if (v.mutability.mutated) { this.imports.add("java.util.List"); type = `List<${this.type(v.type.typeArguments[0])}>`; } else { type = `${this.type(v.type.typeArguments[0])}[]`; } } else { type = this.type(v.type); } return type; } varWoInit(v: IVariable, attr: IHasAttributesAndTrivia) { return `${this.varType(v, attr)} ${this.name_(v.name)}`; } var(v: IVariableWithInitializer, attrs: IHasAttributesAndTrivia) { return this.varWoInit(v, attrs) + (v.initializer !== null ? ` = ${this.expr(v.initializer)}` : ""); } exprCall(typeArgs: IType[], args: Expression[]) { return this.typeArgs2(typeArgs) + `(${args.map(x => this.expr(x)).join(", ")})`; } mutateArg(arg: Expression, shouldBeMutable: boolean) { if (this.isTsArray(arg.actualType)) { const itemType = (<ClassType>arg.actualType).typeArguments[0]; if (arg instanceof ArrayLiteral && !shouldBeMutable) { return arg.items.length === 0 && !this.isTsArray(itemType) ? `new ${this.type(itemType)}[0]` : `new ${this.type(itemType)}[] { ${arg.items.map(x => this.expr(x)).join(', ')} }`; } let currentlyMutable = shouldBeMutable; if (arg instanceof VariableReference) currentlyMutable = arg.getVariable().mutability.mutated; else if (arg instanceof InstanceMethodCallExpression || arg instanceof StaticMethodCallExpression) currentlyMutable = false; if (currentlyMutable && !shouldBeMutable) return `${this.expr(arg)}.toArray(${this.type(itemType)}[]::new)`; else if (!currentlyMutable && shouldBeMutable) { this.imports.add("java.util.Arrays"); this.imports.add("java.util.ArrayList"); return `new ArrayList<>(Arrays.asList(${this.expr(arg)}))`; } } return this.expr(arg); } mutatedExpr(expr: Expression, toWhere: Expression) { if (toWhere instanceof VariableReference) { const v = toWhere.getVariable(); if (this.isTsArray(v.type)) return this.mutateArg(expr, v.mutability.mutated); } return this.expr(expr); } callParams(args: Expression[], params: MethodParameter[]) { const argReprs: string[] = []; for (let i = 0; i < args.length; i++) argReprs.push(this.isTsArray(params[i].type) ? this.mutateArg(args[i], params[i].mutability.mutated) : this.expr(args[i])); return `(${argReprs.join(", ")})`; } methodCall(expr: IMethodCallExpression) { return this.name_(expr.method.name) + this.typeArgs2(expr.typeArgs) + this.callParams(expr.args, expr.method.parameters); } inferExprNameForType(type: IType): string { if (type instanceof ClassType && type.typeArguments.every((x,_) => x instanceof ClassType)) { const fullName = type.typeArguments.map(x => (<ClassType>x).decl.name).join('') + type.decl.name; return NameUtils.shortName(fullName); } return null; } isSetExpr(varRef: VariableReference): boolean { return varRef.parentNode instanceof BinaryExpression && varRef.parentNode.left === varRef && ["=", "+=", "-="].includes(varRef.parentNode.operator); } expr(expr: IExpression): string { for (const plugin of this.plugins) { const result = plugin.expr(expr); if (result !== null) return result; } let res = "UNKNOWN-EXPR"; if (expr instanceof NewExpression) { res = `new ${this.type(expr.cls, true, true)}${this.callParams(expr.args, expr.cls.decl.constructor_ !== null ? expr.cls.decl.constructor_.parameters : [])}`; } else if (expr instanceof UnresolvedNewExpression) { res = `/* TODO: UnresolvedNewExpression */ new ${this.type(expr.cls)}(${expr.args.map(x => this.expr(x)).join(", ")})`; } else if (expr instanceof Identifier) { res = `/* TODO: Identifier */ ${expr.text}`; } else if (expr instanceof PropertyAccessExpression) { res = `/* TODO: PropertyAccessExpression */ ${this.expr(expr.object)}.${expr.propertyName}`; } else if (expr instanceof UnresolvedCallExpression) { res = `/* TODO: UnresolvedCallExpression */ ${this.expr(expr.func)}${this.exprCall(expr.typeArgs, expr.args)}`; } else if (expr instanceof UnresolvedMethodCallExpression) { res = `/* TODO: UnresolvedMethodCallExpression */ ${this.expr(expr.object)}.${expr.methodName}${this.exprCall(expr.typeArgs, expr.args)}`; } else if (expr instanceof InstanceMethodCallExpression) { res = `${this.expr(expr.object)}.${this.methodCall(expr)}`; } else if (expr instanceof StaticMethodCallExpression) { res = `${this.name_(expr.method.parentInterface.name)}.${this.methodCall(expr)}`; } else if (expr instanceof GlobalFunctionCallExpression) { res = `Global.${this.name_(expr.func.name)}${this.exprCall([], expr.args)}`; } else if (expr instanceof LambdaCallExpression) { const resType = this.unpackPromise(expr.actualType); res = `${this.expr(expr.method)}.${resType instanceof VoidType ? "accept" : "apply"}(${expr.args.map(x => this.expr(x)).join(", ")})`; } else if (expr instanceof BooleanLiteral) { res = `${expr.boolValue ? "true" : "false"}`; } else if (expr instanceof StringLiteral) { res = `${JSON.stringify(expr.stringValue)}`; } else if (expr instanceof NumericLiteral) { res = `${expr.valueAsText}`; } else if (expr instanceof CharacterLiteral) { res = `'${expr.charValue}'`; } else if (expr instanceof ElementAccessExpression) { res = `${this.expr(expr.object)}.get(${this.expr(expr.elementExpr)})`; } else if (expr instanceof TemplateString) { const parts: string[] = []; for (const part of expr.parts) { if (part.isLiteral) { let lit = ""; for (let i = 0; i < part.literalText.length; i++) { const chr = part.literalText[i]; if (chr === '\n') lit += "\\n"; else if (chr === '\r') lit += "\\r"; else if (chr === '\t') lit += "\\t"; else if (chr === '\\') lit += "\\\\"; else if (chr === '"') lit += '\\"'; else { const chrCode = chr.charCodeAt(0); if (32 <= chrCode && chrCode <= 126) lit += chr; else throw new Error(`invalid char in template string (code=${chrCode})`); } } parts.push(`"${lit}"`); } else { const repr = this.expr(part.expression); const isComplex = part.expression instanceof ConditionalExpression || part.expression instanceof BinaryExpression; parts.push(isComplex ? `(${repr})` : repr); } } res = parts.join(' + '); } else if (expr instanceof BinaryExpression) { const modifies = ["=", "+=", "-="].includes(expr.operator); if (modifies && expr.left instanceof InstanceFieldReference && this.useGetterSetter(expr.left)) { res = `${this.expr(expr.left.object)}.set${this.ucFirst(expr.left.field.name)}(${this.mutatedExpr(expr.right, expr.operator === "=" ? expr.left : null)})`; } else if (["==", "!="].includes(expr.operator)) { const lit = this.currentClass.parentFile.literalTypes; const leftType = expr.left.getType(); const rightType = expr.right.getType(); const useEquals = TypeHelper.equals(leftType, lit.string) && rightType !== null && TypeHelper.equals(rightType, lit.string); if (useEquals) { this.imports.add("io.onelang.std.core.Objects"); res = `${expr.operator === "!=" ? "!" : ""}Objects.equals(${this.expr(expr.left)}, ${this.expr(expr.right)})`; } else res = `${this.expr(expr.left)} ${expr.operator} ${this.expr(expr.right)}`; } else { res = `${this.expr(expr.left)} ${expr.operator} ${this.mutatedExpr(expr.right, expr.operator === "=" ? expr.left : null)}`; } } else if (expr instanceof ArrayLiteral) { if (expr.items.length === 0) { res = `new ${this.type(expr.actualType, true, true)}()`; } else { this.imports.add(`java.util.List`); this.imports.add(`java.util.ArrayList`); res = `new ArrayList<>(List.of(${expr.items.map(x => this.expr(x)).join(', ')}))`; } } else if (expr instanceof CastExpression) { res = `((${this.type(expr.newType)})${this.expr(expr.expression)})`; } else if (expr instanceof ConditionalExpression) { res = `${this.expr(expr.condition)} ? ${this.expr(expr.whenTrue)} : ${this.mutatedExpr(expr.whenFalse, expr.whenTrue)}`; } else if (expr instanceof InstanceOfExpression) { res = `${this.expr(expr.expr)} instanceof ${this.type(expr.checkType)}`; } else if (expr instanceof ParenthesizedExpression) { res = `(${this.expr(expr.expression)})`; } else if (expr instanceof RegexLiteral) { this.imports.add(`io.onelang.std.core.RegExp`); res = `new RegExp(${JSON.stringify(expr.pattern)})`; } else if (expr instanceof Lambda) { let body: string; if (expr.body.statements.length === 1 && expr.body.statements[0] instanceof ReturnStatement) body = " " + this.expr((<ReturnStatement>expr.body.statements[0]).expression); else body = this.block(expr.body, false); const params = expr.parameters.map(x => this.name_(x.name)); res = `${params.length === 1 ? params[0] : `(${params.join(", ")})`} ->${body}`; } else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Prefix) { res = `${expr.operator}${this.expr(expr.operand)}`; } else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Postfix) { res = `${this.expr(expr.operand)}${expr.operator}`; } else if (expr instanceof MapLiteral) { if (expr.items.length > 10) throw new Error("MapLiteral is only supported with maximum of 10 items"); if (expr.items.length === 0) { res = `new ${this.type(expr.actualType, true, true)}()`; } else { this.imports.add(`java.util.Map`); this.imports.add(`java.util.LinkedHashMap`); const repr = expr.items.map(item => `${JSON.stringify(item.key)}, ${this.expr(item.value)}`).join(", "); res = `new LinkedHashMap<>(Map.of(${repr}))`; } } else if (expr instanceof NullLiteral) { res = `null`; } else if (expr instanceof AwaitExpression) { res = `${this.expr(expr.expr)}`; } else if (expr instanceof ThisReference) { res = `this`; } else if (expr instanceof StaticThisReference) { res = `${this.currentClass.name}`; } else if (expr instanceof EnumReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof ClassReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof MethodParameterReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof VariableDeclarationReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof ForVariableReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof ForeachVariableReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof CatchVariableReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof GlobalFunctionReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof SuperReference) { res = `super`; } else if (expr instanceof StaticFieldReference) { res = `${this.name_(expr.decl.parentInterface.name)}.${this.name_(expr.decl.name)}`; } else if (expr instanceof StaticPropertyReference) { res = `${this.name_(expr.decl.parentClass.name)}.${this.name_(expr.decl.name)}`; } else if (expr instanceof InstanceFieldReference) { // TODO: unified handling of field -> property conversion? if (this.useGetterSetter(expr)) res = `${this.expr(expr.object)}.get${this.ucFirst(expr.field.name)}()`; else res = `${this.expr(expr.object)}.${this.name_(expr.field.name)}`; } else if (expr instanceof InstancePropertyReference) { res = `${this.expr(expr.object)}.${this.isSetExpr(expr) ? "set" : "get"}${this.ucFirst(expr.property.name)}()`; } else if (expr instanceof EnumMemberReference) { res = `${this.name_(expr.decl.parentEnum.name)}.${this.name_(expr.decl.name)}`; } else if (expr instanceof NullCoalesceExpression) { res = `(${this.expr(expr.defaultExpr)} != null ? (${this.expr(expr.defaultExpr)}) : (${this.mutatedExpr(expr.exprIfNull, expr.defaultExpr)}))`; } else debugger; return res; } useGetterSetter(fieldRef: InstanceFieldReference): boolean { return fieldRef.object.actualType instanceof InterfaceType || (fieldRef.field.interfaceDeclarations !== null && fieldRef.field.interfaceDeclarations.length > 0); } block(block: Block, allowOneLiner = true): string { const stmtLen = block.statements.length; return stmtLen === 0 ? " { }" : allowOneLiner && stmtLen === 1 && !(block.statements[0] instanceof IfStatement) && !(block.statements[0] instanceof VariableDeclaration) ? `\n${this.pad(this.rawBlock(block))}` : ` {\n${this.pad(this.rawBlock(block))}\n}`; } stmtDefault(stmt: Statement): string { let res = "UNKNOWN-STATEMENT"; if (stmt instanceof BreakStatement) { res = "break;"; } else if (stmt instanceof ReturnStatement) { res = stmt.expression === null ? "return;" : `return ${this.mutateArg(stmt.expression, false)};`; } else if (stmt instanceof UnsetStatement) { res = `/* unset ${this.expr(stmt.expression)}; */`; } else if (stmt instanceof ThrowStatement) { res = `throw ${this.expr(stmt.expression)};`; } else if (stmt instanceof ExpressionStatement) { res = `${this.expr(stmt.expression)};`; } else if (stmt instanceof VariableDeclaration) { if (stmt.initializer instanceof NullLiteral) res = `${this.type(stmt.type, stmt.mutability.mutated)} ${this.name_(stmt.name)} = null;`; else if (stmt.initializer !== null) res = `var ${this.name_(stmt.name)} = ${this.mutateArg(stmt.initializer, stmt.mutability.mutated)};`; else res = `${this.type(stmt.type)} ${this.name_(stmt.name)};`; } else if (stmt instanceof ForeachStatement) { res = `for (var ${this.name_(stmt.itemVar.name)} : ${this.expr(stmt.items)})` + this.block(stmt.body); } else if (stmt instanceof IfStatement) { const elseIf = stmt.else_ !== null && stmt.else_.statements.length === 1 && stmt.else_.statements[0] instanceof IfStatement; res = `if (${this.expr(stmt.condition)})${this.block(stmt.then)}`; res += (elseIf ? `\nelse ${this.stmt(stmt.else_.statements[0])}` : "") + (!elseIf && stmt.else_ !== null ? `\nelse` + this.block(stmt.else_) : ""); } else if (stmt instanceof WhileStatement) { res = `while (${this.expr(stmt.condition)})` + this.block(stmt.body); } else if (stmt instanceof ForStatement) { res = `for (${stmt.itemVar !== null ? this.var(stmt.itemVar, null) : ""}; ${this.expr(stmt.condition)}; ${this.expr(stmt.incrementor)})` + this.block(stmt.body); } else if (stmt instanceof DoStatement) { res = `do${this.block(stmt.body)} while (${this.expr(stmt.condition)});`; } else if (stmt instanceof TryStatement) { res = "try" + this.block(stmt.tryBody, false); if (stmt.catchBody !== null) { //this.imports.add("System"); res += ` catch (Exception ${this.name_(stmt.catchVar.name)}) ${this.block(stmt.catchBody, false)}`; } if (stmt.finallyBody !== null) res += "finally" + this.block(stmt.finallyBody); } else if (stmt instanceof ContinueStatement) { res = `continue;`; } else debugger; return res; } stmt(stmt: Statement): string { let res: string = null; if (stmt.attributes !== null && "java-import" in stmt.attributes) for (const imp of stmt.attributes["java-import"].split(/\n/g)) this.imports.add(imp); if (stmt.attributes !== null && "java" in stmt.attributes) { res = stmt.attributes["java"]; } else { for (const plugin of this.plugins) { res = plugin.stmt(stmt); if (res !== null) break; } if (res === null) res = this.stmtDefault(stmt); } return this.leading(stmt) + res; } stmts(stmts: Statement[]): string { return stmts.map(stmt => this.stmt(stmt)).join("\n"); } rawBlock(block: Block): string { return this.stmts(block.statements); } methodGen(prefix: string, params: MethodParameter[], body: string): string { return `${prefix}(${params.map(p => this.varWoInit(p, p)).join(", ")})${body}`; } method(method: Method, isCls: boolean): string { // TODO: final const prefix = (isCls ? this.vis(method.visibility) + " " : "") + this.preIf("static ", method.isStatic) + //this.preIf("virtual ", method.overrides === null && method.overriddenBy.length === 0) + //this.preIf("override ", method.overrides !== null) + //this.preIf("async ", method.async) + this.preIf("/* throws */ ", method.throws) + (method.typeArguments.length > 0 ? `<${method.typeArguments.join(', ')}> ` : "") + `${this.type(method.returns, false)} ` + this.name_(method.name); return this.methodGen(prefix, method.parameters, method.body === null ? ";" : ` {\n${this.pad(this.stmts(method.body.statements))}\n}`); } class(cls: Class) { this.currentClass = cls; const resList: string[] = []; const staticConstructorStmts: Statement[] = []; const complexFieldInits: Statement[] = []; const fieldReprs: string[] = []; const propReprs: string[] = []; for (const field of cls.fields) { const isInitializerComplex = field.initializer !== null && !(field.initializer instanceof StringLiteral) && !(field.initializer instanceof BooleanLiteral) && !(field.initializer instanceof NumericLiteral); const prefix = `${this.vis(field.visibility)} ${this.preIf("static ", field.isStatic)}`; if (field.interfaceDeclarations.length > 0) { const varType = this.varType(field, field); const name = this.name_(field.name); const pname = this.ucFirst(field.name); const setToFalse = TypeHelper.equals(field.type, this.currentClass.parentFile.literalTypes.boolean); propReprs.push( `${varType} ${name}${setToFalse ? " = false" : field.initializer !== null ? ` = ${this.expr(field.initializer)}` : ""};\n` + `${prefix}${varType} get${pname}() { return this.${name}; }\n` + `${prefix}void set${pname}(${varType} value) { this.${name} = value; }`); } else if (isInitializerComplex) { if (field.isStatic) staticConstructorStmts.push(new ExpressionStatement(new BinaryExpression(new StaticFieldReference(field), "=", field.initializer))); else complexFieldInits.push(new ExpressionStatement(new BinaryExpression(new InstanceFieldReference(new ThisReference(cls), field), "=", field.initializer))); fieldReprs.push(`${prefix}${this.varWoInit(field, field)};`); } else fieldReprs.push(`${prefix}${this.var(field, field)};`); } resList.push(fieldReprs.join("\n")); resList.push(propReprs.join("\n\n")); for (const prop of cls.properties) { const prefix = `${this.vis(prop.visibility)} ${this.preIf("static ", prop.isStatic)}`; if (prop.getter !== null) resList.push(`${prefix}${this.type(prop.type)} get${this.ucFirst(prop.name)}()${this.block(prop.getter, false)}`); if (prop.setter !== null) resList.push(`${prefix}void set${this.ucFirst(prop.name)}(${this.type(prop.type)} value)${this.block(prop.setter, false)}`); } if (staticConstructorStmts.length > 0) resList.push(`static {\n${this.pad(this.stmts(staticConstructorStmts))}\n}`); if (cls.constructor_ !== null) { const constrFieldInits: Statement[] = []; for (const field of cls.fields.filter(x => x.constructorParam !== null)) { const fieldRef = new InstanceFieldReference(new ThisReference(cls), field); const mpRef = new MethodParameterReference(field.constructorParam); // TODO: decide what to do with "after-TypeEngine" transformations mpRef.setActualType(field.type, false, false); constrFieldInits.push(new ExpressionStatement(new BinaryExpression(fieldRef, "=", mpRef))); } const superCall = cls.constructor_.superCallArgs !== null ? `super(${cls.constructor_.superCallArgs.map(x => this.expr(x)).join(", ")});\n` : ""; // @java var stmts = Stream.of(constrFieldInits, complexFieldInits, cls.constructor_.getBody().statements).flatMap(Collection::stream).toArray(Statement[]::new); // @java-import java.util.Collection // @java-import java.util.stream.Stream const stmts = constrFieldInits.concat(complexFieldInits).concat(cls.constructor_.body.statements); // TODO: super calls resList.push(this.methodGen( "public " + this.preIf("/* throws */ ", cls.constructor_.throws) + this.name_(cls.name), cls.constructor_.parameters, `\n{\n${this.pad(superCall + this.stmts(stmts))}\n}`)); } else if (complexFieldInits.length > 0) resList.push(`public ${this.name_(cls.name)}()\n{\n${this.pad(this.stmts(complexFieldInits))}\n}`); const methods: string[] = []; for (const method of cls.methods) { if (method.body === null) continue; // declaration only methods.push(this.method(method, true)); } resList.push(methods.join("\n\n")); return this.pad(resList.filter(x => x !== "").join("\n\n")); } ucFirst(str: string): string { return str[0].toUpperCase() + str.substr(1); } interface(intf: Interface) { this.currentClass = intf; const resList: string[] = []; for (const field of intf.fields) { const varType = this.varType(field, field); const name = this.ucFirst(field.name); resList.push(`${varType} get${name}();\nvoid set${name}(${varType} value);`); } resList.push(intf.methods.map(method => this.method(method, false)).join("\n")); return this.pad(resList.filter(x => x !== "").join("\n\n")); } pad(str: string): string { return str.split(/\n/g).map(x => ` ${x}`).join('\n'); } pathToNs(path: string): string { // Generator/ExprLang/ExprLangAst.ts -> Generator.ExprLang const parts = path.split(/\//g); parts.pop(); return parts.join('.'); } importsHead(): string { const imports: string[] = []; for (const imp of this.imports.values()) imports.push(imp); this.imports = new Set<string>(); return imports.length === 0 ? "" : imports.map(x => `import ${x};`).join("\n") + "\n\n"; } toImport(scope: ExportScopeRef): string { // TODO: hack if (scope.scopeName === "index") { const name = scope.packageName.split(/-/g)[0].replace(/One\./g, "").toLowerCase(); return `io.onelang.std.${name}`; } return `${scope.packageName}.${scope.scopeName.replace(/\//g, ".")}`; } generate(pkg: Package): GeneratedFile[] { const result: GeneratedFile[] = []; for (const path of Object.keys(pkg.files)) { const file = pkg.files[path]; const packagePath = `${pkg.name}/${file.sourcePath.path}`; const dstDir = `src/main/java/${packagePath}`; const packageName = packagePath.replace(/\//g, "."); const imports = new Set<string>(); for (const impList of file.imports) { const impPkg = this.toImport(impList.exportScope); for (const imp of impList.imports) imports.add(`${impPkg}.${imp.name}`); } const headImports = Array.from(imports.values()).map(x => `import ${x};`).join("\n"); const head = `package ${packageName};\n\n${headImports}\n\n`; for (const enum_ of file.enums) { result.push(new GeneratedFile(`${dstDir}/${enum_.name}.java`, `${head}public enum ${this.name_(enum_.name)} { ${enum_.values.map(x => this.name_(x.name)).join(", ")} }`)); } for (const intf of file.interfaces) { const res = `public interface ${this.name_(intf.name)}${this.typeArgs(intf.typeArguments)}`+ `${this.preArr(" extends ", intf.baseInterfaces.map(x => this.type(x)))} {\n${this.interface(intf)}\n}`; result.push(new GeneratedFile(`${dstDir}/${intf.name}.java`, `${head}${this.importsHead()}${res}`)); } for (const cls of file.classes) { const res = `public class ${this.name_(cls.name)}${this.typeArgs(cls.typeArguments)}` + (cls.baseClass !== null ? ` extends ${this.type(cls.baseClass)}` : "") + this.preArr(" implements ", cls.baseInterfaces.map(x => this.type(x))) + ` {\n${this.class(cls)}\n}`; result.push(new GeneratedFile(`${dstDir}/${cls.name}.java`, `${head}${this.importsHead()}${res}`)); } } return result; } }
the_stack
import type { CustomSyntaxChecker } from '../../types'; import { log } from '../../debug'; import { matched, unmatched } from '../../match-result'; import { TokenCollection } from '../../token'; import { datetimeTokenCheck } from './datetime-tokens'; /** * @see https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#durations */ export const checkDurationISO8601LikeString: CustomSyntaxChecker = () => function checkDurationISO8601LikeString(value) { log('CHECK: duration-string (ISO8601 like)'); // PnDTnHnMnS const tokens = TokenCollection.fromPatterns(value, [ // Start sign P /[^0-9T]?/, // date part /[^T]*/, // Time sign T /[^0-9]?/, // Time part /.*/, ]); log('Duration ISO8601: "%s" => %O', tokens.value, tokens); const res = tokens.eachCheck( p => { if (!p || !p.value) { return unmatched('', 'missing-token', { expects: [{ type: 'const', value: 'P' }], partName: 'duration', }); } if (!p.match('P', false)) { return p.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'P' }], partName: 'duration', }); } }, d => { if (!d || !d.value) { return; } const [num, sign, extra] = TokenCollection.fromPatterns(d, [/[0-9]+/, /./]); log('Date part: "%s" => %O', d.value, { num, sign }); if (!num.match(/^[0-9]+$/)) { return num.unmatched({ reason: 'unexpected-token', expects: [], partName: 'date', }); } if (!sign || !sign.value) { return unmatched('', 'missing-token', { expects: [{ type: 'const', value: 'D' }], partName: 'date', }); } if (!sign.match('D', false)) { return sign.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'D' }], partName: 'date', }); } if (extra && extra.value) { return extra.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'T' }], }); } }, t => { if (!t || !t.value) { return unmatched('', 'missing-token', { expects: [{ type: 'const', value: 'T' }], }); } if (!t.match('T', false)) { return t.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'T' }], }); } }, time => { if (!time) { return unmatched('', 'missing-token', { expects: [ { type: 'common', value: 'hour' }, { type: 'common', value: 'minute' }, { type: 'common', value: 'second' }, ], partName: 'time', }); } const timeTokens = TokenCollection.fromPatterns(time, [ // Hour part /[0-9]+(\.[0-9]*)?[^0-9]?/, // Minute part /[0-9]+(\.[0-9]*)?[^0-9]?/, // Second part /[0-9]+(\.[0-9]*)?[^0-9]?/, ]); log('Time part: "%s" => %O', timeTokens.value, timeTokens); const [h, m, s] = timeTokens; if ((h?.value || '') + (m?.value || '') + (s?.value || '') === '') { return unmatched('', 'missing-token', { expects: [ { type: 'common', value: 'hour' }, { type: 'common', value: 'minute' }, { type: 'common', value: 'second' }, ], }); } const specified = new Set<'H' | 'M' | 'S'>(); for (const t of timeTokens) { if (!t || !t.value) { continue; } if (specified.has('S')) { return t.unmatched({ reason: 'extra-token', }); } const [num, dpfp, sign] = TokenCollection.fromPatterns(t, [/[0-9]+/, /(\.[0-9]*)?/, /[^0-9]+/]); log('Time part (h|m|s): "%s" => %O', t.value, { num, dpfp, sign }); if (!num.match(/^[0-9]+$/)) { return num.unmatched({ reason: 'unexpected-token', expects: [{ type: 'common', value: 'number' }], partName: 'time', }); } if (dpfp && dpfp.value) { const [dp, fp] = TokenCollection.fromPatterns(dpfp, [/\./, /[0-9]+/]); log('Second fractional part (h|m|s): "%s" => %O', dpfp.value, { dp, fp }); if (!dp.match('.')) { return dp.unmatched({ reason: 'unexpected-token', expects: [], partName: 'decimal point', }); } if (!fp || !fp.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'fractional part' }], partName: 'second', }); } if (!fp.match(/^[0-9]+$/)) { return fp.unmatched({ reason: 'unexpected-token', expects: [], partName: 'fractional part', }); } if (!(1 <= fp.length && fp.length <= 3)) { return fp.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 1, lte: 3 }, expects: [], partName: 'fractional part', }); } } const expects = [ { type: 'const', value: 'H' }, { type: 'const', value: 'M' }, { type: 'const', value: 'S' }, ] as const; if (!sign || !sign.value) { return unmatched('', 'missing-token', { expects: expects.filter(e => !specified.has(e.value)), partName: 'time', }); } if (specified.has('M') && sign.match('H', false)) { return sign.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'S' }], partName: 'time', }); } if ( !sign.match(['H', 'M', 'S'], false) || (sign.match('H', false) && specified.has('H')) || (sign.match('M', false) && specified.has('M')) ) { return sign.unmatched({ reason: 'unexpected-token', expects: expects.filter(e => !specified.has(e.value)), partName: 'time', }); } specified.add(sign.value as 'H' | 'M' | 'S'); } }, datetimeTokenCheck.extra, ); if (!res.matched) { log('Failed: %O', res); } return res; }; export const checkDurationComponentListString: CustomSyntaxChecker = () => function checkDurationComponentListString(value) { log('CHECK: duration-string (duration component list)'); if (!value) { return unmatched('', 'empty-token', { expects: [{ type: 'common', value: 'time' }], }); } const patterns = [ // 1. Zero or more ASCII whitespace. /\s*/, // 2. One or more ASCII digits, representing a number of time units, // scaled by the duration time component scale specified (see below) // to represent a number of seconds. /[0-9]+/, // 3. If the duration time component scale specified is 1 (i.e. the units are seconds), // then, optionally, a U+002E FULL STOP character (.) followed by // one, two, or three ASCII digits, representing a fraction of a second. /(\.[0-9]*)?/, // 4. Zero or more ASCII whitespace. /\s*/, // 5. One of the following characters, representing the duration time component scale // of the time unit used in the numeric part of the duration time component: /[^0-9]/, // 6. Zero or more ASCII whitespace. /\s*/, ]; const tokens = TokenCollection.fromPatterns(value, patterns, { repeat: true }); const components = tokens.chunk(patterns.length); const specified = new Set<'w' | 'd' | 'h' | 'm' | 's'>(); for (const component of components) { log('Duration Component: "%s" => %O', component.value, component); const [, , dpfp, , unit] = component; const res = component.eachCheck( ws => {}, num => { if (!num || !num.value) { const reason = dpfp?.value || unit?.value ? 'unexpected-token' : 'missing-token'; return unmatched('', reason, { expects: [{ type: 'common', value: 'time' }], }); } }, dpfp => { if (!dpfp || !dpfp.value) { return; } const unitExpects = ( [ { type: 'const', value: 'w' }, { type: 'const', value: 'd' }, { type: 'const', value: 'h' }, { type: 'const', value: 'm' }, { type: 'const', value: 's' }, ] as const ).filter(e => !specified.has(e.value)); if (specified.has('s')) { return dpfp.unmatched({ reason: 'unexpected-token', expects: unitExpects, partName: 'unit', }); } const [, fp] = TokenCollection.fromPatterns(dpfp, [/\./, /[0-9]+/]); if (!fp || !fp.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'fractional part' }], partName: 'fractional part', }); } if (!fp.match(/[0-9]+/)) { return fp.unmatched({ reason: 'unexpected-token', expects: [{ type: 'common', value: 'fractional part' }], partName: 'fractional part', }); } if (!(1 <= fp.length && fp.length <= 3)) { return fp.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 1, lte: 3 }, expects: [], partName: 'fractional part', }); } }, ws => {}, unit => { const expects = ( [ { type: 'const', value: 'w' }, { type: 'const', value: 'd' }, { type: 'const', value: 'h' }, { type: 'const', value: 'm' }, { type: 'const', value: 's' }, ] as const ).filter(e => !specified.has(e.value)); if (!unit || !unit.value) { return unmatched('', 'missing-token', { expects, partName: 'unit', }); } const unitVal = unit.value.toLowerCase() as 'w' | 'd' | 'h' | 'm' | 's'; if (specified.has(unitVal)) { return unit.unmatched({ reason: 'duplicated', expects, partName: 'unit', }); } if (dpfp && dpfp.value && unit.match(['w', 'd', 'h', 'm'])) { return unit.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 's' }], partName: 'unit', }); } if (!unit.match(['w', 'd', 'h', 'm', 's'])) { return unit.unmatched({ reason: 'unexpected-token', expects, partName: 'unit', }); } specified.add(unitVal); }, ws => {}, ); if (!res.matched) { log('Failed: %O', res); return res; } } return matched(); };
the_stack
import { BasicEntityGetter, BasicListGetter, DataCache, FilterBuilder, ListView, ServerError } from "@batch-flask/core"; import { LoadingStatus } from "@batch-flask/ui/loading"; import { List, OrderedSet } from "immutable"; import { from, of } from "rxjs"; import { flatMap } from "rxjs/operators"; import { FakeModel } from "../test/fake-model"; const fake1 = { id: "1", parentId: "parent-1", state: "active", name: "Fake1" }; const fake2 = { id: "2", parentId: "parent-1", state: "active", name: "Fake2" }; const fake3 = { id: "3", parentId: "parent-1", state: "running", name: "Fake3" }; const fake4 = { id: "4", parentId: "parent-1", state: "running", name: "Fake4" }; const fake5 = { id: "5", parentId: "parent-1", state: "completed", name: "Fake5" }; const firstPage = [ { id: "1", state: "active", name: "Fake1" }, { id: "2", state: "active", name: "Fake2" }, { id: "3", state: "running", name: "Fake3" }, ]; const secondPage = [ { id: "4", state: "running", name: "Fake4" }, { id: "5", state: "completed", name: "Fake5" }, ]; const filteredData = [ { id: "1", state: "active", name: "Fake1" }, { id: "3", state: "running", name: "Fake3" }, { id: "4", state: "running", name: "Fake4" }, ]; const filters = { filter1: FilterBuilder.prop("id").eq("filter1"), filter2: FilterBuilder.prop("id").eq("filter2"), badFilter: FilterBuilder.prop("id").eq("bad-filter"), }; function getData(params, options, nextLink) { if (options && options.filter === filters.filter2) { return { data: filteredData, }; } else if (nextLink) { return { data: secondPage, }; } else { return { data: firstPage, nextLink: "#page2", }; } } describe("ListView", () => { let getter: BasicListGetter<FakeModel, {}>; let cache: DataCache<FakeModel>; let dataSpy: jasmine.Spy; let view: ListView<FakeModel, {}>; let items: List<FakeModel>; let hasMore: boolean; let status: LoadingStatus; let error: ServerError; beforeEach(() => { cache = new DataCache<FakeModel>(); dataSpy = jasmine.createSpy("supplyDataSpy").and.callFake((params, options, nextLink) => { if (options && options.filter === filters.badFilter) { return from(Promise.reject(new ServerError({ status: 409, message: "Conflict on the resource", code: "Conflict", }))); } else { return from(Promise.resolve(getData(params, options, nextLink))); } }); getter = new BasicListGetter(FakeModel, { cache: () => cache, supplyData: dataSpy, }); view = new ListView({ cache: () => cache, getter: getter, }); view.params = { parentId: "parent-1", }; view.items.subscribe(x => items = x); view.hasMore.subscribe(x => hasMore = x); view.status.subscribe(x => status = x); view.error.subscribe(x => error = x); }); afterEach(() => { view.dispose(); }); it("should have no items and ready to load more by default", () => { expect(hasMore).toBe(true); expect(items.toJS()).toEqual([]); }); it("It retrieve the first batch of items", (done) => { view.fetchNext().subscribe(() => { expect(items.toJS()).toEqual([fake1, fake2, fake3]); expect(dataSpy).toHaveBeenCalledTimes(1); expect(hasMore).toBe(true); done(); }); }); it("It retrieve the next batch of items", (done) => { view.fetchNext().pipe( flatMap(() => view.fetchNext()), ).subscribe(() => { expect(dataSpy).toHaveBeenCalledTimes(2); expect(items.toJS()).toEqual([fake1, fake2, fake3, fake4, fake5]); expect(hasMore).toBe(false); done(); }); }); it("It fetch all", (done) => { view.fetchAll().subscribe(() => { expect(items.toJS()).toEqual([fake1, fake2, fake3, fake4, fake5]); expect(dataSpy).toHaveBeenCalledTimes(2); expect(hasMore).toBe(false); done(); }); }); it("should clear the items when refresing with params true", (done) => { view.fetchNext().subscribe(() => { expect(dataSpy).toHaveBeenCalledTimes(1); const obs = view.refresh(true); expect(items.size).toBe(0, "Should have cleared the items"); obs.subscribe(() => { expect(dataSpy).toHaveBeenCalledTimes(2); expect(items.toJS()).toEqual([fake1, fake2, fake3]); done(); }); }); }); it("should not clear the items when refresing with params false", (done) => { view.fetchNext().subscribe(() => { expect(dataSpy).toHaveBeenCalledTimes(1); const obs = view.refresh(false); expect(items.size).not.toBe(0, "Should NOT have cleared the items"); items = List(); // Make sure it get the new value obs.subscribe(() => { view.items.subscribe(x => items = x); expect(dataSpy).toHaveBeenCalledTimes(2); expect(items.toJS()).toEqual([fake1, fake2, fake3]); done(); }); }); }); it("#refreshAll() should get all the items", (done) => { items = List([]); // Reset the items to make sure it loads all of them again view.refreshAll().subscribe(() => { expect(items.toJS()).toEqual([fake1, fake2, fake3, fake4, fake5]); done(); }); }); it("it should apply the options", (done) => { view.fetchNext().subscribe(() => { expect(items.toJS()).toEqual([fake1, fake2, fake3]); expect(dataSpy).toHaveBeenCalledTimes(1); view.setOptions({ filter: filters.filter2 }); view.fetchNext().subscribe(() => { expect(dataSpy).toHaveBeenCalledTimes(2); expect(items.toJS()).toEqual([fake1, fake3, fake4], "Should have updated to the new data"); expect(hasMore).toBe(false); done(); }); }); }); it("should return hasMore false if there is only 1 page of data after first fetch", (done) => { view.setOptions({ filter: filters.filter2 }); view.fetchNext().subscribe(() => { expect(items.toJS()).toEqual([fake1, fake3, fake4]); expect(hasMore).toBe(false); done(); }); }); it("Should remove item from the list when the cache call onItemDeleted", (done) => { view.fetchNext().subscribe(() => { const subSpy = jasmine.createSpy("items sub"); view.items.subscribe(subSpy); expect(subSpy).toHaveBeenCalledTimes(1); // Should initialy get called cache.deleteItemByKey("2"); expect(subSpy).toHaveBeenCalledTimes(2); // Should not have been called more than once const newList = [fake1, fake3]; expect(items.toJS()).toEqual(newList); done(); }); }); describe("#loadNewItem()", () => { beforeEach((done) => { view.fetchNext().subscribe(() => done()); }); it("should NOT add the item if already present and update exiting one", (done) => { const getter = new BasicEntityGetter(FakeModel, { cache: () => cache, supplyData: () => of({ id: "2", state: "running", name: "Fake2" }), }); const expected = [ fake1, { id: "2", parentId: "parent-1", state: "running", name: "Fake2" }, fake3, ]; view.loadNewItem(getter.fetch({ parentId: "parent-1", id: "2" })).subscribe(() => { expect(items.toJS()).toEqual(expected); done(); }); }); it("should add the item if NOT already present", (done) => { const getter = new BasicEntityGetter(FakeModel, { cache: () => cache, supplyData: () => of({ id: "4", state: "running", name: "Fake4" }), }); const expected = [ { id: "4", parentId: "parent-1", state: "running", name: "Fake4" }, ].concat([fake1, fake2, fake3]); view.loadNewItem(getter.fetch({ parentId: "parent-1", id: "4" })).subscribe(() => { expect(items.toJS()).toEqual(expected); done(); }); }); }); describe("when there is keys in the cachedKeys", () => { beforeEach((done) => { // This should set the query cache view.setOptions({ filter: filters.filter2 }); view.fetchNext().subscribe(() => done()); }); it("should have set the query cache", () => { const queryCache = cache.queryCache.getKeys(filters.filter2.toOData()); expect(queryCache).not.toBeFalsy(); expect(queryCache.keys).toEqualImmutable(OrderedSet(["1", "3", "4"])); }); }); describe("when first call returns an error", () => { let thrownError: ServerError; beforeEach((done) => { view.setOptions({ filter: filters.badFilter }); view.fetchNext().subscribe( () => done(), (e) => { thrownError = e; done(); }, ); }); it("should have the status set to Error", () => { expect(status).toBe(LoadingStatus.Error); }); it("should have have an error", () => { expect(thrownError).not.toBeFalsy(); expect(error).not.toBeFalsy(); expect(error instanceof ServerError).toBe(true); }); it("should have set hasMore item to false", () => { expect(hasMore).toBe(false); }); it("should not fetch next", (done) => { expect(dataSpy).toHaveBeenCalledOnce(); view.fetchNext().subscribe(() => { // only the initial call expect(dataSpy).toHaveBeenCalledOnce(); done(); }, () => { expect(false).toBe(true, "Should not have returned a failure here"); }); }); it("should fetch next if forcing new data", (done) => { view.refresh().subscribe({ next: () => { // only the initial call expect(false).toBe(true, "Should not have returned a success here"); }, error: () => { expect(dataSpy).toHaveBeenCalledTimes(2); done(); }, }); }); it("should fix the error if changing filter to a valid one", (done) => { view.setOptions({ filter: filters.filter1 }); view.fetchNext().subscribe({ next: () => { expect(dataSpy).toHaveBeenCalledTimes(2); done(); }, error: () => { // only the initial call expect(false).toBe(true, "Should not have returned a failure here"); }, }); }); }); });
the_stack
import _ = require('lodash'); import RX = require('reactxp'); import * as CommonStyles from '../CommonStyles'; import { Test, TestResult, TestType } from '../Test'; const _styles = { container: RX.Styles.createViewStyle({ flex: 1, alignSelf: 'stretch', flexDirection: 'column', alignItems: 'flex-start' }), explainTextContainer: RX.Styles.createViewStyle({ margin: 12 }), explainText: RX.Styles.createTextStyle({ fontSize: CommonStyles.generalFontSize, color: CommonStyles.explainTextColor }), resultContainer: RX.Styles.createViewStyle({ margin: 12, flexDirection: 'row', alignItems: 'center', alignSelf: 'stretch' }), resultText: RX.Styles.createTextStyle({ flex: -1, marginLeft: 12, fontSize: CommonStyles.generalFontSize, color: CommonStyles.explainTextColor }), textInput1: RX.Styles.createTextInputStyle({ flex: 1, maxWidth: 200, borderWidth: 1, fontSize: CommonStyles.generalFontSize, padding: 4, borderColor: '#999' }), textInput2: RX.Styles.createTextInputStyle({ flex: 1, width: 200, borderWidth: 1, fontSize: CommonStyles.generalFontSize, color: 'green', padding: 4, borderColor: '#999' }), textInput3: RX.Styles.createTextInputStyle({ margin: 12, width: 200, height: 100, borderWidth: 1, fontSize: CommonStyles.generalFontSize, padding: 4, borderColor: '#999' }), textInput7: RX.Styles.createTextInputStyle({ flex: 1, maxWidth: 200, borderWidth: 1, fontSize: CommonStyles.generalFontSize, padding: 4, borderColor: '#999', shadowColor: 'red', shadowOffset: { width: 1, height: 4 }, shadowRadius: 5 }), eventHistoryScrollView: RX.Styles.createScrollViewStyle({ margin: 12, padding: 8, alignSelf: 'stretch', height: 100, backgroundColor: '#eee' }), eventHistoryText: RX.Styles.createTextStyle({ fontSize: 12, }), placeholder: RX.Styles.createViewStyle({ width: 1, height: 300 }), button: RX.Styles.createButtonStyle({ alignSelf: 'flex-start', borderWidth: 1, borderColor: '#666', borderRadius: 6, paddingHorizontal: 8, paddingVertical: 4, marginTop: 4 }), buttonText: RX.Styles.createTextStyle({ fontSize: CommonStyles.generalFontSize, color: '#666' }) }; interface TextInputViewState { test1Input: string; test2Input: string; test6Input: string; test6EventHistory: string[]; test7Input: string; } class TextInputView extends RX.Component<RX.CommonProps, TextInputViewState> { private _multilineTextInput: RX.TextInput | null = null; constructor(props: RX.CommonProps) { super(props); this.state = { test1Input: '', test2Input: '', test6Input: '', test6EventHistory: [], test7Input: '' }; } render() { return ( <RX.View style={ _styles.container}> <RX.View style={ _styles.explainTextContainer } key={ 'explanation1' }> <RX.Text style={ _styles.explainText }> { 'This is a single-line text input box. ' + 'The placeholder text is light blue. ' + 'Input is limited to 8 characters in length. ' + 'Text is centered. ' + 'Auto-correct is disabled. ' + 'Auto-focus is enabled. ' + 'The return key type (for on-screen keyboards) is "done". ' } </RX.Text> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput style={ _styles.textInput1 } placeholder={ 'Type here' } placeholderTextColor={ 'blue' } maxLength={ 10 } returnKeyType={ 'done' } value={ this.state.test1Input } autoCorrect={ false } accessibilityId={ 'TextInputViewTextInput' } autoFocus={ true } onChangeText={ val => this.setState({ test1Input: val }) } /> <RX.Text style={ _styles.resultText } numberOfLines={ 1 }> { this.state.test1Input } </RX.Text> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation2' }> <RX.Text style={ _styles.explainText }> { 'This is a multi-line text input box. ' + 'For on-screen keyboards, the return key should be "go", and the keyboard should use a light theme. ' + 'Text should be green. ' + 'It supports auto correct, auto capitalization (individual words), and spell checking. ' } </RX.Text> <RX.Text style={ _styles.explainText }> { 'Press this button to set the focus to the multi-line text input box below. ' } </RX.Text> <RX.Button style={ _styles.button } onPress={ this._onPressFocus }> <RX.Text style={ _styles.buttonText }> { 'Focus' } </RX.Text> </RX.Button> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput ref={ this._onMountTextInput } style={ _styles.textInput2 } placeholder={ 'Placeholder text' } returnKeyType={ 'go' } value={ this.state.test2Input } onChangeText={ val => this.setState({ test2Input: val }) } allowFontScaling={ false } autoCorrect={ true } autoCapitalize={ 'words' } spellCheck={ true } blurOnSubmit={ true } editable={ true } keyboardAppearance={ 'light' } multiline={ true } /> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation3' }> <RX.Text style={ _styles.explainText }> { 'This text input box uses the "defaultValue" to specify the initial value. ' + 'The keyboard type is "numeric". ' + 'The text is right-justified. ' + 'The return key type (for on-screen keyboards) is "send". ' } </RX.Text> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput style={ _styles.textInput1 } placeholder={ 'PIN' } returnKeyType={ 'send' } keyboardType={ 'numeric' } defaultValue={ '1234' } disableFullscreenUI={ true } /> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation4' }> <RX.Text style={ _styles.explainText }> { 'This text input box is not editable. ' } </RX.Text> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput style={ _styles.textInput1 } placeholder={ 'Disabled' } editable={ false } /> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation5' }> <RX.Text style={ _styles.explainText }> { 'This text input box obscures the text (for password entry). ' + 'It uses an "email-address" keyboard type. ' } </RX.Text> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput style={ _styles.textInput1 } placeholder={ 'Enter password' } secureTextEntry={ true } keyboardType={ 'email-address' } /> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation6' }> <RX.Text style={ _styles.explainText }> { 'This is a multi-line text input box. ' + 'It records and displays all events (displayed in reverse order). Try focus, blur, typing, ' + 'pasting, scrolling, changing selections, and submitting (hit return). ' } </RX.Text> </RX.View> <RX.TextInput style={ _styles.textInput3 } autoCorrect={ false } value={ this.state.test6Input } onChangeText={ this._onChangeTextTest6 } onKeyPress={ this._onKeyPressTest6 } onBlur={ this._onBlurTest6 } onFocus={ this._onFocusTest6 } onPaste={ this._onPasteTest6 } onScroll={ this._onScrollTest6 } onSelectionChange={ this._onSelectionChangeTest6 } onSubmitEditing={ this._onSubmitEditingTest6 } multiline={ true } /> <RX.View style={ _styles.eventHistoryScrollView }> <RX.ScrollView> <RX.Text style={ _styles.eventHistoryText }> { this.state.test6EventHistory.length ? this.state.test6EventHistory.join('\n') : 'Event history will appear here' } </RX.Text> </RX.ScrollView> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation7' }> <RX.Text style={ _styles.explainText }> { 'The text entered in this input box will have a red shadow.' } </RX.Text> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput style={ _styles.textInput7 } value={ this.state.test7Input } onChangeText={ val => this.setState({ test7Input: val }) } /> <RX.Text style={ _styles.resultText }> { this.state.test1Input } </RX.Text> </RX.View> <RX.View style={ _styles.explainTextContainer } key={ 'explanation8' }> <RX.Text style={ _styles.explainText }> { 'This text input box uses the "clearButtonMode" prop to hide the `X` that appears while typing. ' + '(This is only relevant to iOS and UWP apps). ' } </RX.Text> </RX.View> <RX.View style={ _styles.resultContainer }> <RX.TextInput style={ _styles.textInput1 } placeholder={ 'This box will not have the usual `X` delete button as you type.' } clearButtonMode={ 'never' } /> </RX.View> <RX.View style={ _styles.placeholder }/> </RX.View> ); } private _onMountTextInput = (elem: any) => { this._multilineTextInput = elem; } private _onPressFocus = (e: RX.Types.SyntheticEvent) => { e.stopPropagation(); if (this._multilineTextInput) { this._multilineTextInput.focus(); } } private _onChangeTextTest6 = (value: string) => { this.setState({ test6Input: value }); this._appendHistoryTest6('onChangeText'); } private _onKeyPressTest6 = (e: RX.Types.KeyboardEvent) => { let eventText = 'onKeyPress: ' + 'Key = "' + e.key + '", Code = ' + e.keyCode; this._appendHistoryTest6(eventText); } private _onPasteTest6 = (e: RX.Types.ClipboardEvent) => { this._appendHistoryTest6('onPaste'); } private _onScrollTest6 = (newScrollLeft: number, newScrollTop: number) => { this._appendHistoryTest6('onSroll: (left=' + newScrollLeft + ', top=' + newScrollTop + ')'); } private _onBlurTest6 = (e: RX.Types.FocusEvent) => { this._appendHistoryTest6(`onBlur: ${this._focusEventToString(e)}`); } private _onFocusTest6 = (e: RX.Types.FocusEvent) => { this._appendHistoryTest6(`onFocus: ${this._focusEventToString(e)}`); } private _focusEventToString = ({ bubbles, cancelable, defaultPrevented, timeStamp, nativeEvent }: RX.Types.FocusEvent) => { return JSON.stringify({ bubbles, cancelable, defaultPrevented, timeStamp, nativeEvent }); } private _onSelectionChangeTest6 = (start: number, end: number) => { this._appendHistoryTest6('onSelectionChange: [' + start + ', ' + end + ']'); } private _onSubmitEditingTest6 = () => { this._appendHistoryTest6('onSubmitEditing'); } private _appendHistoryTest6(newLine: string) { // Prepend it so we can always see the latest. // Limit to the last 20 items. let newHistory = [newLine].concat(_.slice(this.state.test6EventHistory, 0, 18)); this.setState({ test6EventHistory: newHistory }); } } class TextInputTest implements Test { getPath(): string { return 'Components/TextInput/Interactive'; } getTestType(): TestType { return TestType.Interactive; } render(onMount: (component: any) => void): RX.Types.ReactNode { return ( <TextInputView ref={ onMount }/> ); } } export default new TextInputTest();
the_stack
///<reference path='../../lib/Addon.node.d.ts' /> // // Copyright (C) Microsoft. All rights reserved. // import { IChromeInstance } from '../../lib/EdgeAdapterInterfaces'; import * as edgeAdapter from '../../lib/Addon.node'; // const binding_path = binary.find(path.resolve(path.join(__dirname,'../../../package.json'))); // var edgeAdapter = require(binding_path); import * as http from 'http'; import * as ws from 'ws'; import * as fs from 'fs'; import * as crypto from 'crypto'; import { Server as WebSocketServer } from 'ws'; declare var __dirname; export module EdgeAdapter { export class Service { private _httpServer: http.Server; private _webSocketServer: WebSocketServer; private _serverPort: number; private _chromeToolsPort: number; private _guidToIdMap: Map<string, string> = new Map<string, string>(); private _idToEdgeMap: Map<string, edgeAdapter.EdgeInstanceId> = new Map<string, edgeAdapter.EdgeInstanceId>(); private _idToNetWorkProxyMap: Map<string, edgeAdapter.NetworkProxyInstanceId> = new Map<string, edgeAdapter.NetworkProxyInstanceId>(); private _edgeToWSMap: Map<edgeAdapter.EdgeInstanceId, ws[]> = new Map<edgeAdapter.EdgeInstanceId, ws[]>(); private _diagLogging: boolean = false; private _newtworkProxyImplementedRequests: Array<string> = new Array<string>('Network.enable', 'Network.disable', 'Network.getResponseBody'); constructor(diagLogging: boolean) { this._diagLogging = diagLogging; } public run(serverPort: number, chromeToolsPort: number, url: string): void { this._serverPort = serverPort; this._chromeToolsPort = chromeToolsPort; edgeAdapter.initialize(__dirname, (id, msg) => this.onEdgeMessage(id, msg), (msg) => this.onLogMessage(msg)); edgeAdapter.setSecurityACLs(__dirname + "\\..\\..\\lib\\"); if (chromeToolsPort > 0) { edgeAdapter.serveChromeDevTools(chromeToolsPort); } if (url) { edgeAdapter.openEdge(url); } this._httpServer = http.createServer((req, res) => this.onServerRequest(req, res)); this._webSocketServer = new WebSocketServer({ server: this._httpServer }); this._webSocketServer.on('connection', (client, message) => this.onWSSConnection(client, message)); this._httpServer.listen(serverPort, "0.0.0.0"); } private onServerRequest(request: http.IncomingMessage, response: http.ServerResponse): void { // Normalize request url let url = request.url.trim().toLocaleLowerCase(); // Extract parameter list // TODO: improve the parameter extraction let urlParts = this.extractParametersFromUrl(url); url = urlParts.url; let param = urlParts.paramChain; if (url.lastIndexOf('/') == url.length - 1) { url = url.substr(0, url.length - 1); } const host = request.headers.host || "localhost"; switch (url) { case '/json': case '/json/list': // Respond with json response.writeHead(200, { "Content-Type": "text/json" }); response.write(JSON.stringify(this.getEdgeJson(host))); response.end(); break; case '/json/version': // Write out protocol.json file response.writeHead(200, { "Content-Type": "text/json" }); response.write(this.getEdgeVersionJson()); response.end(); break; case '/json/protocol': // Write out protocol.json file response.writeHead(200, { "Content-Type": "text/json" }); response.write(this.getChromeProtocol()); response.end(); break; case '': // Respond with attach page response.writeHead(200, { "Content-Type": "text/html" }); response.write(fs.readFileSync(__dirname + '/../chromeProtocol/inspect.html', 'utf8')); response.end(); break; case '/json/new': // create a new tab if (!param) { param = ""; } this.createNewTab(param, host, response) break; case '/json/close': // close a tab response.writeHead(200, { "Content-Type": "text/html" }); this.closeEdgeInstance(param); response.end(); break; default: // Not found response.writeHead(404, { "Content-Type": "text/html" }); response.end(); break; } } private createNewTab(param: string, host: any, response: http.ServerResponse) { let initialChromeTabs = this.getEdgeJson(host); let retries = 200; // Retry for 30 seconds. if (edgeAdapter.openEdge(param)) { const getNewTab = () => { let actualChromeTabs = this.getEdgeJson(host); let newTabInfo = this.getNewTabInfo(initialChromeTabs, actualChromeTabs, param); if (!newTabInfo && retries > 0) { retries--; return setTimeout(getNewTab, 150); } response.write(JSON.stringify(newTabInfo)); response.end(); } return getNewTab(); } else { response.end(); } } private getNewTabInfo(initialInstances: IChromeInstance[], actualInstances: IChromeInstance[], url: string): IChromeInstance { for (var index = 0; index < actualInstances.length; index++) { let element = actualInstances[index]; if (!initialInstances.some(x => x.id == element.id)) { return element; } } return null; } private onWSSConnection(ws: ws, message?: http.IncomingMessage): void { // Normalize request url if (!message) { return; } let url = message.url.trim().toUpperCase(); if (url.lastIndexOf('/') == url.length - 1) { url = url.substr(0, url.length - 1); } let guid = url; const index = guid.lastIndexOf('/'); if (index != -1) { guid = guid.substr(index + 1); } let succeeded = false; let instanceId: edgeAdapter.EdgeInstanceId = null; let networkInstanceId: edgeAdapter.NetworkProxyInstanceId = null; if (this._guidToIdMap.has(guid)) { const id = this._guidToIdMap.get(guid); instanceId = this._idToEdgeMap.get(id); if (!instanceId) { // New connection instanceId = edgeAdapter.connectTo(id); if (instanceId) { this.injectAdapterFiles(instanceId); this._idToEdgeMap.set(id, instanceId); this._edgeToWSMap.set(instanceId, [ws]); succeeded = true; } } else { // Already connected const sockets = this._edgeToWSMap.get(instanceId); sockets.push(ws); this._edgeToWSMap.set(instanceId, sockets); succeeded = true; } networkInstanceId = this._idToNetWorkProxyMap.get(id); if (!networkInstanceId) { networkInstanceId = edgeAdapter.createNetworkProxyFor(id); if (networkInstanceId) { this._idToNetWorkProxyMap.set(id, networkInstanceId); this._idToNetWorkProxyMap.set(networkInstanceId, id); } } } if (succeeded && networkInstanceId) { // Forward messages to the proxy ws.on('message', (msg: ws.Data) => { if (this._diagLogging) { console.log("Client:", instanceId, msg); } if (this.isMessageForNetworkProxy(msg)) { edgeAdapter.forwardTo(networkInstanceId.toString(), msg.toString()); } else { edgeAdapter.forwardTo(instanceId.toString(), msg.toString()); } }); const removeSocket = (instanceId: edgeAdapter.EdgeInstanceId) => { const sockets = this._edgeToWSMap.get(instanceId); const index = sockets.indexOf(ws); if (index > -1) { sockets.splice(index, 1); } this._edgeToWSMap.set(instanceId, sockets); }; // Remove socket on close or error ws.on('close', () => { removeSocket(instanceId); }); ws.on('error', () => { removeSocket(instanceId); }); } else { // No matching Edge instance ws.close(); } } private log(message: string): void { this.onLogMessage(message); } private isMessageForNetworkProxy(requestMessage: ws.Data): boolean { var parsedMessage: Object; try { parsedMessage = JSON.parse(requestMessage.toString()); } catch (SyntaxError) { console.log("Error parsing request message: ", requestMessage); return false; } let requestType = parsedMessage['method'] as string; return this._newtworkProxyImplementedRequests.indexOf(requestType) != -1; } private onEdgeMessage(instanceId: edgeAdapter.EdgeInstanceId, msg: string): void { if (this._diagLogging) { console.log("EdgeService:", instanceId, msg); } let edgeProxyId; if (this._idToNetWorkProxyMap.has(instanceId)) { // message comes from network proxy, we get he edge proxy id const id = this._idToNetWorkProxyMap.get(instanceId) edgeProxyId = this._idToEdgeMap.get(id); } else { edgeProxyId = instanceId; } if (this._edgeToWSMap.has(edgeProxyId)) { const sockets = this._edgeToWSMap.get(edgeProxyId) for (let i = 0; i < sockets.length; i++) { sockets[i].send(msg); } } } private onLogMessage(msg: string): void { console.log("Log: " + msg); } private injectAdapterFiles(instanceId: edgeAdapter.EdgeInstanceId): void { const files: { engine: edgeAdapter.EngineType, filename: string }[] = [ { engine: "browser", filename: "assert.js" }, { engine: "browser", filename: "common.js" }, { engine: "browser", filename: "browser.js" }, { engine: "browser", filename: "dom.js" }, { engine: "browser", filename: "runtime.js" }, { engine: "browser", filename: "page.js" }, { engine: "browser", filename: "CssParser.js" }, { engine: "browser", filename: "browserTool.js" }, { engine: "browser", filename: "network.js" }, { engine: "debugger", filename: "assert.js" }, { engine: "debugger", filename: "common.js" }, { engine: "debugger", filename: "debugger.js" }, ]; for (let i = 0; i < files.length; i++) { const script = fs.readFileSync(__dirname + '/../chromeProtocol/' + files[i].filename, 'utf8'); this.log(`Injecting '${files[i].engine}:${files[i].filename}'`); edgeAdapter.injectScriptTo(instanceId, files[i].engine, files[i].filename, script); } } private getEdgeJson(host: string | string[]): IChromeInstance[] { const chromeInstances: IChromeInstance[] = []; const map = new Map<string, string>(); const instances = edgeAdapter.getEdgeInstances(); if (this._diagLogging) { console.log("Edge Instances:", instances); } for (let i = 0; i < instances.length; i++) { // Get or generate a new guid let guid: string = null; if (!this._guidToIdMap.has(instances[i].id)) { guid = this.createGuid(); } else { guid = this._guidToIdMap.get(instances[i].id); } map.set(guid, instances[i].id); map.set(instances[i].id, guid); const websocket = `ws://${host}/devtools/page/${guid}`; const devtools = `chrome-devtools://devtools/bundled/inspector.html?ws=${websocket.substr(5)}`; // Generate the json description of this instance chromeInstances.push({ description: instances[i].processName, devtoolsFrontendUrl: devtools, id: guid, title: instances[i].title, type: "page", url: instances[i].url, webSocketDebuggerUrl: websocket }); } // Reset the map to the new instances this._guidToIdMap = map; return chromeInstances; } private getEdgeVersionJson(): string { // Todo: Currently Edge does not store it's UA string and there is no way to fetch the UA without loading Edge. const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586"; const version = { "Browser": "Microsoft Edge 13", "Protocol-Version": "1", "User-Agent": userAgent, "WebKit-Version": "0" }; return JSON.stringify(version); } private getChromeProtocol(): string { const script = fs.readFileSync(__dirname + '/../chromeProtocol/protocol.json', 'utf8'); return script; } private createGuid(): string { const g: string = crypto.createHash('md5').update(Math.random().toString()).digest('hex').toUpperCase(); return `${g.substring(0, 8)}-${g.substring(9, 13)}-${g.substring(13, 17)}-${g.substring(17, 21)}-${g.substring(21, 31)}` } private extractParametersFromUrl(url: string): { url: string, paramChain: string } { let parameters; const closeUrl = '/json/close'; if (url.indexOf('/json/new') != -1) { const urlSegements = url.split('?'); if (urlSegements.length > 1) { url = urlSegements[0]; parameters = urlSegements[1]; } } else if (url.indexOf(closeUrl) != -1) { parameters = url.replace(`${closeUrl}/`, ''); url = url.slice(0, closeUrl.length); } return { url: url, paramChain: parameters }; } private closeEdgeInstance(guid: string): boolean { var edgeResult = false; var networkProxyResult = false; const id = this._guidToIdMap.get(guid.toLocaleUpperCase()); if (id) { edgeResult = edgeAdapter.closeEdge(id); const networkInstanceId = this._idToNetWorkProxyMap.get(id); if (networkInstanceId) { networkProxyResult = edgeAdapter.closeNetworkProxyInstance(networkInstanceId); } // tab is closed, clean all the mappings and close connections let instanceId = this._idToEdgeMap.get(id); const sockets = this._edgeToWSMap.get(instanceId) if (sockets) { for (let i = 0; i < sockets.length; i++) { sockets[i].removeAllListeners(); sockets[i].close(); } } this._edgeToWSMap.delete(instanceId); this._guidToIdMap.delete(guid.toLocaleUpperCase()); this._guidToIdMap.delete(id); this._idToNetWorkProxyMap.delete(id); this._idToNetWorkProxyMap.delete(networkInstanceId); this._idToEdgeMap.delete(id); } return edgeResult && networkProxyResult; } } }
the_stack
import { moment, Notice, TFile } from 'obsidian'; import { createDailyNote } from 'obsidian-daily-notes-interface'; import { getDailyNoteSettings } from '_obsidian-daily-notes-interface@0.9.4@obsidian-daily-notes-interface'; import { t } from '../translations/helper'; import { UseDailyOrPeriodic } from '../memos'; namespace utils { export function getNowTimeStamp(): number { return parseInt(moment().format('x')); } export function getOSVersion(): 'Windows' | 'MacOS' | 'Linux' | 'Unknown' { const appVersion = navigator.userAgent; let detectedOS: 'Windows' | 'MacOS' | 'Linux' | 'Unknown' = 'Unknown'; if (appVersion.indexOf('Win') != -1) { detectedOS = 'Windows'; } else if (appVersion.indexOf('Mac') != -1) { detectedOS = 'MacOS'; } else if (appVersion.indexOf('Linux') != -1) { detectedOS = 'Linux'; } return detectedOS; } export function getTimeStampByDate(t: Date | number | string): number { if (typeof t === 'string') { t = t.replaceAll('-', '/'); } return new Date(t).getTime(); } export function getDateStampByDate(t: Date | number | string): number { const d = new Date(getTimeStampByDate(t)); return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); } export function getDateString(t: Date | number | string): string { const d = new Date(getTimeStampByDate(t)); const year = d.getFullYear(); const month = d.getMonth() + 1; const date = d.getDate(); return `${year}/${month}/${date}`; } export function getTimeString(t: Date | number | string): string { const d = new Date(getTimeStampByDate(t)); const hours = d.getHours(); const mins = d.getMinutes(); const hoursStr = hours < 10 ? '0' + hours : hours; const minsStr = mins < 10 ? '0' + mins : mins; return `${hoursStr}:${minsStr}`; } // For example: 2021-4-8 17:52:17 export function getDateTimeString(t: Date | number | string): string { const d = new Date(getTimeStampByDate(t)); const year = d.getFullYear(); const month = d.getMonth() + 1; const date = d.getDate(); const hours = d.getHours(); const mins = d.getMinutes(); const secs = d.getSeconds(); const monthStr = month < 10 ? '0' + month : month; const dateStr = date < 10 ? '0' + date : date; const hoursStr = hours < 10 ? '0' + hours : hours; const minsStr = mins < 10 ? '0' + mins : mins; const secsStr = secs < 10 ? '0' + secs : secs; // const secsStr = '00'; return `${year}/${monthStr}/${dateStr} ${hoursStr}:${minsStr}:${secsStr}`; } export function dedupe<T>(data: T[]): T[] { return Array.from(new Set(data)); } export function dedupeObjectWithId<T extends { id: string }>(data: T[]): T[] { const idSet = new Set<string>(); const result = []; for (const d of data) { if (!idSet.has(d.id)) { idSet.add(d.id); result.push(d); } } return result; } export function debounce(fn: FunctionType, delay: number) { let timer: number | null = null; return () => { if (timer) { clearTimeout(timer); timer = setTimeout(fn, delay); } else { timer = setTimeout(fn, delay); } }; } export function debouncePlus(fn: FunctionType, delay: number, immdiate = false, resultCallback) { let timer: number = null; let isInvoke = false; function _debounce(...arg: any[]) { if (timer) clearTimeout(timer); if (immdiate && !isInvoke) { const result = fn.apply(this, arg); if (resultCallback && typeof resultCallback === 'function') resultCallback(result); isInvoke = true; } else { timer = setTimeout(() => { const result = fn.apply(this, arg); if (resultCallback && typeof resultCallback === 'function') resultCallback(result); isInvoke = false; timer = null; }, delay); } } console.log('hi'); _debounce.cancel = function () { if (timer) clearTimeout(timer); timer = null; isInvoke = false; }; return _debounce; } export function throttle(fn: FunctionType, delay: number) { let valid = true; return () => { if (!valid) { return false; } valid = false; setTimeout(() => { fn(); valid = true; }, delay); }; } export function transformObjectToParamsString(object: KVObject): string { const params = []; const keys = Object.keys(object).sort(); for (const key of keys) { const val = object[key]; if (val) { if (typeof val === 'object') { params.push(...transformObjectToParamsString(val).split('&')); } else { params.push(`${key}=${val}`); } } } return params.join('&'); } export function transformParamsStringToObject(paramsString: string): KVObject { const object: KVObject = {}; const params = paramsString.split('&'); for (const p of params) { const [key, val] = p.split('='); if (key && val) { object[key] = val; } } return object; } export function filterObjectNullKeys(object: KVObject): KVObject { if (!object) { return {}; } const finalObject: KVObject = {}; const keys = Object.keys(object).sort(); for (const key of keys) { const val = object[key]; if (typeof val === 'object') { const temp = filterObjectNullKeys(JSON.parse(JSON.stringify(val))); if (temp && Object.keys(temp).length > 0) { finalObject[key] = temp; } } else { if (val) { finalObject[key] = val; } } } return finalObject; } export async function copyTextToClipboard(text: string) { if (navigator.clipboard && navigator.clipboard.writeText) { try { await navigator.clipboard.writeText(text); } catch (error: unknown) { console.warn('Copy to clipboard failed.', error); } } else { console.warn('Copy to clipboard failed, methods not supports.'); } } export function getImageSize(src: string): Promise<{ width: number; height: number }> { return new Promise((resolve) => { const imgEl = new Image(); imgEl.onload = () => { const { width, height } = imgEl; if (width > 0 && height > 0) { resolve({ width, height }); } else { resolve({ width: 0, height: 0 }); } }; imgEl.onerror = () => { resolve({ width: 0, height: 0 }); }; imgEl.className = 'hidden'; imgEl.src = src; document.body.appendChild(imgEl); imgEl.remove(); }); } export async function createDailyNoteCheck(date: any): Promise<TFile> { let file; switch (UseDailyOrPeriodic) { case 'Daily': file = await createDailyNote(date); break; case 'Periodic': file = await window.app.plugins.getPlugin('periodic-notes')?.createDailyNote('day', date); break; default: file = await createDailyNote(date); break; } return file; } } export function getDailyNoteFormat(): string { let dailyNoteFormat = ''; let dailyNoteTempForPeriodicNotes = ''; const folderFromPeriodicNotesNew = window.app.plugins .getPlugin('periodic-notes') ?.calendarSetManager?.getActiveConfig('day')?.folder; const folderFromPeriodicNotes = window.app.plugins.getPlugin('periodic-notes')?.settings?.daily?.format; if (folderFromPeriodicNotesNew === undefined) { dailyNoteTempForPeriodicNotes = folderFromPeriodicNotes; } else { dailyNoteTempForPeriodicNotes = folderFromPeriodicNotesNew; } switch (UseDailyOrPeriodic) { case 'Daily': dailyNoteFormat = getDailyNoteSettings().format || 'YYYY-MM-DD'; break; case 'Periodic': dailyNoteFormat = dailyNoteTempForPeriodicNotes || 'YYYY-MM-DD'; break; default: dailyNoteFormat = getDailyNoteSettings().format || 'YYYY-MM-DD'; break; } if (dailyNoteFormat === '' || dailyNoteFormat === undefined) { new Notice(t("You didn't set format for daily notes in both periodic-notes and daily-notes plugins.")); } return dailyNoteFormat; // if (window.app.plugins.getPlugin('periodic-notes')?.calendarSetManager?.getActiveConfig('day').enabled) { // const periodicNotes = window.app.plugins.getPlugin('periodic-notes'); // dailyNoteFormat = periodicNotes.calendarSetManager.getActiveConfig('day').format || 'YYYY-MM-DD'; // return dailyNoteFormat; // } // if (window.app.plugins.getPlugin('periodic-notes')?.settings?.daily) { // const dailyNotes = window.app.plugins.getPlugin('periodic-notes'); // dailyNoteFormat = dailyNotes.settings.daily.format || 'YYYY-MM-DD'; // return dailyNoteFormat; // } // const dailyNotesSetting = getDailyNoteSettings(); // dailyNoteFormat = dailyNotesSetting.format; // return dailyNoteFormat; } export function getDailyNotePath(): string { let dailyNotePath = ''; let dailyNoteTempForPeriodicNotes = ''; const folderFromPeriodicNotesNew = window.app.plugins .getPlugin('periodic-notes') ?.calendarSetManager?.getActiveConfig('day')?.folder; const folderFromPeriodicNotes = window.app.plugins.getPlugin('periodic-notes')?.settings?.daily?.folder; if (folderFromPeriodicNotesNew === undefined) { dailyNoteTempForPeriodicNotes = folderFromPeriodicNotes; } else { dailyNoteTempForPeriodicNotes = folderFromPeriodicNotesNew; } switch (UseDailyOrPeriodic) { case 'Daily': dailyNotePath = getDailyNoteSettings().folder || ''; break; case 'Periodic': dailyNotePath = dailyNoteTempForPeriodicNotes || ''; break; default: dailyNotePath = getDailyNoteSettings().folder || ''; break; } // console.log(window.app.plugins.getPlugin('periodic-notes')); // const periodicNotes = window.app.plugins.getPlugin('periodic-notes'); // if (folderFromPeriodicNotesNew !== '' && folderFromPeriodicNotesNew !== undefined) { // // const periodicNotes = window.app.plugins.getPlugin('periodic-notes'); // dailyNotePath = window.app.plugins.getPlugin('periodic-notes').calendarSetManager.getActiveConfig('day').folder; // return dailyNotePath; // } // if (folderFromPeriodicNotes !== undefined && folderFromPeriodicNotes !== '') { // // const dailyNotes = window.app.plugins.getPlugin('periodic-notes'); // dailyNotePath = window.app.plugins.getPlugin('periodic-notes').settings.daily.folder; // // console.log(dailyNotePath); // return dailyNotePath; // } // const dailyNotesSetting = getDailyNoteSettings(); // dailyNotePath = dailyNotesSetting.folder; if (dailyNotePath === '' || dailyNotePath === undefined) { new Notice(t("You didn't set folder for daily notes in both periodic-notes and daily-notes plugins.")); } return dailyNotePath; } export default utils;
the_stack
import * as angular from 'angular'; import { ButtonTypeEnum } from './buttonTypeEnum'; import { ButtonTemplateType } from './buttonTemplateType'; export interface IButtonScope extends angular.IScope { disabled: boolean; uifType: string; } export interface IButtonAttributes extends angular.IAttributes { uifType: string; ngHref: string; disabled: string; } /** * @controller * @name ButtonController * @private * @description * Used to more easily inject the Angular $log service into the directive. */ class ButtonController { public static $inject: string[] = ['$log']; constructor(public $log: angular.ILogService) { } } /** * @ngdoc directive * @name uifButton * @module officeuifabric.components.button * * @restrict E * * @description * `<uif-button>` is a button directive. This direcive implements multiple types * of buttons including action, primary, command, compound and hero buttons. Each type * may also support inclusion of icons using the `<uif-icon>` directive. Buttons are * rendered as a `<button>` or `<a>` element depending in an `ng-href` attribute is * specified. All buttons can be disabled by adding the `disabled` attribute * * @see {link http://dev.office.com/fabric/components/button} * * @usage * * Regular buttons: * <uif-button>Lorem Ipsum</uif-button> * * Primary buttons: * <uif-button uif-type="primary">Lorem Ipsum</uif-button> * * Disabled buttons: * <uif-button disabled="disabled">Lorem Ipsum</uif-button> * or * <uif-button ng-disabled="true">Lorem Ipsum</uif-button> * * Command buttons: * <uif-button uif-type="command">Lorem Ipsum</uif-button> * <uif-button uif-type="command"> * <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum * </uif-button> * * Compound buttons: * <uif-button uif-type="Compound">Lorem Ipsum</uif-button> * <uif-button uif-type="Compound"> * Lorem Ipsum * <uif-button-description>Lorem Ipsum Description</uif-button-description> * </uif-button> * * Hero buttons: * <uif-button uif-type="Hero">Lorem Ipsum</uif-button> * <uif-button uif-type="Hero"> * <uif-icon uif-type="plus"></uif-icon> * Lorem Ipsum * </uif-button> */ export class ButtonDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public scope: {} = {}; public controller: any = ButtonController; public controllerAs: string = 'button'; // array of all the possibilities for a button private templateOptions: { [buttonTemplateType: number]: string } = {}; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($log: angular.ILogService) => new ButtonDirective($log); directive.$inject = ['$log']; return directive; } constructor(private $log: angular.ILogService) { this._populateHtmlTemplates(); } public template: any = ($element: angular.IAugmentedJQuery, $attrs: IButtonAttributes) => { // verify button type is supported if (!angular.isUndefined($attrs.uifType) && angular.isUndefined(ButtonTypeEnum[$attrs.uifType])) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.button - Unsupported button: ' + 'The button (\'' + $attrs.uifType + '\') is not supported by the Office UI Fabric. ' + 'Supported options are listed here: ' + 'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/button/buttonTypeEnum.ts'); } // determine template switch ($attrs.uifType) { // if hero, return button | link case ButtonTypeEnum[ButtonTypeEnum.primary]: return angular.isUndefined($attrs.ngHref) ? this.templateOptions[ButtonTemplateType.primaryButton] : this.templateOptions[ButtonTemplateType.primaryLink]; // if command, return button | link case ButtonTypeEnum[ButtonTypeEnum.command]: return angular.isUndefined($attrs.ngHref) ? this.templateOptions[ButtonTemplateType.commandButton] : this.templateOptions[ButtonTemplateType.commandLink]; // if compound, return button | link case ButtonTypeEnum[ButtonTypeEnum.compound]: return angular.isUndefined($attrs.ngHref) ? this.templateOptions[ButtonTemplateType.compoundButton] : this.templateOptions[ButtonTemplateType.compoundLink]; // if hero, return button | link case ButtonTypeEnum[ButtonTypeEnum.hero]: return angular.isUndefined($attrs.ngHref) ? this.templateOptions[ButtonTemplateType.heroButton] : this.templateOptions[ButtonTemplateType.heroLink]; // else no type specified, so it's an action button default: return angular.isUndefined($attrs.ngHref) ? this.templateOptions[ButtonTemplateType.actionButton] : this.templateOptions[ButtonTemplateType.actionLink]; } } public compile( element: angular.IAugmentedJQuery, attrs: IButtonAttributes, transclude: angular.ITranscludeFunction): angular.IDirectivePrePost { return { post: this.postLink, pre: this.preLink }; } /** * Update the scope before linking everything up. */ private preLink( scope: IButtonScope, element: angular.IAugmentedJQuery, attrs: IButtonAttributes, controllers: any, transclude: angular.ITranscludeFunction): void { attrs.$observe('disabled', (isDisabled) => { scope.disabled = !!isDisabled; }); // if disabled prevent click action element.on('click', (e: Event) => { if (scope.disabled) { e.preventDefault(); } }); } /** * Check the rendered HTML for anything that is invalid. */ private postLink( scope: IButtonScope, element: angular.IAugmentedJQuery, attrs: IButtonAttributes, controllers: any, transclude: angular.ITranscludeFunction): void { // if an icon was added to the button's contents for specific button types // that don't support icons, remove the icon if (angular.isUndefined(attrs.uifType) || attrs.uifType === ButtonTypeEnum[ButtonTypeEnum.primary] || attrs.uifType === ButtonTypeEnum[ButtonTypeEnum.compound]) { let iconElement: JQuery = element.find('uif-icon'); if (iconElement.length !== 0) { iconElement.remove(); controllers.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.button - ' + 'Icon not allowed in primary or compound buttons: ' + 'The primary & compound button does not support including icons in the body. ' + 'The icon has been removed but may cause rendering errors. Consider buttons that support icons such as command or hero.'); } } // create necessary wrappers around inner content in button depending on button type transclude((clone: angular.IAugmentedJQuery) => { let wrapper: angular.IAugmentedJQuery; switch (attrs.uifType) { // if type === command case ButtonTypeEnum[ButtonTypeEnum.command]: for (let i: number = 0; i < clone.length; i++) { // wrap the button label if (this._isValidLabel(clone[i])) { wrapper = angular.element('<span></span>'); wrapper.addClass('ms-Button-label').append(clone[i]); element.append(wrapper); } // wrap the button's icon if (clone[i].tagName === 'UIF-ICON') { wrapper = angular.element('<span></span>'); wrapper.addClass('ms-Button-icon').append(clone[i]); element.append(wrapper); } } break; // if type === compound case ButtonTypeEnum[ButtonTypeEnum.compound]: for (let i: number = 0; i < clone.length; i++) { // icon is not supported on compound button if (clone[i].tagName === 'UIF-ICON') { continue; } // wrap the button label if (this._isValidLabel(clone[i])) { wrapper = angular.element('<span></span>'); wrapper.addClass('ms-Button-label').append(clone[i]); element.append(wrapper); // add the description... just add it to the button } else { element.append(clone[i]); } } break; // if type === hero case ButtonTypeEnum[ButtonTypeEnum.hero]: for (let i: number = 0; i < clone.length; i++) { // wrap the label if (this._isValidLabel(clone[i])) { wrapper = angular.element('<span></span>'); wrapper.addClass('ms-Button-label').append(clone[i]); element.append(wrapper); } // wrap the icon if (clone[i].tagName === 'UIF-ICON') { wrapper = angular.element('<span></span>'); wrapper.addClass('ms-Button-icon').append(clone[i]); element.append(wrapper); } } break; default: break; } }); } private _isValidLabel(clone: HTMLElement): boolean { return clone.nodeType === Node.TEXT_NODE && clone.nodeValue.trim().length > 0; } private _populateHtmlTemplates(): void { // regular / action button this.templateOptions[ButtonTemplateType.actionButton] = `<button class="ms-Button" ng-class="{\'is-disabled\': disabled}"> <span class="ms-Button-label" ng-transclude></span> </button>`; this.templateOptions[ButtonTemplateType.actionLink] = `<a class="ms-Button" ng-class="{\'is-disabled\': disabled}"> <span class="ms-Button-label" ng-transclude></span> </a>`; // primary button this.templateOptions[ButtonTemplateType.primaryButton] = `<button class="ms-Button ms-Button--primary" ng-class="{\'is-disabled\': disabled}"> <span class="ms-Button-label" ng-transclude></span> </button>`; this.templateOptions[ButtonTemplateType.primaryLink] = `<a class="ms-Button ms-Button--primary" ng-class="{\'is-disabled\': disabled}"> <span class="ms-Button-label" ng-transclude></span> </a>`; // command button this.templateOptions[ButtonTemplateType.commandButton] = `<button class="ms-Button ms-Button--command" ng-class="{\'is-disabled\': disabled}"></button>`; this.templateOptions[ButtonTemplateType.commandLink] = `<a class="ms-Button ms-Button--command" ng-class="{\'is-disabled\': disabled}"></a>`; // compound button this.templateOptions[ButtonTemplateType.compoundButton] = `<button class="ms-Button ms-Button--compound" ng-class="{\'is-disabled\': disabled}"></button>`; this.templateOptions[ButtonTemplateType.compoundLink] = `<a class="ms-Button ms-Button--compound" ng-class="{\'is-disabled\': disabled}"></a>`; // hero button this.templateOptions[ButtonTemplateType.heroButton] = `<button class="ms-Button ms-Button--hero" ng-class="{\'is-disabled\': disabled}"></button>`; this.templateOptions[ButtonTemplateType.heroLink] = `<a class="ms-Button ms-Button--hero" ng-class="{\'is-disabled\': disabled}"></a>`; } } /** * @ngdoc directive * @name uifDescriptionButton * @module officeuifabric.components.button * * @restrict E * * @description * `<uif-button-description>` is a button description directive. * * @see {link http://dev.office.com/fabric/components/button} * * @usage * * <uif-button-description>Lorem Ipsum</uif-button-description> */ export class ButtonDescriptionDirective implements angular.IDirective { public restrict: string = 'E'; public require: string = '^uifButton'; public transclude: boolean = true; public replace: boolean = true; public scope: boolean = false; public template: string = '<span class="ms-Button-description" ng-transclude></span>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new ButtonDescriptionDirective(); return directive; } } /** * @ngdoc module * @name officeuifabric.components.button * * @description * Button * */ export let module: angular.IModule = angular.module('officeuifabric.components.button', [ 'officeuifabric.components' ]) .directive('uifButton', ButtonDirective.factory()) .directive('uifButtonDescription', ButtonDescriptionDirective.factory());
the_stack
import { triggerEvent, options } from '@tko/utils' import { applyBindings, contextFor } from '@tko/bind' import { observable, observableArray } from '@tko/observable' import { DataBindProvider } from '@tko/provider.databind' import { VirtualProvider } from '@tko/provider.virtual' import { MultiProvider } from '@tko/provider.multi' import {bindings as templateBindings} from '@tko/binding.template' import {bindings as coreBindings} from '@tko/binding.core' import '@tko/utils/helpers/jasmine-13-helper' describe('Binding: Using', function () { beforeEach(jasmine.prepareTestNode) beforeEach(function () { var provider = new MultiProvider({ providers: [ new DataBindProvider(), new VirtualProvider() ] }) options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) provider.bindingHandlers.set(templateBindings) }) it('Should leave descendant nodes in the document (and bind them in the context of the supplied value) if the value is truthy', function () { testNode.innerHTML = "<div data-bind='using: someItem'><span data-bind='text: existentChildProp'></span></div>" expect(testNode.childNodes.length).toEqual(1) applyBindings({ someItem: { existentChildProp: 'Child prop value' } }, testNode) expect(testNode.childNodes[0].childNodes.length).toEqual(1) expect(testNode.childNodes[0].childNodes[0]).toContainText('Child prop value') }) it('Should leave descendant nodes in the document (and bind them) if the value is falsy', function () { testNode.innerHTML = "<div data-bind='using: someItem'><span data-bind='text: $data'></span></div>" applyBindings({ someItem: null }, testNode) expect(testNode.childNodes[0].childNodes.length).toEqual(1) expect(testNode.childNodes[0].childNodes[0]).toContainText('') }) it('Should leave descendant nodes unchanged and not bind them more than once if the supplied value notifies a change', function () { var countedClicks = 0 var someItem = observable({ childProp: observable('Hello'), handleClick: function () { countedClicks++ } }) testNode.innerHTML = "<div data-bind='using: someItem'><span data-bind='text: childProp, click: handleClick'></span></div>" var originalNode = testNode.childNodes[0].childNodes[0] applyBindings({ someItem: someItem }, testNode) expect(testNode.childNodes[0].childNodes[0]).toEqual(originalNode) // Initial state is one subscriber, one click handler expect(testNode.childNodes[0].childNodes[0]).toContainText('Hello') expect(someItem().childProp.getSubscriptionsCount()).toEqual(1) triggerEvent(testNode.childNodes[0].childNodes[0], 'click') expect(countedClicks).toEqual(1) // Force "update" binding handler to fire, then check we still have one subscriber... someItem.valueHasMutated() expect(someItem().childProp.getSubscriptionsCount()).toEqual(1) // ... and one click handler countedClicks = 0 triggerEvent(testNode.childNodes[0].childNodes[0], 'click') expect(countedClicks).toEqual(1) // and the node is still the same expect(testNode.childNodes[0].childNodes[0]).toEqual(originalNode) }) it('Should be able to access parent binding context via $parent', function () { testNode.innerHTML = "<div data-bind='using: someItem'><span data-bind='text: $parent.parentProp'></span></div>" applyBindings({ someItem: { }, parentProp: 'Parent prop value' }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('Parent prop value') }) it('Should be able to access all parent binding contexts via $parents, and root context via $root', function () { testNode.innerHTML = "<div data-bind='using: topItem'>" + "<div data-bind='using: middleItem'>" + "<div data-bind='using: bottomItem'>" + "<span data-bind='text: name'></span>" + "<span data-bind='text: $parent.name'></span>" + "<span data-bind='text: $parents[1].name'></span>" + "<span data-bind='text: $parents[2].name'></span>" + "<span data-bind='text: $root.name'></span>" + '</div>' + '</div>' + '</div>' applyBindings({ name: 'outer', topItem: { name: 'top', middleItem: { name: 'middle', bottomItem: { name: 'bottom' } } } }, testNode) var finalContainer = testNode.childNodes[0].childNodes[0].childNodes[0] expect(finalContainer.childNodes[0]).toContainText('bottom') expect(finalContainer.childNodes[1]).toContainText('middle') expect(finalContainer.childNodes[2]).toContainText('top') expect(finalContainer.childNodes[3]).toContainText('outer') expect(finalContainer.childNodes[4]).toContainText('outer') // Also check that, when we later retrieve the binding contexts, we get consistent results expect(contextFor(testNode).$data.name).toEqual('outer') expect(contextFor(testNode.childNodes[0]).$data.name).toEqual('outer') expect(contextFor(testNode.childNodes[0].childNodes[0]).$data.name).toEqual('top') expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0]).$data.name).toEqual('middle') expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0].childNodes[0]).$data.name).toEqual('bottom') var firstSpan = testNode.childNodes[0].childNodes[0].childNodes[0].childNodes[0] expect(firstSpan.tagName).toEqual('SPAN') expect(contextFor(firstSpan).$data.name).toEqual('bottom') expect(contextFor(firstSpan).$root.name).toEqual('outer') expect(contextFor(firstSpan).$parents[1].name).toEqual('top') }) it('Should be able to define a \"using\" region using a containerless binding', function () { var someitem = observable({someItem: 'first value'}) testNode.innerHTML = 'xxx <!-- ko using: someitem --><span data-bind="text: someItem"></span><!-- /ko -->' applyBindings({ someitem: someitem }, testNode) expect(testNode).toContainText('xxx first value') someitem({ someItem: 'second value' }) expect(testNode).toContainText('xxx second value') }) it('Should be able to use \"using\" within an observable top-level view model', function () { var vm = observable({someitem: observable({someItem: 'first value'})}) testNode.innerHTML = 'xxx <!-- ko using: someitem --><span data-bind="text: someItem"></span><!-- /ko -->' applyBindings(vm, testNode) expect(testNode).toContainText('xxx first value') vm({someitem: observable({ someItem: 'second value' })}) expect(testNode).toContainText('xxx second value') }) it('Should be able to nest a template within \"using\"', function () { testNode.innerHTML = "<div data-bind='using: someitem'>" + "<div data-bind='foreach: childprop'><span data-bind='text: $data'></span></div></div>" var childprop = observableArray([]) var someitem = observable({childprop: childprop}) var viewModel = {someitem: someitem} applyBindings(viewModel, testNode) // First it's not there (by template) var container = testNode.childNodes[0] expect(container).toContainHtml('<div data-bind="foreach: childprop"></div>') // Then it's there childprop.push('me') expect(container).toContainHtml('<div data-bind="foreach: childprop"><span data-bind=\"text: $data\">me</span></div>') // Then there's a second one childprop.push('me2') expect(container).toContainHtml('<div data-bind="foreach: childprop"><span data-bind=\"text: $data\">me</span><span data-bind=\"text: $data\">me2</span></div>') // Then it changes someitem({childprop: ['notme']}) expect(container).toContainHtml('<div data-bind="foreach: childprop"><span data-bind=\"text: $data\">notme</span></div>') }) it('Should be able to nest a containerless template within \"using\"', function () { testNode.innerHTML = "<div data-bind='using: someitem'>text" + "<!-- ko foreach: childprop --><span data-bind='text: $data'></span><!-- /ko --></div>" var childprop = observableArray([]) var someitem = observable({childprop: childprop}) var viewModel = {someitem: someitem} applyBindings(viewModel, testNode) // First it's not there (by template) var container = testNode.childNodes[0] expect(container).toContainHtml('text<!-- ko foreach: childprop --><!-- /ko -->') // Then it's there childprop.push('me') expect(container).toContainHtml('text<!-- ko foreach: childprop --><span data-bind="text: $data">me</span><!-- /ko -->') // Then there's a second one childprop.push('me2') expect(container).toContainHtml('text<!-- ko foreach: childprop --><span data-bind="text: $data">me</span><span data-bind="text: $data">me2</span><!-- /ko -->') // Then it changes someitem({childprop: ['notme']}) container = testNode.childNodes[0] expect(container).toContainHtml('text<!-- ko foreach: childprop --><span data-bind="text: $data">notme</span><!-- /ko -->') }) it('Should provide access to an observable viewModel through $rawData', function () { testNode.innerHTML = "<div data-bind='using: item'><input data-bind='value: $rawData'/></div>" var item = observable('one') applyBindings({ item: item }, testNode) expect(item.getSubscriptionsCount('change')).toEqual(2) // only subscriptions are the using and value bindings expect(testNode.childNodes[0]).toHaveValues(['one']) // Should update observable when input is changed testNode.childNodes[0].childNodes[0].value = 'two' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(item()).toEqual('two') // Should update the input when the observable changes item('three') expect(testNode.childNodes[0]).toHaveValues(['three']) }) })
the_stack
import * as cdk from '@aws-cdk/core'; import * as dynamodb from '@aws-cdk/aws-dynamodb'; import * as lambda from '@aws-cdk/aws-lambda'; import * as kms from '@aws-cdk/aws-kms'; import * as iam from '@aws-cdk/aws-iam'; import * as sns from '@aws-cdk/aws-sns'; import * as logs from '@aws-cdk/aws-logs'; import * as cw from '@aws-cdk/aws-cloudwatch'; import * as cw_actions from '@aws-cdk/aws-cloudwatch-actions'; import * as path from 'path'; export interface BLEALambdaPythonStackProps extends cdk.StackProps { alarmTopic: sns.Topic; table: dynamodb.Table; appKey: kms.Key; } export class BLEALambdaPythonStack extends cdk.Stack { public readonly getItemFunction: lambda.Function; public readonly listItemsFunction: lambda.Function; public readonly putItemFunction: lambda.Function; constructor(scope: cdk.Construct, id: string, props: BLEALambdaPythonStackProps) { super(scope, id, props); // Custom Policy for App Key props.appKey.addToResourcePolicy( new iam.PolicyStatement({ actions: ['kms:*'], principals: [new iam.AccountRootPrincipal()], resources: ['*'], }), ); props.appKey.addToResourcePolicy( new iam.PolicyStatement({ actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'], principals: [ new iam.AnyPrincipal().withConditions({ ArnLike: { 'aws:PrincipalArn': `arn:aws:iam::${cdk.Stack.of(this).account}:role/BLEA-LambdaPython-*`, }, }), ], resources: ['*'], }), ); // Policy operating KMS CMK for Lambda const kmsPolicy = new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'], resources: [props.appKey.keyArn], }); // Using Lambda Python Library // // !!!! CAUTION !!!! // Lambda Python Library is experimental. This implementation might be changed. // See: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-python-readme.html // // Lambda layer for Lambda Powertools // For install instruction, See: https://awslabs.github.io/aws-lambda-powertools-python/latest/#install const lambdaPowertools = lambda.LayerVersion.fromLayerVersionArn( this, 'lambda-powertools', `arn:aws:lambda:${cdk.Stack.of(this).region}:017000801446:layer:AWSLambdaPowertoolsPython:3`, ); // GetItem Function const getItemFunction = new lambda.Function(this, 'getItem', { runtime: lambda.Runtime.PYTHON_3_7, code: lambda.Code.fromAsset(path.join(__dirname, '../lambda/python/getItem')), handler: 'getItem.lambda_handler', memorySize: 256, timeout: cdk.Duration.seconds(25), tracing: lambda.Tracing.ACTIVE, insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0, layers: [lambdaPowertools], environment: { DDB_TABLE: props.table.tableName, }, environmentEncryption: props.appKey, logRetention: logs.RetentionDays.THREE_MONTHS, }); getItemFunction.addToRolePolicy(kmsPolicy); getItemFunction.addToRolePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['dynamodb:Query', 'dynamodb:GetItem'], resources: [props.table.tableArn, props.table.tableArn + '/index/*'], }), ); this.getItemFunction = getItemFunction; // Sample metrics and alarm // See: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/best-practices.html getItemFunction .metricErrors({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'getItemErrorsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); getItemFunction .metricDuration({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'getItemDurationAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); new cw.Metric({ namespace: 'AWS/Lambda', metricName: 'ConcurrentExecutions', period: cdk.Duration.minutes(5), statistic: cw.Statistic.MAXIMUM, dimensionsMap: { FunctionName: getItemFunction.functionName, }, }) .createAlarm(this, 'getItemConcurrentExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); getItemFunction .metricThrottles({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'getItemThrottlesAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // ListItem Function const listItemsFunction = new lambda.Function(this, 'listItems', { runtime: lambda.Runtime.PYTHON_3_7, code: lambda.Code.fromAsset(path.join(__dirname, '../lambda/python/listItems')), handler: 'listItems.lambda_handler', timeout: cdk.Duration.seconds(25), memorySize: 2048, tracing: lambda.Tracing.ACTIVE, insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0, layers: [lambdaPowertools], environment: { DDB_TABLE: props.table.tableName, }, environmentEncryption: props.appKey, logRetention: logs.RetentionDays.THREE_MONTHS, }); listItemsFunction.addToRolePolicy(kmsPolicy); listItemsFunction.addToRolePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['dynamodb:Query', 'dynamodb:Scan'], resources: [props.table.tableArn, props.table.tableArn + '/index/*'], }), ); this.listItemsFunction = listItemsFunction; // Sample metrics and alarm // See: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/best-practices.html listItemsFunction .metricErrors({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'listItemsErrorsExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); listItemsFunction .metricDuration({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'listItemsDurationAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); new cw.Metric({ namespace: 'AWS/Lambda', metricName: 'ConcurrentExecutions', period: cdk.Duration.minutes(5), statistic: cw.Statistic.MAXIMUM, dimensionsMap: { FunctionName: listItemsFunction.functionName, }, }) .createAlarm(this, 'listItemsConcurrentExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); listItemsFunction .metricThrottles({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'listItemsThrottlesAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // PutItem Function const putItemFunction = new lambda.Function(this, 'putItem', { runtime: lambda.Runtime.PYTHON_3_7, code: lambda.Code.fromAsset(path.join(__dirname, '../lambda/python/putItem')), handler: 'putItem.lambda_handler', timeout: cdk.Duration.seconds(25), memorySize: 256, tracing: lambda.Tracing.ACTIVE, insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0, layers: [lambdaPowertools], environment: { DDB_TABLE: props.table.tableName, }, environmentEncryption: props.appKey, logRetention: logs.RetentionDays.THREE_MONTHS, }); putItemFunction.addToRolePolicy(kmsPolicy); putItemFunction.addToRolePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['dynamodb:PutItem'], resources: [props.table.tableArn, props.table.tableArn + '/index/*'], }), ); this.putItemFunction = putItemFunction; // Sample metrics and alarm // See: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/best-practices.html putItemFunction .metricErrors({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'putItemErrorsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); putItemFunction .metricDuration({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'putItemDurationAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); new cw.Metric({ namespace: 'AWS/Lambda', metricName: 'ConcurrentExecutions', period: cdk.Duration.minutes(5), statistic: cw.Statistic.MAXIMUM, dimensionsMap: { FunctionName: putItemFunction.functionName, }, }) .createAlarm(this, 'putItemConcurrentExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); putItemFunction .metricThrottles({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'putItemThrottlesAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); } }
the_stack
import { ready as cryptoReady, tcrypto, random, utils } from '@tanker/crypto'; import { expect } from '@tanker/test-utils'; import { encodeListLength } from '../../Blocks/Serialize'; import { serializeUserDeviceV3, unserializeUserDeviceV1, unserializeUserDeviceV2, unserializeUserDeviceV3, serializeDeviceRevocationV2, unserializeDeviceRevocationV1, unserializeDeviceRevocationV2, } from '../Serialize'; import type { DeviceCreationRecord, } from '../Serialize'; import makeUint8Array from '../../__tests__/makeUint8Array'; // NOTE: If you ever have to change something here, change it in the Go code too! // The test vectors should stay the same describe('user serialization: payload test vectors', () => { before(() => cryptoReady); it('correctly deserializes a DeviceCreation v1 test vector', async () => { const deviceCreation = { ephemeral_public_signature_key: new Uint8Array([ 0x4e, 0x2a, 0x65, 0xdf, 0xe6, 0x5d, 0x00, 0x58, 0xf4, 0xdf, 0xb0, 0x5d, 0x37, 0x64, 0x18, 0x1d, 0x10, 0x61, 0xf7, 0x54, 0xbb, 0x70, 0x30, 0x4f, 0x08, 0x6e, 0x32, 0x14, 0x85, 0x7a, 0xee, 0xe5, ]), user_id: new Uint8Array([ 0xbd, 0xec, 0xe7, 0xbe, 0x4c, 0xd6, 0xc8, 0x33, 0xec, 0xf9, 0x42, 0xe1, 0xa9, 0xc4, 0xa7, 0x3e, 0x39, 0xac, 0xdd, 0x6d, 0x99, 0x37, 0xc2, 0x9a, 0xbf, 0xf8, 0x6c, 0x4f, 0xce, 0x3a, 0x34, 0xcd, ]), delegation_signature: new Uint8Array([ 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, ]), public_signature_key: new Uint8Array([ 0x21, 0x2c, 0x54, 0x3a, 0xae, 0xcf, 0xc6, 0xef, 0x0b, 0x60, 0xae, 0xe6, 0x11, 0x52, 0xa1, 0x30, 0x60, 0xbc, 0x34, 0xbc, 0x1b, 0x89, 0x39, 0xe1, 0xd9, 0x94, 0x9a, 0xaa, 0x14, 0x4c, 0x41, 0x60, ]), public_encryption_key: new Uint8Array([ 0x42, 0x9a, 0xfa, 0x09, 0xee, 0xea, 0xce, 0x12, 0xec, 0x59, 0x06, 0x35, 0xa8, 0x7f, 0x82, 0xe6, 0x39, 0xc8, 0xce, 0xd0, 0xc8, 0xe5, 0x57, 0x16, 0x72, 0x94, 0x9e, 0xfb, 0xed, 0x59, 0xde, 0x2e, ]), user_key_pair: null, is_ghost_device: false, last_reset: new Uint8Array(tcrypto.HASH_SIZE), revoked: Number.MAX_SAFE_INTEGER, }; const payload = utils.concatArrays( deviceCreation.ephemeral_public_signature_key, deviceCreation.user_id, deviceCreation.delegation_signature, deviceCreation.public_signature_key, deviceCreation.public_encryption_key, ); expect(unserializeUserDeviceV1(payload)).to.deep.equal(deviceCreation); }); it('correctly deserializes a DeviceCreation v2 test vector', async () => { const deviceCreation = { last_reset: new Uint8Array(tcrypto.HASH_SIZE), ephemeral_public_signature_key: new Uint8Array([ 0x4e, 0x2a, 0x65, 0xdf, 0xe6, 0x5d, 0x00, 0x58, 0xf4, 0xdf, 0xb0, 0x5d, 0x37, 0x64, 0x18, 0x1d, 0x10, 0x61, 0xf7, 0x54, 0xbb, 0x70, 0x30, 0x4f, 0x08, 0x6e, 0x32, 0x14, 0x85, 0x7a, 0xee, 0xe5, ]), user_id: new Uint8Array([ 0xbd, 0xec, 0xe7, 0xbe, 0x4c, 0xd6, 0xc8, 0x33, 0xec, 0xf9, 0x42, 0xe1, 0xa9, 0xc4, 0xa7, 0x3e, 0x39, 0xac, 0xdd, 0x6d, 0x99, 0x37, 0xc2, 0x9a, 0xbf, 0xf8, 0x6c, 0x4f, 0xce, 0x3a, 0x34, 0xcd, ]), delegation_signature: new Uint8Array([ 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, ]), public_signature_key: new Uint8Array([ 0x21, 0x2c, 0x54, 0x3a, 0xae, 0xcf, 0xc6, 0xef, 0x0b, 0x60, 0xae, 0xe6, 0x11, 0x52, 0xa1, 0x30, 0x60, 0xbc, 0x34, 0xbc, 0x1b, 0x89, 0x39, 0xe1, 0xd9, 0x94, 0x9a, 0xaa, 0x14, 0x4c, 0x41, 0x60, ]), public_encryption_key: new Uint8Array([ 0x42, 0x9a, 0xfa, 0x09, 0xee, 0xea, 0xce, 0x12, 0xec, 0x59, 0x06, 0x35, 0xa8, 0x7f, 0x82, 0xe6, 0x39, 0xc8, 0xce, 0xd0, 0xc8, 0xe5, 0x57, 0x16, 0x72, 0x94, 0x9e, 0xfb, 0xed, 0x59, 0xde, 0x2e, ]), user_key_pair: null, is_ghost_device: false, revoked: Number.MAX_SAFE_INTEGER, }; const payload = utils.concatArrays( deviceCreation.last_reset, deviceCreation.ephemeral_public_signature_key, deviceCreation.user_id, deviceCreation.delegation_signature, deviceCreation.public_signature_key, deviceCreation.public_encryption_key, ); expect(unserializeUserDeviceV2(payload)).to.deep.equal(deviceCreation); }); it('correctly deserializes a DeviceCreation v3 test vector', async () => { const payload = new Uint8Array([ // ephemeral_public_signature_key 0x65, 0x70, 0x68, 0x20, 0x70, 0x75, 0x62, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // user_id 0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // delegation_signature 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x73, 0x69, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // public_signature_key 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // public_encryption_key 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // user public_encryption_key 0x75, 0x73, 0x65, 0x72, 0x20, 0x70, 0x75, 0x62, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // user encrypted_private_encryption_key 0x75, 0x73, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // is_ghost_device 0x01, ]); const deviceCreation = { last_reset: new Uint8Array(32), ephemeral_public_signature_key: makeUint8Array('eph pub key', tcrypto.SIGNATURE_PUBLIC_KEY_SIZE), user_id: makeUint8Array('user id', tcrypto.HASH_SIZE), delegation_signature: makeUint8Array('delegation sig', tcrypto.SIGNATURE_SIZE), public_signature_key: makeUint8Array('public signature key', tcrypto.SIGNATURE_PUBLIC_KEY_SIZE), public_encryption_key: makeUint8Array('public enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), user_key_pair: { public_encryption_key: makeUint8Array('user pub enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), encrypted_private_encryption_key: makeUint8Array('user enc key', tcrypto.SEALED_KEY_SIZE), }, is_ghost_device: true, revoked: Number.MAX_SAFE_INTEGER, }; expect(unserializeUserDeviceV3(payload)).to.deep.equal(deviceCreation); }); it('correctly deserializes a DeviceRevocationV1 test vector', async () => { const deviceRevocation = { device_id: new Uint8Array([ 0xe9, 0x0b, 0x0a, 0x13, 0x05, 0xb1, 0x82, 0x85, 0xab, 0x9d, 0xbe, 0x3f, 0xdb, 0x57, 0x2b, 0x71, 0x6c, 0x0d, 0xa1, 0xa3, 0xad, 0xb8, 0x86, 0x9b, 0x39, 0x58, 0xcb, 0x00, 0xfa, 0x31, 0x5d, 0x87, ]), }; const payload = deviceRevocation.device_id; expect(unserializeDeviceRevocationV1(payload)).to.deep.equal(deviceRevocation); }); it('correctly deserializes a DeviceRevocationV2 test vector', async () => { const deviceRevocation = { device_id: new Uint8Array([ 0xe9, 0x0b, 0x0a, 0x13, 0x05, 0xb1, 0x82, 0x85, 0xab, 0x9d, 0xbe, 0x3f, 0xdb, 0x57, 0x2b, 0x71, 0x6c, 0x0d, 0xa1, 0xa3, 0xad, 0xb8, 0x86, 0x9b, 0x39, 0x58, 0xcb, 0x00, 0xfa, 0x31, 0x5d, 0x87, ]), user_keys: { public_encryption_key: new Uint8Array([ 0x42, 0x9a, 0xfa, 0x09, 0xee, 0xea, 0xce, 0x12, 0xec, 0x59, 0x06, 0x35, 0xa8, 0x7f, 0x82, 0xe6, 0x39, 0xc8, 0xce, 0xd0, 0xc8, 0xe5, 0x57, 0x16, 0x72, 0x94, 0x9e, 0xfb, 0xed, 0x59, 0xde, 0x2e, ]), previous_public_encryption_key: new Uint8Array([ 0x8e, 0x3e, 0x33, 0x57, 0x3d, 0xd5, 0x3c, 0xe7, 0x29, 0xbc, 0x73, 0x90, 0x7f, 0x83, 0x20, 0xee, 0xe9, 0x0b, 0x0a, 0x13, 0x05, 0xb1, 0x82, 0x85, 0xab, 0x9d, 0xbe, 0x3f, 0xdb, 0x57, 0x2b, 0x71, ]), encrypted_previous_encryption_key: new Uint8Array([ 0xf1, 0x28, 0xa8, 0x12, 0x03, 0x8e, 0x7c, 0x9c, 0x39, 0xad, 0x73, 0x21, 0xa3, 0xee, 0x50, 0x53, 0xc1, 0x1d, 0xda, 0x76, 0xaf, 0xc8, 0xfd, 0x70, 0x74, 0x5c, 0xbb, 0xd6, 0xb8, 0x7f, 0x8f, 0x6b, 0xe1, 0xaf, 0x36, 0x80, 0x3f, 0xf3, 0xbc, 0xb2, 0xfb, 0x4e, 0xe1, 0x7d, 0xea, 0xbd, 0x19, 0x6b, 0x8e, 0x3e, 0x33, 0x57, 0x3d, 0xd5, 0x3c, 0xe7, 0x29, 0xbc, 0x73, 0x90, 0x7f, 0x83, 0x20, 0xee, 0x0e, 0xc0, 0x91, 0x63, 0xe7, 0xc2, 0x04, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]), private_keys: [{ recipient: new Uint8Array([ 0xd0, 0xa8, 0x9e, 0xff, 0x7d, 0x59, 0x48, 0x3a, 0xee, 0x7c, 0xe4, 0x99, 0x49, 0x4d, 0x1c, 0xd7, 0x87, 0x54, 0x41, 0xf5, 0xba, 0x51, 0xd7, 0x65, 0xbf, 0x91, 0x45, 0x08, 0x03, 0xf1, 0xe9, 0xc7, ]), key: new Uint8Array([ 0xe1, 0xaf, 0x36, 0x80, 0x3f, 0xf3, 0xbc, 0xb2, 0xfb, 0x4e, 0xe1, 0x7d, 0xea, 0xbd, 0x19, 0x6b, 0x8e, 0x3e, 0x33, 0x57, 0x3d, 0xd5, 0x3c, 0xe7, 0x29, 0xbc, 0x73, 0x90, 0x7f, 0x83, 0x20, 0xee, 0xf1, 0x28, 0xa8, 0x12, 0x03, 0x8e, 0x7c, 0x9c, 0x39, 0xad, 0x73, 0x21, 0xa3, 0xee, 0x50, 0x53, 0xc1, 0x1d, 0xda, 0x76, 0xaf, 0xc8, 0xfd, 0x70, 0x74, 0x5c, 0xbb, 0xd6, 0xb8, 0x7f, 0x8f, 0x6b, 0x0e, 0xc0, 0x91, 0x63, 0xe7, 0xc2, 0x04, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]), }], }, }; const payload = utils.concatArrays( deviceRevocation.device_id, deviceRevocation.user_keys.public_encryption_key, deviceRevocation.user_keys.previous_public_encryption_key, deviceRevocation.user_keys.encrypted_previous_encryption_key, encodeListLength(deviceRevocation.user_keys.private_keys), ...deviceRevocation.user_keys.private_keys.map(userKey => utils.concatArrays(userKey.recipient, userKey.key)), ); expect(unserializeDeviceRevocationV2(payload)).to.deep.equal(deviceRevocation); }); }); describe('user serialization: payloads', () => { it('should serialize/unserialize a UserDeviceV3', async () => { const ephemeralKeys = tcrypto.makeSignKeyPair(); const signatureKeys = tcrypto.makeSignKeyPair(); const encryptionKeys = tcrypto.makeEncryptionKeyPair(); const userDevice = { last_reset: new Uint8Array(tcrypto.HASH_SIZE), ephemeral_public_signature_key: ephemeralKeys.publicKey, user_id: utils.fromString('12341234123412341234123412341234'), delegation_signature: utils.fromString('1234123412341234123412341234123412341234123412341234123412341234'), public_signature_key: signatureKeys.publicKey, public_encryption_key: encryptionKeys.publicKey, user_key_pair: { public_encryption_key: makeUint8Array('user pub enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), encrypted_private_encryption_key: makeUint8Array('user enc priv key', tcrypto.SEALED_KEY_SIZE), }, is_ghost_device: true, revoked: Number.MAX_SAFE_INTEGER, }; expect(unserializeUserDeviceV3(serializeUserDeviceV3(userDevice))).to.deep.equal(userDevice); }); it('should serialize/unserialize a DeviceRevocation', async () => { const deviceRevocation = { device_id: random(tcrypto.HASH_SIZE), user_keys: { public_encryption_key: random(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), previous_public_encryption_key: random(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), encrypted_previous_encryption_key: random(tcrypto.SEALED_KEY_SIZE), private_keys: [], }, }; expect(unserializeDeviceRevocationV2(serializeDeviceRevocationV2(deviceRevocation))).to.deep.equal(deviceRevocation); }); it('should throw when serializing invalid revocation blocks', async () => { const initValidBlock: any = () => ({ device_id: new Uint8Array(tcrypto.HASH_SIZE), user_keys: { public_encryption_key: new Uint8Array(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), previous_public_encryption_key: new Uint8Array(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), encrypted_previous_encryption_key: new Uint8Array(tcrypto.SEALED_KEY_SIZE), private_keys: [{ recipient: new Uint8Array(tcrypto.HASH_SIZE), key: new Uint8Array(tcrypto.SEALED_KEY_SIZE), }], }, }); let invalidBlock = initValidBlock(); invalidBlock.device_id = new Uint8Array(0); expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); invalidBlock = initValidBlock(); invalidBlock.user_keys = {}; expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); invalidBlock = initValidBlock(); invalidBlock.user_keys.public_encryption_key = new Uint8Array(0); expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); invalidBlock = initValidBlock(); invalidBlock.user_keys.previous_public_encryption_key = new Uint8Array(0); expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); invalidBlock = initValidBlock(); invalidBlock.user_keys.encrypted_previous_encryption_key = new Uint8Array(0); expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); invalidBlock = initValidBlock(); invalidBlock.user_keys.private_keys[0].recipient = new Uint8Array(0); expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); invalidBlock = initValidBlock(); invalidBlock.user_keys.private_keys[0].key = new Uint8Array(0); expect(() => serializeDeviceRevocationV2(invalidBlock)).to.throw(); }); it('should throw if the last reset is not null when serializing a new userDeviceV3', async () => { const ephemeralKeys = tcrypto.makeSignKeyPair(); const signatureKeys = tcrypto.makeSignKeyPair(); const encryptionKeys = tcrypto.makeEncryptionKeyPair(); const userDevice = { last_reset: new Uint8Array(Array.from({ length: tcrypto.HASH_SIZE, }, () => 1)), ephemeral_public_signature_key: ephemeralKeys.publicKey, user_id: utils.fromString('12341234123412341234123412341234'), delegation_signature: utils.fromString('1234123412341234123412341234123412341234123412341234123412341234'), public_signature_key: signatureKeys.publicKey, public_encryption_key: encryptionKeys.publicKey, user_key_pair: { public_encryption_key: makeUint8Array('user pub enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), encrypted_private_encryption_key: makeUint8Array('user enc priv key', tcrypto.SEALED_KEY_SIZE), }, is_ghost_device: true, revoked: Number.MAX_SAFE_INTEGER, }; expect(() => serializeUserDeviceV3(userDevice)).to.throw(); }); describe('serialization of invalid user device', () => { let userDevice: DeviceCreationRecord; beforeEach(() => { userDevice = { last_reset: new Uint8Array(tcrypto.HASH_SIZE), ephemeral_public_signature_key: new Uint8Array(tcrypto.SIGNATURE_PUBLIC_KEY_SIZE), user_id: new Uint8Array(tcrypto.HASH_SIZE), delegation_signature: new Uint8Array(tcrypto.SIGNATURE_SIZE), public_signature_key: new Uint8Array(tcrypto.SIGNATURE_PUBLIC_KEY_SIZE), public_encryption_key: new Uint8Array(tcrypto.SIGNATURE_PUBLIC_KEY_SIZE), user_key_pair: { public_encryption_key: new Uint8Array(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE), encrypted_private_encryption_key: new Uint8Array(tcrypto.SEALED_KEY_SIZE), }, is_ghost_device: true, revoked: Number.MAX_SAFE_INTEGER, }; }); const fields = [ 'ephemeral_public_signature_key', 'user_id', 'delegation_signature', 'public_signature_key', 'public_encryption_key', ]; fields.forEach(field => { it(`should throw if user device with invalid ${field}`, async () => { // @ts-expect-error fields only contains Uint8Array fields from DeviceCreationRecord userDevice[field] = new Uint8Array(0); expect(() => serializeUserDeviceV3(userDevice)).to.throw(); }); }); it('should throw if user device with invalid encrypted_private_encryption_key', async () => { userDevice.user_key_pair.encrypted_private_encryption_key = new Uint8Array(0); expect(() => serializeUserDeviceV3(userDevice)).to.throw(); }); it('should throw if user device with invalid public_encryption_key', () => { userDevice.user_key_pair.public_encryption_key = new Uint8Array(0); expect(() => serializeUserDeviceV3(userDevice)).to.throw(); }); }); });
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import * as THREE from 'three'; import memoizeOne from 'memoize-one'; import {buildEuler, buildVector3, getTextureCornerColour, reverseEuler} from '../util/threeUtils'; import HighlightShaderMaterial from '../shaders/highlightShaderMaterial'; import UprightMiniShaderMaterial from '../shaders/uprightMiniShaderMaterial'; import TopDownMiniShaderMaterial from '../shaders/topDownMiniShaderMaterial'; import {DriveMetadata, GridType, MiniProperties} from '../util/googleDriveUtils'; import { DistanceMode, DistanceRound, generateMovementPath, getColourHex, getColourHexString, MapType, MovementPathPoint, ObjectEuler, ObjectVector3, PiecesRosterColumn, PiecesRosterValues } from '../util/scenarioUtils'; import RosterColumnValuesLabel from './rosterColumnValuesLabel'; import TabletopPathComponent, {TabletopPathPoint} from './tabletopPathComponent'; interface TabletopMiniComponentProps { miniId: string; label: string; labelSize: number; metadata: DriveMetadata<void, MiniProperties>; positionObj: ObjectVector3; rotationObj: ObjectEuler; scaleFactor: number; elevation: number; movementPath?: MovementPathPoint[]; distanceMode: DistanceMode; distanceRound: DistanceRound; gridScale?: number; gridUnit?: string; roundToGrid: boolean; texture: THREE.Texture | null; highlight: THREE.Color | null; opacity: number; prone: boolean; topDown: boolean; hideBase: boolean; baseColour?: number; cameraInverseQuat?: THREE.Quaternion; defaultGridType: GridType; maps: {[mapId: string]: MapType}; piecesRosterColumns: PiecesRosterColumn[]; piecesRosterValues: PiecesRosterValues; } interface TabletopMiniComponentState { labelWidth?: number; movedSuffix: string; } export default class TabletopMiniComponent extends React.Component<TabletopMiniComponentProps, TabletopMiniComponentState> { static ORIGIN = new THREE.Vector3(); static NO_ROTATION = new THREE.Euler(); static UP = new THREE.Vector3(0, 1, 0); static DOWN = new THREE.Vector3(0, -1, 0); static MINI_THICKNESS = 0.05; static MINI_WIDTH = 1; static MINI_HEIGHT = 1.2; static MINI_CORNER_RADIUS_PERCENT = 10; static MINI_ASPECT_RATIO = TabletopMiniComponent.MINI_WIDTH / TabletopMiniComponent.MINI_HEIGHT; static MINI_ADJUST = new THREE.Vector3(0, TabletopMiniComponent.MINI_THICKNESS, -TabletopMiniComponent.MINI_THICKNESS / 2); static RENDER_ORDER_ADJUST = 0.1; static HIGHLIGHT_STANDEE_ADJUST = new THREE.Vector3(0, 0, -TabletopMiniComponent.MINI_THICKNESS/4); static ROTATION_XZ = new THREE.Euler(0, Math.PI / 2, 0); static PRONE_ROTATION = new THREE.Euler(-Math.PI/2, 0, 0); static ARROW_SIZE = 0.1; static LABEL_UPRIGHT_POSITION = new THREE.Vector3(0, TabletopMiniComponent.MINI_HEIGHT, 0); static LABEL_TOP_DOWN_POSITION = new THREE.Vector3(0, 0.5, -0.5); static LABEL_PRONE_POSITION = new THREE.Vector3(0, 0.5, -TabletopMiniComponent.MINI_HEIGHT); static propTypes = { miniId: PropTypes.string.isRequired, label: PropTypes.string.isRequired, labelSize: PropTypes.number.isRequired, metadata: PropTypes.object.isRequired, positionObj: PropTypes.object.isRequired, rotationObj: PropTypes.object.isRequired, scaleFactor: PropTypes.number.isRequired, elevation: PropTypes.number.isRequired, movementPath: PropTypes.arrayOf(PropTypes.object), distanceMode: PropTypes.string.isRequired, distanceRound: PropTypes.string.isRequired, gridScale: PropTypes.number, gridUnit: PropTypes.string, roundToGrid: PropTypes.bool, texture: PropTypes.object, highlight: PropTypes.object, opacity: PropTypes.number.isRequired, prone: PropTypes.bool.isRequired, topDown: PropTypes.bool.isRequired, cameraInverseQuat: PropTypes.object }; private readonly generateMovementPath: (movementPath: MovementPathPoint[], maps: {[mapId: string]: MapType}, defaultGridType: GridType) => TabletopPathPoint[]; constructor(props: TabletopMiniComponentProps) { super(props); this.generateMovementPath = memoizeOne(generateMovementPath); this.getBackgroundColour = memoizeOne(this.getBackgroundColour.bind(this)); this.updateMovedSuffix = this.updateMovedSuffix.bind(this); this.state = { movedSuffix: '' }; } UNSAFE_componentWillReceiveProps(nextProps: Readonly<TabletopMiniComponentProps>): void { if (this.state.movedSuffix && !nextProps.movementPath) { this.updateMovedSuffix(''); } } private getBackgroundColour(texture: THREE.Texture | null, overrideColour?: string): THREE.Color { if (overrideColour) { return new THREE.Color(getColourHex(overrideColour)); } else { return getTextureCornerColour(texture); } } private renderLabel(miniScale: THREE.Vector3, rotation: THREE.Euler, renderOrder: number) { const position = this.props.prone ? TabletopMiniComponent.LABEL_PRONE_POSITION.clone() : this.props.topDown ? TabletopMiniComponent.LABEL_TOP_DOWN_POSITION.clone() : TabletopMiniComponent.LABEL_UPRIGHT_POSITION.clone(); if (this.props.topDown) { position.z -= this.props.labelSize / 2 / miniScale.z; if (!this.props.prone && this.props.cameraInverseQuat) { // Rotate the label so it's always above the mini. This involves cancelling out the mini's local rotation, // and also rotating by the camera's inverse rotation around the Y axis (supplied as a prop). position.applyEuler(reverseEuler(rotation)).applyQuaternion(this.props.cameraInverseQuat); } } else { position.y += this.props.labelSize / 2 / miniScale.y; } return ( <RosterColumnValuesLabel label={this.props.label + this.state.movedSuffix} maxWidth={800} labelSize={this.props.labelSize} position={position} inverseScale={miniScale} rotation={rotation} renderOrder={renderOrder + position.y + TabletopMiniComponent.RENDER_ORDER_ADJUST} piecesRosterColumns={this.props.piecesRosterColumns} piecesRosterValues={this.props.piecesRosterValues} /> ); } private renderElevationArrow(arrowDir: THREE.Vector3 | null, arrowLength: number) { return arrowDir ? ( <arrowHelper args={[arrowDir, TabletopMiniComponent.ORIGIN, arrowLength, undefined, TabletopMiniComponent.ARROW_SIZE, TabletopMiniComponent.ARROW_SIZE]}/> ) : null; } private renderMiniBaseCylinderGeometry() { return ( <cylinderGeometry attach='geometry' args={[0.5, 0.5, TabletopMiniComponent.MINI_THICKNESS, 32]}/> ); } private renderMiniBase(renderOrder: number, highlightScale?: THREE.Vector3) { const baseColour = getColourHexString(this.props.baseColour || 0); return this.props.hideBase ? null : ( <group userData={{miniId: this.props.miniId}}> <mesh key='miniBase' renderOrder={renderOrder + TabletopMiniComponent.RENDER_ORDER_ADJUST}> {this.renderMiniBaseCylinderGeometry()} <meshPhongMaterial attach='material' args={[{color: baseColour, transparent: this.props.opacity < 1.0, opacity: this.props.opacity}]} /> </mesh> { (!this.props.highlight) ? null : ( <mesh scale={highlightScale} renderOrder={renderOrder + TabletopMiniComponent.RENDER_ORDER_ADJUST}> {this.renderMiniBaseCylinderGeometry()} <HighlightShaderMaterial colour={this.props.highlight} intensityFactor={1} /> </mesh> ) } </group> ); } private updateMovedSuffix(movedSuffix: string) { this.setState({movedSuffix: movedSuffix ? ` (moved ${movedSuffix})` : ''}); } renderTopDownMini() { const position = buildVector3(this.props.positionObj); const rotation = buildEuler(this.props.rotationObj); // Make larger minis (slightly) thinner than smaller ones. const scale = new THREE.Vector3(this.props.scaleFactor, 1 + (0.05 / this.props.scaleFactor), this.props.scaleFactor); const highlightScale = (!this.props.highlight) ? undefined : ( new THREE.Vector3((this.props.scaleFactor + 2 * TabletopMiniComponent.MINI_THICKNESS) / this.props.scaleFactor, (2 + 2 * TabletopMiniComponent.MINI_THICKNESS) / this.props.scaleFactor, (this.props.scaleFactor + 2 * TabletopMiniComponent.MINI_THICKNESS) / this.props.scaleFactor) ); let offset = TabletopMiniComponent.MINI_ADJUST.clone(); const arrowDir = this.props.elevation > TabletopMiniComponent.ARROW_SIZE ? TabletopMiniComponent.UP : (this.props.elevation < -TabletopMiniComponent.MINI_HEIGHT - TabletopMiniComponent.ARROW_SIZE ? TabletopMiniComponent.DOWN : null); const arrowLength = (this.props.elevation > 0 ? this.props.elevation + TabletopMiniComponent.MINI_THICKNESS : (-this.props.elevation - TabletopMiniComponent.MINI_HEIGHT - TabletopMiniComponent.MINI_THICKNESS)); if (arrowDir) { offset.y += this.props.elevation; } const colour = this.getBackgroundColour(this.props.texture, this.props.metadata.properties.colour); return ( <group> <group position={position} rotation={rotation} scale={scale}> <group position={offset} userData={{miniId: this.props.miniId}}> {this.renderLabel(scale, rotation, position.y)} <mesh key='topDown' rotation={TabletopMiniComponent.ROTATION_XZ} renderOrder={position.y + offset.y + TabletopMiniComponent.RENDER_ORDER_ADJUST}> {this.renderMiniBaseCylinderGeometry()} <TopDownMiniShaderMaterial texture={this.props.texture} opacity={this.props.opacity} colour={colour} properties={this.props.metadata.properties} /> </mesh> { (!this.props.highlight) ? null : ( <mesh scale={highlightScale} renderOrder={position.y + offset.y + TabletopMiniComponent.RENDER_ORDER_ADJUST}> {this.renderMiniBaseCylinderGeometry()} <HighlightShaderMaterial colour={this.props.highlight} intensityFactor={1} /> </mesh> ) } </group> {this.renderElevationArrow(arrowDir, arrowLength)} {arrowDir ? this.renderMiniBase(position.y, highlightScale) : null} </group> { !this.props.movementPath ? null : ( <TabletopPathComponent miniId={this.props.miniId} positionObj={{...this.props.positionObj, y: this.props.positionObj.y + this.props.elevation}} movementPath={this.generateMovementPath(this.props.movementPath, this.props.maps, this.props.defaultGridType)} distanceMode={this.props.distanceMode} distanceRound={this.props.distanceRound} gridScale={this.props.gridScale} gridUnit={this.props.gridUnit} roundToGrid={this.props.roundToGrid} updateMovedSuffix={this.updateMovedSuffix} /> ) } </group> ); } renderStandeeMini() { const position = buildVector3(this.props.positionObj); const rotation = buildEuler(this.props.rotationObj); const scale = new THREE.Vector3(this.props.scaleFactor, this.props.scaleFactor, this.props.scaleFactor); const baseHighlightScale = (!this.props.highlight) ? undefined : ( new THREE.Vector3((this.props.scaleFactor + 2 * TabletopMiniComponent.MINI_THICKNESS) / this.props.scaleFactor, 1.2, (this.props.scaleFactor + 2 * TabletopMiniComponent.MINI_THICKNESS) / this.props.scaleFactor) ); const standeeHighlightScale = (!this.props.highlight) ? undefined : ( new THREE.Vector3((this.props.scaleFactor + 2 * TabletopMiniComponent.MINI_THICKNESS) / this.props.scaleFactor, (this.props.scaleFactor * TabletopMiniComponent.MINI_HEIGHT + 2 * TabletopMiniComponent.MINI_THICKNESS) / (this.props.scaleFactor * TabletopMiniComponent.MINI_HEIGHT), 1.1) ); let offset = TabletopMiniComponent.MINI_ADJUST.clone(); const arrowDir = this.props.elevation > TabletopMiniComponent.ARROW_SIZE ? TabletopMiniComponent.UP : (this.props.elevation < -TabletopMiniComponent.MINI_HEIGHT - TabletopMiniComponent.ARROW_SIZE ? TabletopMiniComponent.DOWN : null); const arrowLength = (this.props.elevation > 0 ? this.props.elevation + TabletopMiniComponent.MINI_THICKNESS : (-this.props.elevation - TabletopMiniComponent.MINI_HEIGHT - TabletopMiniComponent.MINI_THICKNESS)) / this.props.scaleFactor; if (arrowDir) { offset.y += this.props.elevation / this.props.scaleFactor; } const proneRotation = (this.props.prone) ? TabletopMiniComponent.PRONE_ROTATION : TabletopMiniComponent.NO_ROTATION; const colour = this.getBackgroundColour(this.props.texture, this.props.metadata.properties.colour); return ( <group> <group position={position} rotation={rotation} scale={scale} key={'group' + this.props.miniId}> <group position={offset} userData={{miniId: this.props.miniId}}> {this.renderLabel(scale, rotation, position.y)} <mesh rotation={proneRotation} renderOrder={position.y + offset.y + TabletopMiniComponent.RENDER_ORDER_ADJUST}> <MiniExtrusion/> <UprightMiniShaderMaterial texture={this.props.texture} opacity={this.props.opacity} colour={colour} properties={this.props.metadata.properties}/> </mesh> { (!this.props.highlight) ? null : ( <mesh rotation={proneRotation} position={TabletopMiniComponent.HIGHLIGHT_STANDEE_ADJUST} scale={standeeHighlightScale} renderOrder={position.y + offset.y + TabletopMiniComponent.RENDER_ORDER_ADJUST} > <MiniExtrusion/> <HighlightShaderMaterial colour={this.props.highlight} intensityFactor={1} /> </mesh> ) } </group> {this.renderElevationArrow(arrowDir, arrowLength)} {this.renderMiniBase(position.y, baseHighlightScale)} </group> { !this.props.movementPath ? null : ( <TabletopPathComponent miniId={this.props.miniId} positionObj={{...this.props.positionObj, y: this.props.positionObj.y + this.props.elevation}} movementPath={this.generateMovementPath(this.props.movementPath, this.props.maps, this.props.defaultGridType)} distanceMode={this.props.distanceMode} distanceRound={this.props.distanceRound} gridScale={this.props.gridScale} gridUnit={this.props.gridUnit} roundToGrid={this.props.roundToGrid} updateMovedSuffix={this.updateMovedSuffix} /> ) } </group> ); } render() { return (!this.props.metadata || !this.props.metadata.properties) ? ( null ) : (this.props.topDown && !this.props.prone) ? ( this.renderTopDownMini() ) : ( this.renderStandeeMini() ); } } function MiniExtrusion() { const shape = React.useMemo(() => { const width = TabletopMiniComponent.MINI_WIDTH; const height = TabletopMiniComponent.MINI_HEIGHT; const cornerRadius = width * TabletopMiniComponent.MINI_CORNER_RADIUS_PERCENT / 100; const shape = new THREE.Shape(); shape.moveTo(-width/2, 0); shape.lineTo(-width/2, height - cornerRadius); shape.quadraticCurveTo(-width/2, height, cornerRadius - width/2, height); shape.lineTo(width/2 - cornerRadius, height); shape.quadraticCurveTo(width/2, height, width/2, height - cornerRadius); shape.lineTo(width/2, 0); shape.lineTo(-width/2, 0); return shape; }, []); return ( <extrudeGeometry attach='geometry' args={[shape, {depth: TabletopMiniComponent.MINI_THICKNESS, bevelEnabled: false}]}/> ); }
the_stack
import { values } from 'mobx'; import { BuildSwapSteps, SwapDirection } from 'types/state'; import { grpc } from '@improbable-eng/grpc-web'; import { waitFor } from '@testing-library/react'; import Big from 'big.js'; import { BalanceMode } from 'util/constants'; import { injectIntoGrpcUnary } from 'util/tests'; import { lndChannel, loopInTerms, loopOutTerms } from 'util/tests/sampleData'; import { createStore, Store } from 'store'; import { Channel } from 'store/models'; import { BuildSwapView } from 'store/views'; import { SWAP_ABORT_DELAY } from 'store/views/buildSwapView'; const grpcMock = grpc as jest.Mocked<typeof grpc>; describe('BuildSwapView', () => { let rootStore: Store; let store: BuildSwapView; beforeEach(async () => { rootStore = createStore(); await rootStore.fetchAllData(); store = rootStore.buildSwapView; }); it('should not start a swap if there are no channels', async () => { rootStore.channelStore.channels.clear(); expect(store.currentStep).toBe(BuildSwapSteps.Closed); expect(rootStore.appView.alerts.size).toBe(0); await store.startSwap(); expect(store.currentStep).toBe(BuildSwapSteps.Closed); expect(rootStore.appView.alerts.size).toBe(1); }); it('should toggle the selected channels', () => { expect(store.selectedChanIds).toHaveLength(0); store.toggleSelectedChannel('test'); expect(store.selectedChanIds).toHaveLength(1); store.toggleSelectedChannel('test'); expect(store.selectedChanIds).toHaveLength(0); }); it('should infer the swap direction based on the selected channels (receiving mode)', () => { rootStore.settingsStore.setBalanceMode(BalanceMode.receive); const channels = rootStore.channelStore.sortedChannels; store.toggleSelectedChannel(channels[0].chanId); expect(store.inferredDirection).toEqual(SwapDirection.OUT); store.toggleSelectedChannel(channels[channels.length - 1].chanId); expect(store.inferredDirection).toEqual(SwapDirection.OUT); }); it('should infer the swap direction based on the selected channels (sending mode)', () => { rootStore.settingsStore.setBalanceMode(BalanceMode.send); const channels = rootStore.channelStore.sortedChannels; store.toggleSelectedChannel(channels[0].chanId); expect(store.inferredDirection).toEqual(SwapDirection.IN); store.toggleSelectedChannel(channels[channels.length - 1].chanId); expect(store.inferredDirection).toEqual(SwapDirection.IN); }); it('should infer the swap direction based on the selected channels (routing mode)', () => { rootStore.settingsStore.setBalanceMode(BalanceMode.routing); const channels = rootStore.channelStore.sortedChannels; let c = channels[0]; c.localBalance = c.capacity.mul(0.2); c.remoteBalance = c.capacity.sub(c.localBalance); store.toggleSelectedChannel(c.chanId); expect(store.inferredDirection).toEqual(SwapDirection.IN); c = channels[channels.length - 1]; c.localBalance = c.capacity.mul(0.85); c.remoteBalance = c.capacity.sub(c.localBalance); store.toggleSelectedChannel(channels[channels.length - 1].chanId); expect(store.inferredDirection).toEqual(SwapDirection.OUT); }); it('should not infer the swap direction with no selected channels (routing mode)', () => { rootStore.settingsStore.setBalanceMode(BalanceMode.routing); expect(store.inferredDirection).toBeUndefined(); }); it('should fetch loop terms', async () => { expect(store.terms.in).toEqual({ min: Big(0), max: Big(0) }); expect(store.terms.out).toEqual({ min: Big(0), max: Big(0) }); await store.getTerms(); expect(store.terms.in).toEqual({ min: Big(250000), max: Big(1000000) }); expect(store.terms.out).toEqual({ min: Big(250000), max: Big(1000000), minCltv: 20, maxCltv: 60, }); }); it('should handle errors fetching loop terms', async () => { grpcMock.unary.mockImplementationOnce(desc => { if (desc.methodName === 'GetLoopInTerms') throw new Error('test-err'); return undefined as any; }); expect(rootStore.appView.alerts.size).toBe(0); await store.getTerms(); await waitFor(() => { expect(rootStore.appView.alerts.size).toBe(1); expect(values(rootStore.appView.alerts)[0].message).toBe('test-err'); }); }); it('should return the amount in between min/max by default', async () => { await store.getTerms(); expect(+store.amountForSelected).toBe(625000); }); it('should ensure amount is greater than the min terms', async () => { store.setAmount(Big(loopInTerms.minSwapAmount).sub(100)); await store.getTerms(); expect(store.amountForSelected.toString()).toBe(loopInTerms.minSwapAmount); }); it('should ensure amount is less than the max terms', async () => { store.setAmount(Big(loopInTerms.maxSwapAmount + 100)); await store.getTerms(); expect(store.amountForSelected.toString()).toBe(loopInTerms.maxSwapAmount); }); it('should validate the conf target', async () => { const { minCltvDelta, maxCltvDelta } = loopOutTerms; expect(store.confTarget).toBeUndefined(); let target = maxCltvDelta - 10; store.setConfTarget(target); expect(store.confTarget).toBe(target); store.setDirection(SwapDirection.OUT); await store.getTerms(); store.setConfTarget(target); expect(store.confTarget).toBe(target); target = minCltvDelta - 10; expect(() => store.setConfTarget(target)).toThrow(); target = maxCltvDelta + 10; expect(() => store.setConfTarget(target)).toThrow(); }); it('should submit the Loop Out conf target', async () => { const target = 23; store.setDirection(SwapDirection.OUT); store.setAmount(Big(500000)); expect(store.confTarget).toBeUndefined(); store.setConfTarget(target); expect(store.confTarget).toBe(target); let reqTarget = ''; // mock the grpc unary function in order to capture the supplied dest // passed in with the API request injectIntoGrpcUnary((desc, props) => { reqTarget = (props.request.toObject() as any).sweepConfTarget; }); store.requestSwap(); await waitFor(() => expect(reqTarget).toBe(target)); }); it('should submit the Loop Out address', async () => { const addr = 'xyzabc'; store.setDirection(SwapDirection.OUT); store.setAmount(Big(500000)); expect(store.loopOutAddress).toBeUndefined(); store.setLoopOutAddress(addr); expect(store.loopOutAddress).toBe(addr); // store.goToNextStep(); let reqAddr = ''; // mock the grpc unary function in order to capture the supplied dest // passed in with the API request injectIntoGrpcUnary((desc, props) => { reqAddr = (props.request.toObject() as any).dest; }); store.requestSwap(); await waitFor(() => expect(reqAddr).toBe(addr)); }); it('should select all channels with the same peer for loop in', () => { const channels = rootStore.channelStore.sortedChannels; channels[1].remotePubkey = channels[0].remotePubkey; channels[2].remotePubkey = channels[0].remotePubkey; expect(store.selectedChanIds).toHaveLength(0); store.toggleSelectedChannel(channels[0].chanId); store.setDirection(SwapDirection.IN); expect(store.selectedChanIds).toHaveLength(3); }); it('should fetch a loop in quote', async () => { expect(+store.quote.swapFee).toEqual(0); expect(+store.quote.minerFee).toEqual(0); expect(+store.quote.prepayAmount).toEqual(0); store.setDirection(SwapDirection.IN); store.setAmount(Big(600)); await store.getQuote(); expect(+store.quote.swapFee).toEqual(83); expect(+store.quote.minerFee).toEqual(7387); expect(+store.quote.prepayAmount).toEqual(0); }); it('should fetch a loop out quote', async () => { expect(+store.quote.swapFee).toEqual(0); expect(+store.quote.minerFee).toEqual(0); expect(+store.quote.prepayAmount).toEqual(0); store.setDirection(SwapDirection.OUT); store.setAmount(Big(600)); await store.getQuote(); expect(+store.quote.swapFee).toEqual(83); expect(+store.quote.minerFee).toEqual(7387); expect(+store.quote.prepayAmount).toEqual(1337); }); it('should handle errors fetching loop quote', async () => { grpcMock.unary.mockImplementationOnce(desc => { if (desc.methodName === 'LoopOutQuote') throw new Error('test-err'); return undefined as any; }); store.setDirection(SwapDirection.OUT); store.setAmount(Big(600)); expect(rootStore.appView.alerts.size).toBe(0); await store.getQuote(); await waitFor(() => { expect(rootStore.appView.alerts.size).toBe(1); expect(values(rootStore.appView.alerts)[0].message).toBe('test-err'); }); }); it('should perform a loop in', async () => { const channels = rootStore.channelStore.sortedChannels; // the pubkey in the sampleData is not valid, so hard-code this valid one channels[0].remotePubkey = '035c82e14eb74d2324daa17eebea8c58b46a9eabac87191cc83ee26275b514e6a0'; store.toggleSelectedChannel(channels[0].chanId); store.setDirection(SwapDirection.IN); store.setAmount(Big(600)); store.requestSwap(); await waitFor(() => { expect(grpcMock.unary).toHaveBeenCalledWith( expect.objectContaining({ methodName: 'LoopIn' }), expect.any(Object), ); }); }); it('should perform a loop out', async () => { const channels = rootStore.channelStore.sortedChannels; store.toggleSelectedChannel(channels[0].chanId); store.setDirection(SwapDirection.OUT); store.setAmount(Big(600)); store.requestSwap(); await waitFor(() => { expect(grpcMock.unary).toHaveBeenCalledWith( expect.objectContaining({ methodName: 'LoopOut' }), expect.anything(), ); }); }); it('should store swapped channels after a loop in', async () => { const channels = rootStore.channelStore.sortedChannels; // the pubkey in the sampleData is not valid, so hard-code this valid one channels[0].remotePubkey = '035c82e14eb74d2324daa17eebea8c58b46a9eabac87191cc83ee26275b514e6a0'; store.toggleSelectedChannel(channels[0].chanId); store.setDirection(SwapDirection.IN); store.setAmount(Big(600)); expect(rootStore.swapStore.swappedChannels.size).toBe(0); store.requestSwap(); await waitFor(() => expect(store.currentStep).toBe(BuildSwapSteps.Closed)); expect(rootStore.swapStore.swappedChannels.size).toBe(1); }); it('should store swapped channels after a loop out', async () => { const channels = rootStore.channelStore.sortedChannels; store.toggleSelectedChannel(channels[0].chanId); store.setDirection(SwapDirection.OUT); store.setAmount(Big(600)); expect(rootStore.swapStore.swappedChannels.size).toBe(0); store.requestSwap(); await waitFor(() => expect(store.currentStep).toBe(BuildSwapSteps.Closed)); expect(rootStore.swapStore.swappedChannels.size).toBe(1); }); it('should set the correct swap deadline in production', async () => { store.setDirection(SwapDirection.OUT); store.setAmount(Big(600)); let deadline = ''; // mock the grpc unary function in order to capture the supplied deadline // passed in with the API request injectIntoGrpcUnary((desc, props) => { deadline = (props.request.toObject() as any).swapPublicationDeadline; }); // run a loop on mainnet and verify the deadline rootStore.nodeStore.network = 'mainnet'; store.requestSwap(); await waitFor(() => expect(+deadline).toBeGreaterThan(0)); // inject again for the next swap injectIntoGrpcUnary((desc, props) => { deadline = (props.request.toObject() as any).swapPublicationDeadline; }); // run a loop on regtest and verify the deadline rootStore.nodeStore.network = 'regtest'; store.requestSwap(); await waitFor(() => expect(+deadline).toEqual(0)); }); it('should handle errors when performing a loop', async () => { grpcMock.unary.mockImplementationOnce(desc => { if (desc.methodName === 'LoopIn') throw new Error('test-err'); return undefined as any; }); store.setDirection(SwapDirection.IN); store.setAmount(Big(600)); expect(rootStore.appView.alerts.size).toBe(0); store.requestSwap(); await waitFor(() => { expect(rootStore.appView.alerts.size).toBe(1); expect(values(rootStore.appView.alerts)[0].message).toBe('test-err'); }); }); it('should delay for 3 seconds before performing a swap in production', async () => { store.setDirection(SwapDirection.OUT); store.setAmount(Big(600)); let executed = false; // mock the grpc unary function in order to know when the API request is executed injectIntoGrpcUnary(() => (executed = true)); // use mock timers so the test doesn't actually need to run for 3 seconds jest.useFakeTimers(); // run a loop in production and verify the delay Object.defineProperty(process, 'env', { get: () => ({ NODE_ENV: 'production' }) }); store.requestSwap(); jest.advanceTimersByTime(SWAP_ABORT_DELAY - 1); // the loop still should not have executed here expect(executed).toBe(false); // this should trigger the timeout at 3000 jest.advanceTimersByTime(1); expect(executed).toBe(true); // reset the env and mock timers Object.defineProperty(process, 'env', { get: () => ({ NODE_ENV: 'test' }) }); jest.useRealTimers(); }); it('should do nothing when abortSwap is called without requestSwap', async () => { const spy = jest.spyOn(window, 'clearTimeout'); expect(store.processingTimeout).toBeUndefined(); // run a loop in production and verify the delay store.abortSwap(); expect(store.processingTimeout).toBeUndefined(); expect(spy).not.toBeCalled(); spy.mockClear(); }); describe('min/max swap limits', () => { const addChannel = (capacity: number, localBalance: number) => { const remoteBalance = capacity - localBalance; const lndChan = { ...lndChannel, capacity: `${capacity}`, localBalance: `${localBalance}`, remoteBalance: `${remoteBalance}`, }; const channel = Channel.create(rootStore, lndChan); channel.chanId = `${channel.chanId}${rootStore.channelStore.channels.size}`; channel.remotePubkey = `${channel.remotePubkey}${rootStore.channelStore.channels.size}`; rootStore.channelStore.channels.set(channel.chanId, channel); }; const round = (amount: number) => { return Math.floor(amount / store.AMOUNT_INCREMENT) * store.AMOUNT_INCREMENT; }; beforeEach(() => { rootStore.channelStore.channels.clear(); [ { capacity: 200000, local: 100000 }, { capacity: 100000, local: 50000 }, { capacity: 100000, local: 20000 }, ].forEach(({ capacity, local }) => addChannel(capacity, local)); }); it('should limit Loop In max based on all remote balances', async () => { await store.getTerms(); store.setDirection(SwapDirection.IN); // should be the sum of all remote balances minus the reserve expect(+store.termsForDirection.max).toBe(round(230000 * 0.99)); }); it('should limit Loop In max based on selected remote balances', async () => { store.toggleSelectedChannel(store.channels[0].chanId); store.toggleSelectedChannel(store.channels[1].chanId); await store.getTerms(); store.setDirection(SwapDirection.IN); // should be the sum of the first two remote balances minus the reserve expect(+store.termsForDirection.max).toBe(round(150000 * 0.99)); }); it('should limit Loop Out max based on all local balances', async () => { await store.getTerms(); store.setDirection(SwapDirection.OUT); // should be the sum of all local balances minus the reserve expect(+store.termsForDirection.max).toBe(round(170000 * 0.99)); }); it('should limit Loop Out max based on selected local balances', async () => { store.toggleSelectedChannel(store.channels[0].chanId); store.toggleSelectedChannel(store.channels[1].chanId); await store.getTerms(); store.setDirection(SwapDirection.OUT); // should be the sum of the first two local balances minus the reserve expect(+store.termsForDirection.max).toBe(round(150000 * 0.99)); }); }); });
the_stack
import dedent from "dedent"; import type { InvalidTestCase } from "~/tests/helpers/util"; const tests: ReadonlyArray<InvalidTestCase> = [ { code: dedent` function foo(...numbers: number[]) { } `, optionsSet: [[]], output: dedent` function foo(...numbers: readonly number[]) { } `, errors: [ { messageId: "array", type: "TSArrayType", line: 1, column: 26, }, ], }, { code: dedent` function foo(...numbers: Array<number>) { } `, optionsSet: [[]], output: dedent` function foo(...numbers: ReadonlyArray<number>) { } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 26, }, ], }, { code: dedent` function foo(numbers: Set<number>) { } `, optionsSet: [[]], output: dedent` function foo(numbers: ReadonlySet<number>) { } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 23, }, ], }, { code: dedent` function foo(numbers: Map<number, string>) { } `, optionsSet: [[]], output: dedent` function foo(numbers: ReadonlyMap<number, string>) { } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 23, }, ], }, // Should fail on Array type in interface. { code: dedent` interface Foo { readonly bar: Array<string> } `, optionsSet: [[]], output: dedent` interface Foo { readonly bar: ReadonlyArray<string> } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 2, column: 17, }, ], }, // Should fail on Array type in index interface. { code: dedent` interface Foo { readonly [key: string]: { readonly groups: Array<string> } } `, optionsSet: [[]], output: dedent` interface Foo { readonly [key: string]: { readonly groups: ReadonlyArray<string> } } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 3, column: 22, }, ], }, // Should fail on Array type as function return type and in local interface. { code: dedent` function foo(): Array<string> { interface Foo { readonly bar: Array<string> } } `, optionsSet: [[]], output: dedent` function foo(): ReadonlyArray<string> { interface Foo { readonly bar: ReadonlyArray<string> } } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 17, }, { messageId: "type", type: "TSTypeReference", line: 3, column: 19, }, ], }, // Should fail on Array type as function return type and in local interface. { code: dedent` const foo = (): Array<string> => { interface Foo { readonly bar: Array<string> } } `, optionsSet: [[]], output: dedent` const foo = (): ReadonlyArray<string> => { interface Foo { readonly bar: ReadonlyArray<string> } } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 17, }, { messageId: "type", type: "TSTypeReference", line: 3, column: 19, }, ], }, // Should fail on shorthand syntax Array type as return type. { code: dedent` function foo(): number[] { } `, optionsSet: [[]], output: dedent` function foo(): readonly number[] { } `, errors: [ { messageId: "array", type: "TSArrayType", line: 1, column: 17, }, ], }, // Should fail on shorthand syntax Array type as return type. { code: `const foo = (): number[] => {}`, optionsSet: [[]], output: `const foo = (): readonly number[] => {}`, errors: [ { messageId: "array", type: "TSArrayType", line: 1, column: 17, }, ], }, // Should fail inside function. { code: dedent` const foo = function (): string { let bar: Array<string>; }; `, optionsSet: [[]], output: dedent` const foo = function (): string { let bar: ReadonlyArray<string>; }; `, errors: [ { messageId: "type", type: "TSTypeReference", line: 2, column: 12, }, ], }, // Tuples. { code: dedent` function foo(tuple: [number, string]) { } `, optionsSet: [[]], output: dedent` function foo(tuple: readonly [number, string]) { } `, errors: [ { messageId: "tuple", type: "TSTupleType", line: 1, column: 21, }, ], }, { code: dedent` function foo(tuple: [number, string, [number, string]]) { } `, optionsSet: [[]], output: dedent` function foo(tuple: readonly [number, string, readonly [number, string]]) { } `, errors: [ { messageId: "tuple", type: "TSTupleType", line: 1, column: 21, }, { messageId: "tuple", type: "TSTupleType", line: 1, column: 38, }, ], }, { code: dedent` function foo(tuple: readonly [number, string, [number, string]]) { } `, optionsSet: [[]], output: dedent` function foo(tuple: readonly [number, string, readonly [number, string]]) { } `, errors: [ { messageId: "tuple", type: "TSTupleType", line: 1, column: 47, }, ], }, { code: dedent` function foo(tuple: [number, string, readonly [number, string]]) { } `, optionsSet: [[]], output: dedent` function foo(tuple: readonly [number, string, readonly [number, string]]) { } `, errors: [ { messageId: "tuple", type: "TSTupleType", line: 1, column: 21, }, ], }, // Should fail on Array as type literal member as function parameter. { code: dedent` function foo( param1: { readonly bar: Array<string>, readonly baz: ReadonlyArray<string> } ): { readonly bar: Array<string>, readonly baz: ReadonlyArray<string> } { let foo: { readonly bar: Array<string>, readonly baz: ReadonlyArray<string> } = { bar: ["hello"], baz: ["world"] }; return foo; } `, optionsSet: [[]], output: dedent` function foo( param1: { readonly bar: ReadonlyArray<string>, readonly baz: ReadonlyArray<string> } ): { readonly bar: ReadonlyArray<string>, readonly baz: ReadonlyArray<string> } { let foo: { readonly bar: ReadonlyArray<string>, readonly baz: ReadonlyArray<string> } = { bar: ["hello"], baz: ["world"] }; return foo; } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 3, column: 19, }, { messageId: "type", type: "TSTypeReference", line: 7, column: 17, }, { messageId: "type", type: "TSTypeReference", line: 11, column: 19, }, ], }, // Should fail on Array type alias. { code: `type Foo = Array<string>;`, optionsSet: [[]], output: `type Foo = ReadonlyArray<string>;`, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 12, }, ], }, // Should fail on Array as type member. { code: dedent` function foo() { type Foo = { readonly bar: Array<string> } } `, optionsSet: [[]], output: dedent` function foo() { type Foo = { readonly bar: ReadonlyArray<string> } } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 3, column: 19, }, ], }, // Should fail on Array type alias in local type. { code: dedent` function foo() { type Foo = Array<string>; } `, optionsSet: [[]], output: dedent` function foo() { type Foo = ReadonlyArray<string>; } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 2, column: 14, }, ], }, // Should fail on Array as type member in local type. { code: dedent` function foo() { type Foo = { readonly bar: Array<string> } } `, optionsSet: [[]], output: dedent` function foo() { type Foo = { readonly bar: ReadonlyArray<string> } } `, errors: [ { messageId: "type", type: "TSTypeReference", line: 3, column: 19, }, ], }, // Should fail on Array type in variable declaration. { code: `const foo: Array<string> = [];`, optionsSet: [[]], output: `const foo: ReadonlyArray<string> = [];`, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 12, }, ], }, // Should fail on shorthand Array syntax. { code: `const foo: number[] = [1, 2, 3];`, optionsSet: [[]], output: `const foo: readonly number[] = [1, 2, 3];`, errors: [ { messageId: "array", type: "TSArrayType", line: 1, column: 12, }, ], }, // Should fail on Array type being used as template param. { code: `let x: Foo<Array<string>>;`, optionsSet: [[]], output: `let x: Foo<ReadonlyArray<string>>;`, errors: [ { messageId: "type", type: "TSTypeReference", line: 1, column: 12, }, ], }, // Should fail on nested shorthand arrays. { code: `let x: readonly string[][];`, optionsSet: [[]], output: `let x: readonly (readonly string[])[];`, errors: [ { messageId: "array", type: "TSArrayType", line: 1, column: 17, }, ], }, // Should fail on implicit Array type in variable declaration. { code: dedent` const foo = [1, 2, 3] function bar(param = [1, 2, 3]) {} `, optionsSet: [[{ checkImplicit: true }]], output: dedent` const foo: readonly unknown[] = [1, 2, 3] function bar(param: readonly unknown[] = [1, 2, 3]) {} `, errors: [ { messageId: "implicit", type: "VariableDeclarator", line: 1, column: 7, }, { messageId: "implicit", type: "AssignmentPattern", line: 2, column: 14, }, ], }, // Class Property Signatures. { code: dedent` class Klass { foo: number; private bar: number; static baz: number; private static qux: number; } `, optionsSet: [[]], output: dedent` class Klass { readonly foo: number; private readonly bar: number; static readonly baz: number; private static readonly qux: number; } `, errors: [ { messageId: "property", type: "PropertyDefinition", line: 2, column: 3, }, { messageId: "property", type: "PropertyDefinition", line: 3, column: 3, }, { messageId: "property", type: "PropertyDefinition", line: 4, column: 3, }, { messageId: "property", type: "PropertyDefinition", line: 5, column: 3, }, ], }, // Class Parameter Properties. { code: dedent` class Klass { constructor ( public publicProp: string, protected protectedProp: string, private privateProp: string, ) { } } `, optionsSet: [[]], output: dedent` class Klass { constructor ( public readonly publicProp: string, protected readonly protectedProp: string, private readonly privateProp: string, ) { } } `, errors: [ { messageId: "property", type: "TSParameterProperty", line: 3, column: 5, }, { messageId: "property", type: "TSParameterProperty", line: 4, column: 5, }, { messageId: "property", type: "TSParameterProperty", line: 5, column: 5, }, ], }, // Interface Index Signatures. { code: dedent` interface Foo { [key: string]: string } interface Bar { [key: string]: { prop: string } } `, optionsSet: [[]], output: dedent` interface Foo { readonly [key: string]: string } interface Bar { readonly [key: string]: { readonly prop: string } } `, errors: [ { messageId: "property", type: "TSIndexSignature", line: 2, column: 3, }, { messageId: "property", type: "TSIndexSignature", line: 5, column: 3, }, { messageId: "property", type: "TSPropertySignature", line: 5, column: 20, }, ], }, // Function Index Signatures. { code: dedent` function foo(): { [source: string]: string } { return undefined; } function bar(param: { [source: string]: string }): void { return undefined; } `, optionsSet: [[]], output: dedent` function foo(): { readonly [source: string]: string } { return undefined; } function bar(param: { readonly [source: string]: string }): void { return undefined; } `, errors: [ { messageId: "property", type: "TSIndexSignature", line: 1, column: 19, }, { messageId: "property", type: "TSIndexSignature", line: 4, column: 23, }, ], }, // Type literal with indexer without readonly modifier should produce failures. { code: `let foo: { [key: string]: number };`, optionsSet: [[]], output: `let foo: { readonly [key: string]: number };`, errors: [ { messageId: "property", type: "TSIndexSignature", line: 1, column: 12, }, ], }, // Type literal in property template parameter without readonly should produce failures. { code: dedent` type foo = ReadonlyArray<{ type: string, code: string, }>; `, optionsSet: [[]], output: dedent` type foo = ReadonlyArray<{ readonly type: string, readonly code: string, }>; `, errors: [ { messageId: "property", type: "TSPropertySignature", line: 2, column: 3, }, { messageId: "property", type: "TSPropertySignature", line: 3, column: 3, }, ], }, // Type literal without readonly on members should produce failures. // Also verify that nested members are checked. { code: dedent` let foo: { a: number, b: ReadonlyArray<string>, c: () => string, d: { readonly [key: string]: string }, [key: string]: string, readonly e: { a: number, b: ReadonlyArray<string>, c: () => string, d: { readonly [key: string]: string }, [key: string]: string, } }; `, optionsSet: [[]], output: dedent` let foo: { readonly a: number, readonly b: ReadonlyArray<string>, readonly c: () => string, readonly d: { readonly [key: string]: string }, readonly [key: string]: string, readonly e: { readonly a: number, readonly b: ReadonlyArray<string>, readonly c: () => string, readonly d: { readonly [key: string]: string }, readonly [key: string]: string, } }; `, errors: [ { messageId: "property", type: "TSPropertySignature", line: 2, column: 3, }, { messageId: "property", type: "TSPropertySignature", line: 3, column: 3, }, { messageId: "property", type: "TSPropertySignature", line: 4, column: 3, }, { messageId: "property", type: "TSPropertySignature", line: 5, column: 3, }, { messageId: "property", type: "TSIndexSignature", line: 6, column: 3, }, { messageId: "property", type: "TSPropertySignature", line: 8, column: 5, }, { messageId: "property", type: "TSPropertySignature", line: 9, column: 5, }, { messageId: "property", type: "TSPropertySignature", line: 10, column: 5, }, { messageId: "property", type: "TSPropertySignature", line: 11, column: 5, }, { messageId: "property", type: "TSIndexSignature", line: 12, column: 5, }, ], }, { code: dedent` function foo(bar: { x: number }) { }; `, optionsSet: [[{ allowLocalMutation: true }]], output: dedent` function foo(bar: { readonly x: number }) { }; `, errors: [ { messageId: "property", type: "TSPropertySignature", line: 1, column: 21, }, ], }, // Mapped type without readonly. { code: dedent` const func = (x: { [key in string]: number }) => {} `, optionsSet: [[]], output: dedent` const func = (x: { readonly [key in string]: number }) => {} `, errors: [ { messageId: "property", type: "TSMappedType", line: 1, column: 18, }, ], }, // Flag non class fields. { code: dedent` class Klass { foo() { let bar: { foo: number; }; } } `, optionsSet: [[{ ignoreClass: "fieldsOnly" }]], output: dedent` class Klass { foo() { let bar: { readonly foo: number; }; } } `, errors: [ { messageId: "property", type: "TSPropertySignature", line: 4, column: 7, }, ], }, // Computed properties. { code: dedent` const propertyName = 'myProperty'; type Foo = { [propertyName]: string; }; `, optionsSet: [[]], output: dedent` const propertyName = 'myProperty'; type Foo = { readonly [propertyName]: string; }; `, errors: [ { messageId: "property", type: "TSPropertySignature", line: 3, column: 3, }, ], }, ]; export default tests;
the_stack
import { isFunction, isDefined } from '../../../../../shared/utils'; import { O_ALTER_TABLE_SPEC_ADD_COLUMN, O_ALTER_TABLE_SPEC_ADD_COLUMNS, O_ALTER_TABLE_SPEC_ADD_INDEX, O_ALTER_TABLE_SPEC_ADD_PRIMARY_KEY, O_ALTER_TABLE_SPEC_ADD_UNIQUE_KEY, O_ALTER_TABLE_SPEC_ADD_FULLTEXT_INDEX, O_ALTER_TABLE_SPEC_ADD_SPATIAL_INDEX, O_ALTER_TABLE_SPEC_ADD_FOREIGN_KEY, O_ALTER_TABLE_SPEC_DROP_PRIMARY_KEY, O_ALTER_TABLE_SPEC_SET_DEFAULT_COLUMN_VALUE, O_ALTER_TABLE_SPEC_DROP_DEFAULT_COLUMN_VALUE, O_ALTER_TABLE_SPEC_CHANGE_COLUMN, O_ALTER_TABLE_SPEC_DROP_COLUMN, O_ALTER_TABLE_SPEC_DROP_INDEX, O_ALTER_TABLE_SPEC_DROP_FOREIGN_KEY, O_ALTER_TABLE_SPEC_RENAME_INDEX, O_ALTER_TABLE_SPEC_RENAME, P_ALTER_TABLE, P_ALTER_TABLE_ACTION, O_POSITION, } from '../../../../../typings'; import { TableOptions } from '../table-options'; import { Column } from '../column'; import { Index } from '../index'; import { PrimaryKey } from '../primary-key'; import { UniqueKey } from '../unique-key'; import { FulltextIndex } from '../fulltext-index'; import { SpatialIndex } from '../spatial-index'; import { ForeignKey } from '../foreign-key'; import { ColumnOptions } from '../column-options'; import { Datatype } from '../datatype'; import { TableModelInterface, DatabaseModelInterface, RuleHandler } from '../typings'; /** * Formatter for P_ALTER_TABLE rule's parsed JSON. */ export class AlterTable implements RuleHandler { database!: DatabaseModelInterface; /** * Get table with given name. * * @param name Table name. */ getTable(name: string): TableModelInterface | undefined { return this.database.getTable(name); } /** * Setter for database. * * @param database Database instance. */ setDatabase(database: DatabaseModelInterface): void { this.database = database; } /** * Alters one of the tables. * * @param json JSON format parsed from SQL. */ handleDef(json: P_ALTER_TABLE): void { if (json.id === 'P_ALTER_TABLE') { const table = this.getTable(json.def.table); if (!table) { return; } /** * Runs methods in this class according to the * 'action' property of the ALTER TABLE spec. */ json.def.specs.forEach((spec) => { const changeSpec = spec.def.spec; const tableOptions = spec.def.tableOptions; if (changeSpec) { const def = changeSpec.def; const action = def.action; const fn = AlterTable[action as P_ALTER_TABLE_ACTION]; if (isFunction(fn)) { fn(def as never, table); } } else if (tableOptions) { if (!table.options) { table.options = new TableOptions(); } table.options.mergeWith(TableOptions.fromDef(tableOptions)); } }); return; } throw new TypeError(`Expected P_ALTER_TABLE rule to be handled but received ${json.id}`); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addColumn(json: O_ALTER_TABLE_SPEC_ADD_COLUMN, table: TableModelInterface): void { const column = Column.fromObject(json); /** * Adding columns with REFERENCES should not create FK constraint. * https://github.com/duartealexf/sql-ddl-to-json-schema/issues/16 */ if (column.reference) { delete column.reference; } table.addColumn(column, json.position); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addColumns( json: O_ALTER_TABLE_SPEC_ADD_COLUMNS, table: TableModelInterface, ): void { json.columns.forEach((c) => { const column = Column.fromObject(c); /** * Adding columns with REFERENCES should not create FK constraint. * https://github.com/duartealexf/sql-ddl-to-json-schema/issues/16 */ if (column.reference) { delete column.reference; } table.addColumn(column); }); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addIndex(json: O_ALTER_TABLE_SPEC_ADD_INDEX, table: TableModelInterface): void { const index = Index.fromObject(json); table.pushIndex(index); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addPrimaryKey( json: O_ALTER_TABLE_SPEC_ADD_PRIMARY_KEY, table: TableModelInterface, ): void { const key = PrimaryKey.fromObject(json); table.setPrimaryKey(key); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addUniqueKey( json: O_ALTER_TABLE_SPEC_ADD_UNIQUE_KEY, table: TableModelInterface, ): void { const key = UniqueKey.fromObject(json); table.pushUniqueKey(key); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addFulltextIndex( json: O_ALTER_TABLE_SPEC_ADD_FULLTEXT_INDEX, table: TableModelInterface, ): void { const index = FulltextIndex.fromObject(json); table.pushFulltextIndex(index); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addSpatialIndex( json: O_ALTER_TABLE_SPEC_ADD_SPATIAL_INDEX, table: TableModelInterface, ): void { const index = SpatialIndex.fromObject(json); table.pushFulltextIndex(index); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static addForeignKey( json: O_ALTER_TABLE_SPEC_ADD_FOREIGN_KEY, table: TableModelInterface, ): void { const key = ForeignKey.fromObject(json); table.pushForeignKey(key); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static setDefaultColumnValue( json: O_ALTER_TABLE_SPEC_SET_DEFAULT_COLUMN_VALUE, table: TableModelInterface, ): void { const column = table.getColumn(json.column); if (!isDefined(column) || !isDefined(column.options)) { return; } column.options.default = json.value; } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static dropDefaultColumnValue( json: O_ALTER_TABLE_SPEC_DROP_DEFAULT_COLUMN_VALUE, table: TableModelInterface, ): void { const column = table.getColumn(json.column); if (!isDefined(column) || !isDefined(column.options)) { return; } delete column.options.default; } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static changeColumn( json: O_ALTER_TABLE_SPEC_CHANGE_COLUMN, table: TableModelInterface, ): void { const column = table.getColumn(json.column); if (!column) { return; } let position: O_POSITION | undefined; if (json.position) { if (json.position.after) { if (!table.getColumn(json.position.after)) { /** * Referential 'after' column does not exist. */ return; } } position = json.position; } else { position = table.getColumnPosition(column); } const type = Datatype.fromDef(json.datatype); let options; /** * Alter table change column should not bring old * column options, so we completely overwrite it. * https://github.com/duartealexf/sql-ddl-to-json-schema/issues/10 */ if (json.columnDefinition) { options = ColumnOptions.fromArray(json.columnDefinition); } /** * Stop if anything went wrong parsing new column options. */ if (!isDefined(options)) { return; } /** * Alter table does not overwrite primary key. * Statements like these in the DBMS are canceled. */ if (options.primary && table.primaryKey) { return; } /** * Table should have only one column with autoincrement, * except when column being modified is already autoincrement. * Statements like these in the DBMS are canceled. */ if ( options.autoincrement && (table.columns ?? []).some((c) => c !== column && c.options?.autoincrement) ) { return; } /** * If there is an unique option that would * create duplicate unique key, remove it. */ if ( options.unique && table.uniqueKeys?.some( (uniqueKey) => uniqueKey.columns.length === 1 && uniqueKey.columns[0].column === column.name, ) ) { delete options.unique; } /** * Finally change the column. */ if (position && table.moveColumn(column, position)) { /** * If there is a new column name in statement, that is different * from current name, rename column and references to it. */ if (json.newName && json.newName !== column.name) { table.renameColumn(column, json.newName); } column.type = type; column.options = options; table.extractColumnKeys(column); } } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static dropColumn( json: O_ALTER_TABLE_SPEC_DROP_COLUMN, table: TableModelInterface, ): void { const column = table.getColumn(json.column); if (!column) { return; } table.dropColumn(column); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static dropIndex(json: O_ALTER_TABLE_SPEC_DROP_INDEX, table: TableModelInterface): void { if (json.index.toLowerCase() === 'primary') { AlterTable.dropPrimaryKey(json, table); return; } const index = table.getIndexByName(json.index); if (!index) { return; } table.dropIndexByInstance(index); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static dropPrimaryKey( json: O_ALTER_TABLE_SPEC_DROP_PRIMARY_KEY | O_ALTER_TABLE_SPEC_DROP_INDEX, table: TableModelInterface, ): void { table.dropPrimaryKey(); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static dropForeignKey( json: O_ALTER_TABLE_SPEC_DROP_FOREIGN_KEY, table: TableModelInterface, ): void { const foreignKey = table.getForeignKey(json.key); if (!foreignKey) { return; } table.dropForeignKey(foreignKey); } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static renameIndex( json: O_ALTER_TABLE_SPEC_RENAME_INDEX, table: TableModelInterface, ): void { const index = table.getIndexByName(json.index); if (!index) { return; } index.name = json.newName; } /** * Performs action in ALTER TABLE statement. * * @param json O_ALTER_TABLE_SPEC def object in JSON. * @param table Table to be altered. */ private static rename(json: O_ALTER_TABLE_SPEC_RENAME, table: TableModelInterface): void { table.renameTo(json.newName); } }
the_stack
import * as ts from 'typescript'; export abstract class Visitor { visitNode(node: ts.Node) { switch (node.kind) { case ts.SyntaxKind.AnyKeyword: this.visitAnyKeyword(node); break; case ts.SyntaxKind.ArrayBindingPattern: this.visitBindingPattern(<ts.BindingPattern>node); break; case ts.SyntaxKind.ArrayLiteralExpression: this.visitArrayLiteralExpression(<ts.ArrayLiteralExpression>node); break; case ts.SyntaxKind.ArrayType: this.visitArrayType(<ts.ArrayTypeNode>node); break; case ts.SyntaxKind.ArrowFunction: this.visitArrowFunction(<ts.FunctionLikeDeclaration>node); break; case ts.SyntaxKind.BinaryExpression: this.visitBinaryExpression(<ts.BinaryExpression>node); break; case ts.SyntaxKind.BindingElement: this.visitBindingElement(<ts.BindingElement>node); break; case ts.SyntaxKind.Block: this.visitBlock(<ts.Block>node); break; case ts.SyntaxKind.BreakStatement: this.visitBreakStatement(<ts.BreakOrContinueStatement>node); break; case ts.SyntaxKind.CallExpression: this.visitCallExpression(<ts.CallExpression>node); break; case ts.SyntaxKind.CallSignature: this.visitCallSignature(<ts.SignatureDeclaration>node); break; case ts.SyntaxKind.CaseClause: this.visitCaseClause(<ts.CaseClause>node); break; case ts.SyntaxKind.ClassDeclaration: this.visitClassDeclaration(<ts.ClassDeclaration>node); break; case ts.SyntaxKind.ClassExpression: this.visitClassExpression(<ts.ClassExpression>node); break; case ts.SyntaxKind.CatchClause: this.visitCatchClause(<ts.CatchClause>node); break; case ts.SyntaxKind.ConditionalExpression: this.visitConditionalExpression(<ts.ConditionalExpression>node); break; case ts.SyntaxKind.ConstructSignature: this.visitConstructSignature(<ts.ConstructSignatureDeclaration>node); break; case ts.SyntaxKind.Constructor: this.visitConstructorDeclaration(<ts.ConstructorDeclaration>node); break; case ts.SyntaxKind.ConstructorType: this.visitConstructorType(<ts.FunctionOrConstructorTypeNode>node); break; case ts.SyntaxKind.ContinueStatement: this.visitContinueStatement(<ts.BreakOrContinueStatement>node); break; case ts.SyntaxKind.DebuggerStatement: this.visitDebuggerStatement(<ts.Statement>node); break; case ts.SyntaxKind.DefaultClause: this.visitDefaultClause(<ts.DefaultClause>node); break; case ts.SyntaxKind.DoStatement: this.visitDoStatement(<ts.DoStatement>node); break; case ts.SyntaxKind.ElementAccessExpression: this.visitElementAccessExpression(<ts.ElementAccessExpression>node); break; case ts.SyntaxKind.EnumDeclaration: this.visitEnumDeclaration(<ts.EnumDeclaration>node); break; case ts.SyntaxKind.ExportAssignment: this.visitExportAssignment(<ts.ExportAssignment>node); break; case ts.SyntaxKind.ExpressionStatement: this.visitExpressionStatement(<ts.ExpressionStatement>node); break; case ts.SyntaxKind.ForStatement: this.visitForStatement(<ts.ForStatement>node); break; case ts.SyntaxKind.ForInStatement: this.visitForInStatement(<ts.ForInStatement>node); break; case ts.SyntaxKind.ForOfStatement: this.visitForOfStatement(<ts.ForOfStatement>node); break; case ts.SyntaxKind.FunctionDeclaration: this.visitFunctionDeclaration(<ts.FunctionDeclaration>node); break; case ts.SyntaxKind.FunctionExpression: this.visitFunctionExpression(<ts.FunctionExpression>node); break; case ts.SyntaxKind.FunctionType: this.visitFunctionType(<ts.FunctionOrConstructorTypeNode>node); break; case ts.SyntaxKind.GetAccessor: this.visitGetAccessor(<ts.AccessorDeclaration>node); break; case ts.SyntaxKind.Identifier: this.visitIdentifier(<ts.Identifier>node); break; case ts.SyntaxKind.IfStatement: this.visitIfStatement(<ts.IfStatement>node); break; case ts.SyntaxKind.ImportDeclaration: this.visitImportDeclaration(<ts.ImportDeclaration>node); break; case ts.SyntaxKind.ImportEqualsDeclaration: this.visitImportEqualsDeclaration(<ts.ImportEqualsDeclaration>node); break; case ts.SyntaxKind.IndexSignature: this.visitIndexSignatureDeclaration(<ts.IndexSignatureDeclaration>node); break; case ts.SyntaxKind.InterfaceDeclaration: this.visitInterfaceDeclaration(<ts.InterfaceDeclaration>node); break; case ts.SyntaxKind.JsxAttribute: this.visitJsxAttribute(<ts.JsxAttribute>node); break; case ts.SyntaxKind.JsxElement: this.visitJsxElement(<ts.JsxElement>node); break; case ts.SyntaxKind.JsxExpression: this.visitJsxExpression(<ts.JsxExpression>node); break; case ts.SyntaxKind.JsxSelfClosingElement: this.visitJsxSelfClosingElement(<ts.JsxSelfClosingElement>node); break; case ts.SyntaxKind.JsxSpreadAttribute: this.visitJsxSpreadAttribute(<ts.JsxSpreadAttribute>node); break; case ts.SyntaxKind.LabeledStatement: this.visitLabeledStatement(<ts.LabeledStatement>node); break; case ts.SyntaxKind.MethodDeclaration: this.visitMethodDeclaration(<ts.MethodDeclaration>node); break; case ts.SyntaxKind.MethodSignature: this.visitMethodSignature(<ts.SignatureDeclaration>node); break; case ts.SyntaxKind.ModuleDeclaration: this.visitModuleDeclaration(<ts.ModuleDeclaration>node); break; case ts.SyntaxKind.NamedImports: this.visitNamedImports(<ts.NamedImports>node); break; case ts.SyntaxKind.NamespaceImport: this.visitNamespaceImport(<ts.NamespaceImport>node); break; case ts.SyntaxKind.NewExpression: this.visitNewExpression(<ts.NewExpression>node); break; case ts.SyntaxKind.ObjectBindingPattern: this.visitBindingPattern(<ts.BindingPattern>node); break; case ts.SyntaxKind.ObjectLiteralExpression: this.visitObjectLiteralExpression(<ts.ObjectLiteralExpression>node); break; case ts.SyntaxKind.Parameter: this.visitParameterDeclaration(<ts.ParameterDeclaration>node); break; case ts.SyntaxKind.PostfixUnaryExpression: this.visitPostfixUnaryExpression(<ts.PostfixUnaryExpression>node); break; case ts.SyntaxKind.PrefixUnaryExpression: this.visitPrefixUnaryExpression(<ts.PrefixUnaryExpression>node); break; case ts.SyntaxKind.PropertyAccessExpression: this.visitPropertyAccessExpression(<ts.PropertyAccessExpression>node); break; case ts.SyntaxKind.PropertyAssignment: this.visitPropertyAssignment(<ts.PropertyAssignment>node); break; case ts.SyntaxKind.PropertyDeclaration: this.visitPropertyDeclaration(<ts.PropertyDeclaration>node); break; case ts.SyntaxKind.PropertySignature: this.visitPropertySignature(node); break; case ts.SyntaxKind.RegularExpressionLiteral: this.visitRegularExpressionLiteral(node); break; case ts.SyntaxKind.ReturnStatement: this.visitReturnStatement(<ts.ReturnStatement>node); break; case ts.SyntaxKind.SetAccessor: this.visitSetAccessor(<ts.AccessorDeclaration>node); break; case ts.SyntaxKind.SourceFile: this.visitSourceFile(<ts.SourceFile>node); break; case ts.SyntaxKind.StringLiteral: this.visitStringLiteral(<ts.StringLiteral>node); break; case ts.SyntaxKind.SwitchStatement: this.visitSwitchStatement(<ts.SwitchStatement>node); break; case ts.SyntaxKind.TemplateExpression: this.visitTemplateExpression(<ts.TemplateExpression>node); break; case ts.SyntaxKind.ThrowStatement: this.visitThrowStatement(<ts.ThrowStatement>node); break; case ts.SyntaxKind.TryStatement: this.visitTryStatement(<ts.TryStatement>node); break; case ts.SyntaxKind.TupleType: this.visitTupleType(<ts.TupleTypeNode>node); break; case ts.SyntaxKind.TypeAliasDeclaration: this.visitTypeAliasDeclaration(<ts.TypeAliasDeclaration>node); break; case ts.SyntaxKind.TypeAssertionExpression: this.visitTypeAssertionExpression(<ts.TypeAssertion>node); break; case ts.SyntaxKind.TypeLiteral: this.visitTypeLiteral(<ts.TypeLiteralNode>node); break; case ts.SyntaxKind.TypeReference: this.visitTypeReference(<ts.TypeReferenceNode>node); break; case ts.SyntaxKind.VariableDeclaration: this.visitVariableDeclaration(<ts.VariableDeclaration>node); break; case ts.SyntaxKind.VariableStatement: this.visitVariableStatement(<ts.VariableStatement>node); break; case ts.SyntaxKind.WhileStatement: this.visitWhileStatement(<ts.WhileStatement>node); break; case ts.SyntaxKind.WithStatement: this.visitWithStatement(<ts.WithStatement>node); break; default: console.warn(`unknown node type: ${node}`); break; } } visitChildren(node: ts.Node): void { ts.forEachChild(node, (child) => this.visitNode(child)); } visitAnyKeyword(node: ts.Node): void { this.visitChildren(node); } visitArrayLiteralExpression(node: ts.ArrayLiteralExpression): void { this.visitChildren(node); } visitArrayType(node: ts.ArrayTypeNode): void { this.visitChildren(node); } visitArrowFunction(node: ts.FunctionLikeDeclaration): void { this.visitChildren(node); } visitBinaryExpression(node: ts.BinaryExpression): void { this.visitChildren(node); } visitBindingElement(node: ts.BindingElement): void { this.visitChildren(node); } visitBindingPattern(node: ts.BindingPattern): void { this.visitChildren(node); } visitBlock(node: ts.Block): void { this.visitChildren(node); } visitBreakStatement(node: ts.BreakOrContinueStatement): void { this.visitChildren(node); } visitCallExpression(node: ts.CallExpression): void { this.visitChildren(node); } visitCallSignature(node: ts.SignatureDeclaration): void { this.visitChildren(node); } visitCaseClause(node: ts.CaseClause): void { this.visitChildren(node); } visitClassDeclaration(node: ts.ClassDeclaration): void { this.visitChildren(node); } visitClassExpression(node: ts.ClassExpression): void { this.visitChildren(node); } visitCatchClause(node: ts.CatchClause): void { this.visitChildren(node); } visitConditionalExpression(node: ts.ConditionalExpression): void { this.visitChildren(node); } visitConstructSignature(node: ts.ConstructSignatureDeclaration): void { this.visitChildren(node); } visitConstructorDeclaration(node: ts.ConstructorDeclaration): void { this.visitChildren(node); } visitConstructorType(node: ts.FunctionOrConstructorTypeNode): void { this.visitChildren(node); } visitContinueStatement(node: ts.BreakOrContinueStatement): void { this.visitChildren(node); } visitDebuggerStatement(node: ts.Statement): void { this.visitChildren(node); } visitDefaultClause(node: ts.DefaultClause): void { this.visitChildren(node); } visitDoStatement(node: ts.DoStatement): void { this.visitChildren(node); } visitElementAccessExpression(node: ts.ElementAccessExpression): void { this.visitChildren(node); } visitEnumDeclaration(node: ts.EnumDeclaration): void { this.visitChildren(node); } visitExportAssignment(node: ts.ExportAssignment): void { this.visitChildren(node); } visitExpressionStatement(node: ts.ExpressionStatement): void { this.visitChildren(node); } visitForStatement(node: ts.ForStatement): void { this.visitChildren(node); } visitForInStatement(node: ts.ForInStatement): void { this.visitChildren(node); } visitForOfStatement(node: ts.ForOfStatement): void { this.visitChildren(node); } visitFunctionDeclaration(node: ts.FunctionDeclaration): void { this.visitChildren(node); } visitFunctionExpression(node: ts.FunctionExpression): void { this.visitChildren(node); } visitFunctionType(node: ts.FunctionOrConstructorTypeNode): void { this.visitChildren(node); } visitGetAccessor(node: ts.AccessorDeclaration): void { this.visitChildren(node); } visitIdentifier(node: ts.Identifier): void { this.visitChildren(node); } visitIfStatement(node: ts.IfStatement): void { this.visitChildren(node); } visitImportDeclaration(node: ts.ImportDeclaration): void { this.visitChildren(node); } visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration): void { this.visitChildren(node); } visitIndexSignatureDeclaration(node: ts.IndexSignatureDeclaration): void { this.visitChildren(node); } visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void { this.visitChildren(node); } visitJsxAttribute(node: ts.JsxAttribute): void { this.visitChildren(node); } visitJsxElement(node: ts.JsxElement): void { this.visitChildren(node); } visitJsxExpression(node: ts.JsxExpression): void { this.visitChildren(node); } visitJsxSelfClosingElement(node: ts.JsxSelfClosingElement): void { this.visitChildren(node); } visitJsxSpreadAttribute(node: ts.JsxSpreadAttribute): void { this.visitChildren(node); } visitLabeledStatement(node: ts.LabeledStatement): void { this.visitChildren(node); } visitMethodDeclaration(node: ts.MethodDeclaration): void { this.visitChildren(node); } visitMethodSignature(node: ts.SignatureDeclaration): void { this.visitChildren(node); } visitModuleDeclaration(node: ts.ModuleDeclaration): void { this.visitChildren(node); } visitNamedImports(node: ts.NamedImports): void { this.visitChildren(node); } visitNamespaceImport(node: ts.NamespaceImport): void { this.visitChildren(node); } visitNewExpression(node: ts.NewExpression): void { this.visitChildren(node); } visitObjectLiteralExpression(node: ts.ObjectLiteralExpression): void { this.visitChildren(node); } visitParameterDeclaration(node: ts.ParameterDeclaration): void { this.visitChildren(node); } visitPostfixUnaryExpression(node: ts.PostfixUnaryExpression): void { this.visitChildren(node); } visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression): void { this.visitChildren(node); } visitPropertyAccessExpression(node: ts.PropertyAccessExpression): void { this.visitChildren(node); } visitPropertyAssignment(node: ts.PropertyAssignment): void { this.visitChildren(node); } visitPropertyDeclaration(node: ts.PropertyDeclaration): void { this.visitChildren(node); } visitPropertySignature(node: ts.Node): void { this.visitChildren(node); } visitRegularExpressionLiteral(node: ts.Node): void { this.visitChildren(node); } visitReturnStatement(node: ts.ReturnStatement): void { this.visitChildren(node); } visitSetAccessor(node: ts.AccessorDeclaration): void { this.visitChildren(node); } visitSourceFile(node: ts.SourceFile): void { this.visitChildren(node); } visitStringLiteral(node: ts.StringLiteral): void { this.visitChildren(node); } visitSwitchStatement(node: ts.SwitchStatement): void { this.visitChildren(node); } visitTemplateExpression(node: ts.TemplateExpression): void { this.visitChildren(node); } visitThrowStatement(node: ts.ThrowStatement): void { this.visitChildren(node); } visitTryStatement(node: ts.TryStatement): void { this.visitChildren(node); } visitTupleType(node: ts.TupleTypeNode): void { this.visitChildren(node); } visitTypeAliasDeclaration(node: ts.TypeAliasDeclaration): void { this.visitChildren(node); } visitTypeAssertionExpression(node: ts.TypeAssertion): void { this.visitChildren(node); } visitTypeLiteral(node: ts.TypeLiteralNode): void { this.visitChildren(node); } visitTypeReference(node: ts.TypeReferenceNode): void { this.visitChildren(node); } visitVariableDeclaration(node: ts.VariableDeclaration): void { this.visitChildren(node); } visitVariableStatement(node: ts.VariableStatement): void { this.visitChildren(node); } visitWhileStatement(node: ts.WhileStatement): void { this.visitChildren(node); } visitWithStatement(node: ts.WithStatement): void { this.visitChildren(node); } }
the_stack
import type {Proto, ObserverType} from "@swim/util"; import {FastenerOwner, FastenerInit, FastenerClass, Fastener} from "@swim/component"; import {Model} from "../model/Model"; import {AnyTrait, TraitFactory, Trait} from "./Trait"; /** @internal */ export type TraitRelationType<F extends TraitRelation<any, any>> = F extends TraitRelation<any, infer T> ? T : never; /** @public */ export interface TraitRelationInit<T extends Trait = Trait> extends FastenerInit { extends?: {prototype: TraitRelation<any, any>} | string | boolean | null; type?: TraitFactory<T>; binds?: boolean; observes?: boolean; initTrait?(trait: T): void; willAttachTrait?(trait: T, target: Trait | null): void; didAttachTrait?(trait: T, target: Trait | null): void; deinitTrait?(trait: T): void; willDetachTrait?(trait: T): void; didDetachTrait?(trait: T): void; parentModel?: Model | null; insertChild?(model: Model, trait: T, target: Trait | null, key: string | undefined): void; detectModel?(model: Model): T | null; detectTrait?(trait: Trait): T | null; createTrait?(): T; fromAny?(value: AnyTrait<T>): T; } /** @public */ export type TraitRelationDescriptor<O = unknown, T extends Trait = Trait, I = {}> = ThisType<TraitRelation<O, T> & I> & TraitRelationInit<T> & Partial<I>; /** @public */ export interface TraitRelationClass<F extends TraitRelation<any, any> = TraitRelation<any, any>> extends FastenerClass<F> { } /** @public */ export interface TraitRelationFactory<F extends TraitRelation<any, any> = TraitRelation<any, any>> extends TraitRelationClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): TraitRelationFactory<F> & I; define<O, T extends Trait = Trait>(className: string, descriptor: TraitRelationDescriptor<O, T>): TraitRelationFactory<TraitRelation<any, T>>; define<O, T extends Trait = Trait>(className: string, descriptor: {observes: boolean} & TraitRelationDescriptor<O, T, ObserverType<T>>): TraitRelationFactory<TraitRelation<any, T>>; define<O, T extends Trait = Trait, I = {}>(className: string, descriptor: {implements: unknown} & TraitRelationDescriptor<O, T, I>): TraitRelationFactory<TraitRelation<any, T> & I>; define<O, T extends Trait = Trait, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & TraitRelationDescriptor<O, T, I & ObserverType<T>>): TraitRelationFactory<TraitRelation<any, T> & I>; <O, T extends Trait = Trait>(descriptor: TraitRelationDescriptor<O, T>): PropertyDecorator; <O, T extends Trait = Trait>(descriptor: {observes: boolean} & TraitRelationDescriptor<O, T, ObserverType<T>>): PropertyDecorator; <O, T extends Trait = Trait, I = {}>(descriptor: {implements: unknown} & TraitRelationDescriptor<O, T, I>): PropertyDecorator; <O, T extends Trait = Trait, I = {}>(descriptor: {implements: unknown; observes: boolean} & TraitRelationDescriptor<O, T, I & ObserverType<T>>): PropertyDecorator; } /** @public */ export interface TraitRelation<O = unknown, T extends Trait = Trait> extends Fastener<O> { /** @override */ get fastenerType(): Proto<TraitRelation<any, any>>; /** @protected */ initTrait(trait: T): void; /** @protected */ willAttachTrait(trait: T, target: Trait | null): void; /** @protected */ onAttachTrait(trait: T, target: Trait | null): void; /** @protected */ didAttachTrait(trait: T, target: Trait | null): void; /** @protected */ deinitTrait(trait: T): void; /** @protected */ willDetachTrait(trait: T): void; /** @protected */ onDetachTrait(trait: T): void; /** @protected */ didDetachTrait(trait: T): void; /** @internal @protected */ get parentModel(): Model | null; /** @internal @protected */ insertChild(model: Model, trait: T, target: Trait | null, key: string | undefined): void; /** @internal */ bindModel(model: Model, targetModel: Model | null): void; /** @internal */ unbindModel(model: Model): void; detectModel(model: Model): T | null; /** @internal */ bindTrait(trait: Trait, target: Trait | null): void; /** @internal */ unbindTrait(trait: Trait): void; detectTrait(trait: Trait): T | null; createTrait(): T; /** @internal @protected */ fromAny(value: AnyTrait<T>): T; /** @internal @protected */ get type(): TraitFactory<T> | undefined; // optional prototype property /** @internal @protected */ get binds(): boolean | undefined; // optional prototype property /** @internal @protected */ get observes(): boolean | undefined; // optional prototype property /** @internal @override */ get lazy(): boolean; // prototype property /** @internal @override */ get static(): string | boolean; // prototype property } /** @public */ export const TraitRelation = (function (_super: typeof Fastener) { const TraitRelation: TraitRelationFactory = _super.extend("TraitRelation"); Object.defineProperty(TraitRelation.prototype, "fastenerType", { get: function (this: TraitRelation): Proto<TraitRelation<any, any>> { return TraitRelation; }, configurable: true, }); TraitRelation.prototype.initTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T): void { // hook }; TraitRelation.prototype.willAttachTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T, target: Trait | null): void { // hook }; TraitRelation.prototype.onAttachTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T, target: Trait | null): void { if (this.observes === true) { trait.observe(this as ObserverType<T>); } }; TraitRelation.prototype.didAttachTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T, target: Trait | null): void { // hook }; TraitRelation.prototype.deinitTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T): void { // hook }; TraitRelation.prototype.willDetachTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T): void { // hook }; TraitRelation.prototype.onDetachTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T): void { if (this.observes === true) { trait.unobserve(this as ObserverType<T>); } }; TraitRelation.prototype.didDetachTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: T): void { // hook }; Object.defineProperty(TraitRelation.prototype, "parentModel", { get(this: TraitRelation): Model | null { const owner = this.owner; if (owner instanceof Model) { return owner; } else if (owner instanceof Trait) { return owner.model; } else { return null; } }, configurable: true, }); TraitRelation.prototype.insertChild = function <T extends Trait>(this: TraitRelation<unknown, T>, model: Model, trait: T, target: Trait | null, key: string | undefined): void { model.insertTrait(trait, target, key); }; TraitRelation.prototype.bindModel = function <T extends Trait>(this: TraitRelation<unknown, T>, model: Model, targetModel: Model | null): void { // hook }; TraitRelation.prototype.unbindModel = function <T extends Trait>(this: TraitRelation<unknown, T>, model: Model): void { // hook }; TraitRelation.prototype.detectModel = function <T extends Trait>(this: TraitRelation<unknown, T>, model: Model): T | null { return null; }; TraitRelation.prototype.bindTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: Trait, target: Trait | null): void { // hook }; TraitRelation.prototype.unbindTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: Trait): void { // hook }; TraitRelation.prototype.detectTrait = function <T extends Trait>(this: TraitRelation<unknown, T>, trait: Trait): T | null { return null; }; TraitRelation.prototype.createTrait = function <T extends Trait>(this: TraitRelation<unknown, T>): T { let trait: T | undefined; const type = this.type; if (type !== void 0) { return type.create(); } if (trait === void 0 || trait === null) { let message = "Unable to create "; if (this.name.length !== 0) { message += this.name + " "; } message += "trait"; throw new Error(message); } return trait; }; TraitRelation.prototype.fromAny = function <T extends Trait>(this: TraitRelation<unknown, T>, value: AnyTrait<T>): T { const type = this.type; if (type !== void 0) { return type.fromAny(value); } else { return Trait.fromAny(value) as T; } }; Object.defineProperty(TraitRelation.prototype, "lazy", { get: function (this: TraitRelation): boolean { return false; }, configurable: true, }); Object.defineProperty(TraitRelation.prototype, "static", { get: function (this: TraitRelation): string | boolean { return true; }, configurable: true, }); TraitRelation.construct = function <F extends TraitRelation<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { fastener = _super.construct(fastenerClass, fastener, owner) as F; return fastener; }; TraitRelation.define = function <O, T extends Trait>(className: string, descriptor: TraitRelationDescriptor<O, T>): TraitRelationFactory<TraitRelation<any, T>> { let superClass = descriptor.extends as TraitRelationFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: TraitRelation<any, any>}, fastener: TraitRelation<O, T> | null, owner: O): TraitRelation<O, T> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } return fastener; }; return fastenerClass; }; return TraitRelation; })(Fastener);
the_stack
import { Message, RichTextMessage, RichTextNode } from '@comen/common'; import { identity } from 'rxjs'; import { map } from 'rxjs/operators'; import { ComenConfiguration } from '../config'; const EMOJI_START_TOKEN = ['(', '(']; const EMOJI_END_TOKEN = [')', ')', ',', ',', '.', ' ', '。', '/', '\\', '$', '¥', '-', '+', '*', '#', '@', '!', '~', '?', '=', '_', ';', '"', '“', '”', '|'] function emojiExpressionToken(charArr: string[]): [string, string] { let constructed = ''; //eslint-disable-next-line while (true) { if (charArr.length == 0) { return [constructed, '']; } const next = charArr.shift(); if (EMOJI_START_TOKEN.includes(next)) { charArr.unshift(next); return [constructed, '']; } if (EMOJI_END_TOKEN.includes(next)) { return [constructed, next]; } else { constructed += next; } } } export function emojiExpressionLexer(dict: (token: string) => string | null, content: string): RichTextNode[] { if (content.length == 0) { return [{ type: 'text', content: '' }]; } const nodes: RichTextNode[] = []; const charArr = Array.from(content); let constructedText = ''; //eslint-disable-next-line while (true) { if (charArr.length == 0) { constructedText && nodes.push({ type: 'text', content: constructedText }); break; } const next = charArr.shift(); if (EMOJI_START_TOKEN.includes(next)) { const [token, tokenEnd] = emojiExpressionToken(charArr); const url = dict(token); if (url != null) { //has emoji constructedText && nodes.push({ type: 'text', content: constructedText }); nodes.push({ type: 'emoji', url: url }); if (tokenEnd == ')' || tokenEnd == ')') { constructedText = ''; } else { constructedText = tokenEnd; } } else { constructedText += (next + token + tokenEnd); } } else { constructedText += next; } } return nodes; } function emojiMap(message: Message) { if (message.type == 'text') { const ret = emojiExpressionLexer((token) => { return EMOJI_MAP[token]; }, message.content); if (ret.some(x => x.type == 'emoji')) { return { ...message, type: 'richtext', richtext: { nodes: ret } } as RichTextMessage; } return message; } else { return message; } } export const emojiFilter = (config: ComenConfiguration) => { if (config.platform == 'bilibili') { return map(emojiMap); } return identity; }; /** * TODO: configurable emojis */ export const EMOJI_MAP = { 2021: 'http://i0.hdslb.com/bfs/emote/14d8996128d46dabd3a2ed6c172c8af918d7a5d2.png', 微笑: 'http://i0.hdslb.com/bfs/emote/685612eadc33f6bc233776c6241813385844f182.png', OK: 'http://i0.hdslb.com/bfs/emote/4683fd9ffc925fa6423110979d7dcac5eda297f4.png', 星星眼: 'http://i0.hdslb.com/bfs/emote/63c9d1a31c0da745b61cdb35e0ecb28635675db2.png', doge: 'http://i0.hdslb.com/bfs/emote/bba7c12aa51fed0199c241465560dfc2714c593e.png', 狗头: 'http://i0.hdslb.com/bfs/emote/bba7c12aa51fed0199c241465560dfc2714c593e.png', 妙啊: 'http://i0.hdslb.com/bfs/emote/b4cb77159d58614a9b787b91b1cd22a81f383535.png', 吃瓜: 'http://i0.hdslb.com/bfs/emote/4191ce3c44c2b3df8fd97c33f85d3ab15f4f3c84.png', 辣眼睛: 'http://i0.hdslb.com/bfs/emote/35d62c496d1e4ea9e091243fa812866f5fecc101.png', 滑稽: 'http://i0.hdslb.com/bfs/emote/d15121545a99ac46774f1f4465b895fe2d1411c3.png', 笑哭: 'http://i0.hdslb.com/bfs/emote/c3043ba94babf824dea03ce500d0e73763bf4f40.png', 呲牙: 'http://i0.hdslb.com/bfs/emote/b5a5898491944a4268360f2e7a84623149672eb6.png', 打call: 'http://i0.hdslb.com/bfs/emote/431432c43da3ee5aab5b0e4f8931953e649e9975.png', 歪嘴: 'http://i0.hdslb.com/bfs/emote/4384050fbab0586259acdd170b510fe262f08a17.png', 嫌弃: 'http://i0.hdslb.com/bfs/emote/de4c0783aaa60ec03de0a2b90858927bfad7154b.png', 喜欢: 'http://i0.hdslb.com/bfs/emote/8a10a4d73a89f665feff3d46ca56e83dc68f9eb8.png', 哦呼: 'http://i0.hdslb.com/bfs/emote/362bded07ea5434886271d23fa25f5d85d8af06c.png', 酸了: 'http://i0.hdslb.com/bfs/emote/92b1c8cbceea3ae0e8e32253ea414783e8ba7806.png', 大哭: 'http://i0.hdslb.com/bfs/emote/2caafee2e5db4db72104650d87810cc2c123fc86.png', 害羞: 'http://i0.hdslb.com/bfs/emote/9d2ec4e1fbd6cb1b4d12d2bbbdd124ccb83ddfda.png', 疑惑: 'http://i0.hdslb.com/bfs/emote/b7840db4b1f9f4726b7cb23c0972720c1698d661.png', 调皮: 'http://i0.hdslb.com/bfs/emote/8290b7308325e3179d2154327c85640af1528617.png', 喜极而泣: 'http://i0.hdslb.com/bfs/emote/485a7e0c01c2d70707daae53bee4a9e2e31ef1ed.png', 奸笑: 'http://i0.hdslb.com/bfs/emote/bb84906573472f0a84cebad1e9000eb6164a6f5a.png', 笑: 'http://i0.hdslb.com/bfs/emote/81edf17314cea3b48674312b4364df44d5c01f17.png', 偷笑: 'http://i0.hdslb.com/bfs/emote/6c49d226e76c42cd8002abc47b3112bc5a92f66a.png', 惊讶: 'http://i0.hdslb.com/bfs/emote/f8e9a59cad52ae1a19622805696a35f0a0d853f3.png', 捂脸: 'http://i0.hdslb.com/bfs/emote/6921bb43f0c634870b92f4a8ad41dada94a5296d.png', 阴险: 'http://i0.hdslb.com/bfs/emote/ba8d5f8e7d136d59aab52c40fd3b8a43419eb03c.png', 囧: 'http://i0.hdslb.com/bfs/emote/12e41d357a9807cc80ef1e1ed258127fcc791424.png', 呆: 'http://i0.hdslb.com/bfs/emote/33ad6000d9f9f168a0976bc60937786f239e5d8c.png', 抠鼻: 'http://i0.hdslb.com/bfs/emote/cb89184c97e3f6d50acfd7961c313ce50360d70f.png', 大笑: 'http://i0.hdslb.com/bfs/emote/ca94ad1c7e6dac895eb5b33b7836b634c614d1c0.png', 惊喜: 'http://i0.hdslb.com/bfs/emote/0afecaf3a3499479af946f29749e1a6c285b6f65.png', 无语: 'http://i0.hdslb.com/bfs/emote/44667b7d9349957e903b1b62cb91fb9b13720f04.png', 鼓掌: 'http://i0.hdslb.com/bfs/emote/895d1fc616b4b6c830cf96012880818c0e1de00d.png', 点赞: 'http://i0.hdslb.com/bfs/emote/1a67265993913f4c35d15a6028a30724e83e7d35.png', 尴尬: 'http://i0.hdslb.com/bfs/emote/cb321684ed5ce6eacdc2699092ab8fe7679e4fda.png', 灵魂出窍: 'http://i0.hdslb.com/bfs/emote/43d3db7d97343c01b47e22cfabeca84b4251f35a.png', 委屈: 'http://i0.hdslb.com/bfs/emote/d2f26cbdd6c96960320af03f5514c5b524990840.png', 傲娇: 'http://i0.hdslb.com/bfs/emote/010540d0f61220a0db4922e4a679a1d8eca94f4e.png', 冷: 'http://i0.hdslb.com/bfs/emote/cb0ebbd0668640f07ebfc0e03f7a18a8cd00b4ed.png', 疼: 'http://i0.hdslb.com/bfs/emote/905fd9a99ec316e353b9bd4ecd49a5f0a301eabf.png', 吓: 'http://i0.hdslb.com/bfs/emote/9c10c5ebc7bef27ec641b8a1877674e0c65fea5d.png', 生病: 'http://i0.hdslb.com/bfs/emote/0f25ce04ae1d7baf98650986454c634f6612cb76.png', 吐: 'http://i0.hdslb.com/bfs/emote/06946bfe71ac48a6078a0b662181bb5cad09decc.png', 捂眼: 'http://i0.hdslb.com/bfs/emote/c5c6d6982e1e53e478daae554b239f2b227b172b.png', 嘘声: 'http://i0.hdslb.com/bfs/emote/e64af664d20716e090f10411496998095f62f844.png', 思考: 'http://i0.hdslb.com/bfs/emote/cfa9b7e89e4bfe04bbcd34ccb1b0df37f4fa905c.png', 再见: 'http://i0.hdslb.com/bfs/emote/fc510306bae26c9aec7e287cdf201ded27b065b9.png', 翻白眼: 'http://i0.hdslb.com/bfs/emote/eba54707c7168925b18f6f8b1f48d532fe08c2b1.png', 哈欠: 'http://i0.hdslb.com/bfs/emote/888d877729cbec444ddbd1cf4c9af155a7a06086.png', 奋斗: 'http://i0.hdslb.com/bfs/emote/bb2060c15dba7d3fd731c35079d1617f1afe3376.png', 墨镜: 'http://i0.hdslb.com/bfs/emote/3a03aebfc06339d86a68c2d893303b46f4b85771.png', 难过: 'http://i0.hdslb.com/bfs/emote/a651db36701610aa70a781fa98c07c9789b11543.png', 撇嘴: 'http://i0.hdslb.com/bfs/emote/531863568e5668c5ac181d395508a0eeb1f0cda4.png', 抓狂: 'http://i0.hdslb.com/bfs/emote/4c87afff88c22439c45b79e9d2035d21d5622eba.png', 生气: 'http://i0.hdslb.com/bfs/emote/3195714219c4b582a4fb02033dd1519913d0246d.png', 口罩: 'http://i0.hdslb.com/bfs/emote/3ad2f66b151496d2a5fb0a8ea75f32265d778dd3.png', 鸡腿: 'http://i0.hdslb.com/bfs/emote/c7860392815d345fa69c4f00ef18d67dccfbd574.png', 月饼: 'http://i0.hdslb.com/bfs/emote/89b19c5730e08d6f12fadf6996de5bc2e52f81fe.png', 雪花: 'http://i0.hdslb.com/bfs/emote/a41813c4edf8782047e172c884ebd4507ce5e449.png', 视频卫星: 'http://i0.hdslb.com/bfs/emote/dce6fc7d6dfeafff01241924db60f8251cca5307.png', '11周年': 'http://i0.hdslb.com/bfs/emote/d3b2d5dc028c75ae4df379f4c3afbe186d0f6f9b.png', 干杯: 'http://i0.hdslb.com/bfs/emote/8da12d5f55a2c7e9778dcc05b40571979fe208e6.png', 爱心: 'http://i0.hdslb.com/bfs/emote/ed04066ea7124106d17ffcaf75600700e5442f5c.png', 锦鲤: 'http://i0.hdslb.com/bfs/emote/643d6c19c8164ffd89e3e9cdf093cf5d773d979c.png', 胜利: 'http://i0.hdslb.com/bfs/emote/b49fa9f4b1e7c3477918153b82c60b114d87347c.png', 加油: 'http://i0.hdslb.com/bfs/emote/c7aaeacb21e107292d3bb053e5abde4a4459ed30.png', 抱拳: 'http://i0.hdslb.com/bfs/emote/89516218158dbea18ab78e8873060bf95d33bbbe.png', 响指: 'http://i0.hdslb.com/bfs/emote/1b5c53cf14336903e1d2ae3527ca380a1256a077.png', 保佑: 'http://i0.hdslb.com/bfs/emote/fafe8d3de0dc139ebe995491d2dac458a865fb30.png', 支持: 'http://i0.hdslb.com/bfs/emote/3c210366a5585706c09d4c686a9d942b39feeb50.png', 拥抱: 'http://i0.hdslb.com/bfs/emote/41780a4254750cdaaccb20735730a36044e98ef3.png', 跪了: 'http://i0.hdslb.com/bfs/emote/f2b3aee7e521de7799d4e3aa379b01be032698ac.png', 怪我咯: 'http://i0.hdslb.com/bfs/emote/07cc6077f7f7d75b8d2c722dd9d9828a9fb9e46d.png', 黑洞: 'http://i0.hdslb.com/bfs/emote/e90ec4c799010f25391179118ccd9f66b3b279ba.png', 老鼠: 'http://i0.hdslb.com/bfs/emote/8e6fb491eb1bb0d5862e7ec8ccf9a3da12b6c155.png', 福到了: 'http://i0.hdslb.com/bfs/emote/5de5373d354c373cf1617b6b836f3a8d53c5a655.png', 'W-哈哈': 'http://i0.hdslb.com/bfs/emote/83d527303c8f62f494e6971c48836487e7d87b1b.png', '凛冬-生气': 'http://i0.hdslb.com/bfs/emote/d90bd2fbc13a3cb8d313f6d675f20caf109f60a7.png', '霜叶-疑问': 'http://i0.hdslb.com/bfs/emote/ada3aea8594e724511c1daad15fb3b23900d8e24.png', '煌-震撼': 'http://i0.hdslb.com/bfs/emote/7bb39ac289bc97fe52af047020a9bf324ecdebe1.png', 哭泣: 'http://i0.hdslb.com/bfs/emote/a61abafb8c39defc323b045f30072198007b1c89.png', 哈哈: 'http://i0.hdslb.com/bfs/emote/e6449b0bae13b8c97cc65976ff8cdc2c16be0015.png', 狗子: 'http://i0.hdslb.com/bfs/emote/6a997106af5bf490f22c80a7acf3be813ee755fc.png', 羞羞: 'http://i0.hdslb.com/bfs/emote/f4f9171e4d8c3f30827a8b96ea1ce1beb825ad50.png', 亲亲: 'http://i0.hdslb.com/bfs/emote/2f72bae7b834d499f259c833f7011d5ed8748fd1.png', 耍帅: 'http://i0.hdslb.com/bfs/emote/d7a38b08d1f1cc35b19c35041f29ffcc48808e87.png', 气愤: 'http://i0.hdslb.com/bfs/emote/069b029d17a086ab475fd331697a649e234850bb.png', 高兴: 'http://i0.hdslb.com/bfs/emote/416570a8aca7be12fb2c36e4b846906653f6d294.png', 知识增加: 'http://i0.hdslb.com/bfs/emote/142409b595982b8210b2958f3d340f3b47942645.png', 爷青回: 'http://i0.hdslb.com/bfs/emote/a26189ff1e681bddef7f6533f9aabe7604731a3e.png', 好家伙: 'http://i0.hdslb.com/bfs/emote/63ec80dea3066bd9f449ba999ba531fa61f7b4eb.png', 芜湖起飞: 'http://i0.hdslb.com/bfs/emote/78d04c6ce78a613c90d510cd45fe7e25c57ba00b.png', 梦幻联动: 'http://i0.hdslb.com/bfs/emote/4809416be5ca787c2ec3e897e4fd022a58da6e0e.png', 泪目: 'http://i0.hdslb.com/bfs/emote/bba3703ab90b7d16fe9dbcb85ed949db687f8331.png', 保护: 'http://i0.hdslb.com/bfs/emote/55f8f6445ca7c3170cdfc5b16036abf639ce9b57.png', 害怕: 'http://i0.hdslb.com/bfs/emote/d77e2de26da143249f0c0ad7a608c27152c985bf.png', 爱了爱了: 'http://i0.hdslb.com/bfs/emote/2a165b555ba20391316366c664ed7891883dc5aa.png', 吹爆: 'http://i0.hdslb.com/bfs/emote/b528220f9c37256ed6a37f05bf118e44b08b81e5.png', 三连: 'http://i0.hdslb.com/bfs/emote/21f15fe11b7a84d2f2121c16dec50a4e4556f865.png', 可以: 'http://i0.hdslb.com/bfs/emote/e08543c71202b36c590094417fcfbb80c3506cd8.png', 希望没事: 'http://i0.hdslb.com/bfs/emote/6c0d2e6c486d1ba5afd6204a96e102652464a01d.png', 打卡: 'http://i0.hdslb.com/bfs/emote/a9cf77c78e1b9b40aa3ed4862402fba008ee2f51.png', skr: 'http://i0.hdslb.com/bfs/emote/bd285ff94db16ad52557c3effe930d64663e8375.png', battle: 'http://i0.hdslb.com/bfs/emote/f2f81c8e47db6252becd633a5d1ee14e15df2ea8.png', DNA: 'http://i0.hdslb.com/bfs/emote/f6eb74f8230588f61a298af89061a7d75c5762e5.png', // "妙啊":"http://i0.hdslb.com/bfs/emote/0e98299d7decf5eaffad854977946075c3e91cb8.png", 这次一定: 'http://i0.hdslb.com/bfs/emote/a01ca28923daa7cc896c42f27deb4914e20dd572.png', AWSL: 'http://i0.hdslb.com/bfs/emote/c37f88cf799f9badf9d84b7671dc3dd98c0fc0c2.png', 递话筒: 'http://i0.hdslb.com/bfs/emote/98e6950e39fbb4dd1c576042063ca632074070ba.png', 你细品: 'http://i0.hdslb.com/bfs/emote/535e00658e7e47966f154d3a167fa2365ebc4321.png', 咕咕: 'http://i0.hdslb.com/bfs/emote/d8065c2e7ce48c929317a94553499a46fecc262a.png', 标准结局: 'http://i0.hdslb.com/bfs/emote/3de98174b510cf7dc5fd1bd08c5d881065e79137.png', 危: 'http://i0.hdslb.com/bfs/emote/5cc6c3357c4df544dd8de9d5c5c0cec97c7c9a56.png', 张三: 'http://i0.hdslb.com/bfs/emote/255a938f39cea625032b6650036b31aa26c50a3c.png', 害: 'http://i0.hdslb.com/bfs/emote/cbe798a194612958537c5282fcca7c3bcd2aa15c.png', 我裂开了: 'http://i0.hdslb.com/bfs/emote/29bd57ec4e8952880fea6c9e47aee924e91f10c4.png', 有内味了: 'http://i0.hdslb.com/bfs/emote/7ca61680a905b5b6e2e335c630e725b648b03b4d.png', 猛男必看: 'http://i0.hdslb.com/bfs/emote/c97064450528a0e45c7e7c365a15fbb13fd61d8c.png', 奥力给: 'http://i0.hdslb.com/bfs/emote/c9b8683827ec6c00fea5327c9bec14f581cef2aa.png', 问号: 'http://i0.hdslb.com/bfs/emote/c1d1e76c12180adc8558f47006fe0e7ded4154bb.png', 我哭了: 'http://i0.hdslb.com/bfs/emote/9e0b3877d649aaf6538fbdd3f937e240a9d808e4.png', 高产: 'http://i0.hdslb.com/bfs/emote/9db817cba4a7f4a42398f3b2ec7c0a8e0c247c42.png', 我酸了: 'http://i0.hdslb.com/bfs/emote/a8cbf3f6b8cd9377eeb15b9172f3cd683b2e4650.png', 真香: 'http://i0.hdslb.com/bfs/emote/e68497c775feaac1c3b1a6cd63a50cfb11b767c4.png', 我全都要: 'http://i0.hdslb.com/bfs/emote/d424d1ad8d14c1c9b8367842bc68c658b9229bc1.png', 神仙UP: 'http://i0.hdslb.com/bfs/emote/a49e0d0db1e7d35a0f7411be13208951ab448f03.png', 你币有了: 'http://i0.hdslb.com/bfs/emote/84820c2b147a8ca02f3c4006b63f76c6313cbfa0.png', 不愧是你: 'http://i0.hdslb.com/bfs/emote/9ff2e356797c57ee3b1675ade0883d2d2247be9b.png', 锤: 'http://i0.hdslb.com/bfs/emote/35668cc12ae25b9545420e4a85bf21a0bfc03e5d.png', 秀: 'http://i0.hdslb.com/bfs/emote/50782fbf5d9b7f48f9467b5c53932981e321eedc.png', 爷关更: 'http://i0.hdslb.com/bfs/emote/faad40c56447f1f8abcb4045c17ce159d113d1fd.png', 有生之年: 'http://i0.hdslb.com/bfs/emote/f41fdafe2d0fbb8e8bc1598d2cf37e355560103a.png', 镇站之宝: 'http://i0.hdslb.com/bfs/emote/24e7a6a6e6383c987215fb905e3ee070aca259b5.png', 我太南了: 'http://i0.hdslb.com/bfs/emote/a523f3e4c63e4db1232365765d0ec452f83be97e.png', 完结撒花: 'http://i0.hdslb.com/bfs/emote/ea9db62ff5bca8e069cd70c4233353a802835422.png', 大师球: 'http://i0.hdslb.com/bfs/emote/f30089248dd137c568edabcb07cf67e0f6e98cf3.png', 知识盲区: 'http://i0.hdslb.com/bfs/emote/ccc94600b321a28116081e49ecedaa4ee8728312.png', 狼火: 'http://i0.hdslb.com/bfs/emote/33ccd3617bfa89e9d1498b13b7542b63f163e5de.png', 你可真星: 'http://i0.hdslb.com/bfs/emote/54c8ddff400abfe388060cabfbb579280fdea1be.png' }
the_stack
import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; }; export type Query = { __typename?: 'Query'; getAccessList: Array<Scalars['String']>; projects?: Maybe<Array<Maybe<Project>>>; user?: Maybe<User>; users?: Maybe<Array<Maybe<User>>>; }; export type Project = { __typename?: 'Project'; id?: Maybe<Scalars['Int']>; title?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['String']>; }; export type UserInput = { email: Scalars['String']; name?: Maybe<Scalars['String']>; password?: Maybe<Scalars['String']>; }; export type AdminUserInput = { id: Scalars['Int']; email?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; accessList?: Maybe<Array<Scalars['String']>>; }; export type CredentialsInput = { email: Scalars['String']; password?: Maybe<Scalars['String']>; }; export type EmailInput = { email: Scalars['String']; }; export type NewPasswordInput = { password: Scalars['String']; token: Scalars['String']; }; export enum AuthServices { Google = 'GOOGLE', } export type SocialLoginInput = { service: AuthServices; token: Scalars['String']; }; export type User = { __typename?: 'User'; id?: Maybe<Scalars['Int']>; email?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; accessList?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type AuthResult = { __typename?: 'AuthResult'; success?: Maybe<Scalars['Boolean']>; token?: Maybe<Scalars['String']>; message?: Maybe<Scalars['String']>; }; export type Mutation = { __typename?: 'Mutation'; createUser?: Maybe<User>; updateUser?: Maybe<User>; register?: Maybe<AuthResult>; login?: Maybe<AuthResult>; forgotPassword?: Maybe<AuthResult>; resetPassword?: Maybe<AuthResult>; validateSocialLogin?: Maybe<AuthResult>; }; export type MutationCreateUserArgs = { user: UserInput; }; export type MutationUpdateUserArgs = { user: AdminUserInput; }; export type MutationRegisterArgs = { user: UserInput; }; export type MutationLoginArgs = { credentials: CredentialsInput; }; export type MutationForgotPasswordArgs = { credentials: EmailInput; }; export type MutationResetPasswordArgs = { credentials: NewPasswordInput; }; export type MutationValidateSocialLoginArgs = { credentials: SocialLoginInput; }; export type ForgotPasswordMutationVariables = Exact<{ credentials: EmailInput; }>; export type ForgotPasswordMutation = { __typename?: 'Mutation' } & { forgotPassword?: Maybe< { __typename?: 'AuthResult' } & Pick<AuthResult, 'success' | 'message'> >; }; export type ResetPasswordMutationVariables = Exact<{ credentials: NewPasswordInput; }>; export type ResetPasswordMutation = { __typename?: 'Mutation' } & { resetPassword?: Maybe< { __typename?: 'AuthResult' } & Pick<AuthResult, 'success' | 'message' | 'token'> >; }; export type LoginMutationVariables = Exact<{ credentials: CredentialsInput; }>; export type LoginMutation = { __typename?: 'Mutation' } & { login?: Maybe< { __typename?: 'AuthResult' } & Pick<AuthResult, 'success' | 'token' | 'message'> >; }; export type RegisterMutationVariables = Exact<{ user: UserInput; }>; export type RegisterMutation = { __typename?: 'Mutation' } & { register?: Maybe< { __typename?: 'AuthResult' } & Pick<AuthResult, 'success' | 'token' | 'message'> >; }; export type ValidateSocialLoginMutationVariables = Exact<{ credentials: SocialLoginInput; }>; export type ValidateSocialLoginMutation = { __typename?: 'Mutation' } & { validateSocialLogin?: Maybe< { __typename?: 'AuthResult' } & Pick<AuthResult, 'success' | 'token' | 'message'> >; }; export type UserQueryVariables = Exact<{ [key: string]: never }>; export type UserQuery = { __typename?: 'Query' } & { user?: Maybe<{ __typename?: 'User' } & Pick<User, 'email' | 'name'>>; }; export const ForgotPasswordDocument = gql` mutation forgotPassword($credentials: EmailInput!) { forgotPassword(credentials: $credentials) { success message } } `; export type ForgotPasswordMutationFn = Apollo.MutationFunction< ForgotPasswordMutation, ForgotPasswordMutationVariables >; /** * __useForgotPasswordMutation__ * * To run a mutation, you first call `useForgotPasswordMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useForgotPasswordMutation` 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 [forgotPasswordMutation, { data, loading, error }] = useForgotPasswordMutation({ * variables: { * credentials: // value for 'credentials' * }, * }); */ export function useForgotPasswordMutation( baseOptions?: Apollo.MutationHookOptions< ForgotPasswordMutation, ForgotPasswordMutationVariables >, ) { return Apollo.useMutation<ForgotPasswordMutation, ForgotPasswordMutationVariables>( ForgotPasswordDocument, baseOptions, ); } export type ForgotPasswordMutationHookResult = ReturnType< typeof useForgotPasswordMutation >; export type ForgotPasswordMutationResult = Apollo.MutationResult<ForgotPasswordMutation>; export type ForgotPasswordMutationOptions = Apollo.BaseMutationOptions< ForgotPasswordMutation, ForgotPasswordMutationVariables >; export const ResetPasswordDocument = gql` mutation resetPassword($credentials: NewPasswordInput!) { resetPassword(credentials: $credentials) { success message token } } `; export type ResetPasswordMutationFn = Apollo.MutationFunction< ResetPasswordMutation, ResetPasswordMutationVariables >; /** * __useResetPasswordMutation__ * * To run a mutation, you first call `useResetPasswordMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useResetPasswordMutation` 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 [resetPasswordMutation, { data, loading, error }] = useResetPasswordMutation({ * variables: { * credentials: // value for 'credentials' * }, * }); */ export function useResetPasswordMutation( baseOptions?: Apollo.MutationHookOptions< ResetPasswordMutation, ResetPasswordMutationVariables >, ) { return Apollo.useMutation<ResetPasswordMutation, ResetPasswordMutationVariables>( ResetPasswordDocument, baseOptions, ); } export type ResetPasswordMutationHookResult = ReturnType<typeof useResetPasswordMutation>; export type ResetPasswordMutationResult = Apollo.MutationResult<ResetPasswordMutation>; export type ResetPasswordMutationOptions = Apollo.BaseMutationOptions< ResetPasswordMutation, ResetPasswordMutationVariables >; export const LoginDocument = gql` mutation login($credentials: CredentialsInput!) { login(credentials: $credentials) { success token message } } `; export type LoginMutationFn = Apollo.MutationFunction< LoginMutation, LoginMutationVariables >; /** * __useLoginMutation__ * * To run a mutation, you first call `useLoginMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useLoginMutation` 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 [loginMutation, { data, loading, error }] = useLoginMutation({ * variables: { * credentials: // value for 'credentials' * }, * }); */ export function useLoginMutation( baseOptions?: Apollo.MutationHookOptions<LoginMutation, LoginMutationVariables>, ) { return Apollo.useMutation<LoginMutation, LoginMutationVariables>( LoginDocument, baseOptions, ); } export type LoginMutationHookResult = ReturnType<typeof useLoginMutation>; export type LoginMutationResult = Apollo.MutationResult<LoginMutation>; export type LoginMutationOptions = Apollo.BaseMutationOptions< LoginMutation, LoginMutationVariables >; export const RegisterDocument = gql` mutation register($user: UserInput!) { register(user: $user) { success token message } } `; export type RegisterMutationFn = Apollo.MutationFunction< RegisterMutation, RegisterMutationVariables >; /** * __useRegisterMutation__ * * To run a mutation, you first call `useRegisterMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRegisterMutation` 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 [registerMutation, { data, loading, error }] = useRegisterMutation({ * variables: { * user: // value for 'user' * }, * }); */ export function useRegisterMutation( baseOptions?: Apollo.MutationHookOptions<RegisterMutation, RegisterMutationVariables>, ) { return Apollo.useMutation<RegisterMutation, RegisterMutationVariables>( RegisterDocument, baseOptions, ); } export type RegisterMutationHookResult = ReturnType<typeof useRegisterMutation>; export type RegisterMutationResult = Apollo.MutationResult<RegisterMutation>; export type RegisterMutationOptions = Apollo.BaseMutationOptions< RegisterMutation, RegisterMutationVariables >; export const ValidateSocialLoginDocument = gql` mutation validateSocialLogin($credentials: SocialLoginInput!) { validateSocialLogin(credentials: $credentials) { success token message } } `; export type ValidateSocialLoginMutationFn = Apollo.MutationFunction< ValidateSocialLoginMutation, ValidateSocialLoginMutationVariables >; /** * __useValidateSocialLoginMutation__ * * To run a mutation, you first call `useValidateSocialLoginMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useValidateSocialLoginMutation` 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 [validateSocialLoginMutation, { data, loading, error }] = useValidateSocialLoginMutation({ * variables: { * credentials: // value for 'credentials' * }, * }); */ export function useValidateSocialLoginMutation( baseOptions?: Apollo.MutationHookOptions< ValidateSocialLoginMutation, ValidateSocialLoginMutationVariables >, ) { return Apollo.useMutation< ValidateSocialLoginMutation, ValidateSocialLoginMutationVariables >(ValidateSocialLoginDocument, baseOptions); } export type ValidateSocialLoginMutationHookResult = ReturnType< typeof useValidateSocialLoginMutation >; export type ValidateSocialLoginMutationResult = Apollo.MutationResult<ValidateSocialLoginMutation>; export type ValidateSocialLoginMutationOptions = Apollo.BaseMutationOptions< ValidateSocialLoginMutation, ValidateSocialLoginMutationVariables >; export const UserDocument = gql` query user { user { email name } } `; /** * __useUserQuery__ * * To run a query within a React component, call `useUserQuery` and pass it any options that fit your needs. * When your component renders, `useUserQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useUserQuery({ * variables: { * }, * }); */ export function useUserQuery( baseOptions?: Apollo.QueryHookOptions<UserQuery, UserQueryVariables>, ) { return Apollo.useQuery<UserQuery, UserQueryVariables>(UserDocument, baseOptions); } export function useUserLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<UserQuery, UserQueryVariables>, ) { return Apollo.useLazyQuery<UserQuery, UserQueryVariables>(UserDocument, baseOptions); } export type UserQueryHookResult = ReturnType<typeof useUserQuery>; export type UserLazyQueryHookResult = ReturnType<typeof useUserLazyQuery>; export type UserQueryResult = Apollo.QueryResult<UserQuery, UserQueryVariables>;
the_stack
import { isAbsolute, resolve } from 'path'; import { cachedLookup, normalizeSlashes } from './util'; import type * as _ts from 'typescript'; import type { TSCommon, TSInternal } from './ts-compiler-types'; /** @internal */ export const createTsInternals = cachedLookup(createTsInternalsUncached); /** * Given a reference to the TS compiler, return some TS internal functions that we * could not or did not want to grab off the `ts` object. * These have been copy-pasted from TS's source and tweaked as necessary. * * NOTE: This factory returns *only* functions which need a reference to the TS * compiler. Other functions do not need a reference to the TS compiler so are * exported directly from this file. */ function createTsInternalsUncached(_ts: TSCommon) { const ts = _ts as TSCommon & TSInternal; /** * Copied from: * https://github.com/microsoft/TypeScript/blob/v4.3.2/src/compiler/commandLineParser.ts#L2821-L2846 */ function getExtendsConfigPath( extendedConfig: string, host: _ts.ParseConfigHost, basePath: string, errors: _ts.Push<_ts.Diagnostic>, createDiagnostic: ( message: _ts.DiagnosticMessage, arg1?: string ) => _ts.Diagnostic ) { extendedConfig = normalizeSlashes(extendedConfig); if ( isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, './') || startsWith(extendedConfig, '../') ) { let extendedConfigPath = getNormalizedAbsolutePath( extendedConfig, basePath ); if ( !host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ts.Extension.Json) ) { extendedConfigPath = `${extendedConfigPath}.json`; if (!host.fileExists(extendedConfigPath)) { errors.push( createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig) ); return undefined; } } return extendedConfigPath; } // If the path isn't a rooted or relative path, resolve like a module const resolved = ts.nodeModuleNameResolver( extendedConfig, combinePaths(basePath, 'tsconfig.json'), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true ); if (resolved.resolvedModule) { return resolved.resolvedModule.resolvedFileName; } errors.push( createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig) ); return undefined; } return { getExtendsConfigPath }; } // These functions have alternative implementation to avoid copying too much from TS function isRootedDiskPath(path: string) { return isAbsolute(path); } function combinePaths(path: string, ...paths: (string | undefined)[]): string { return normalizeSlashes( resolve(path, ...(paths.filter((path) => path) as string[])) ); } function getNormalizedAbsolutePath( fileName: string, currentDirectory: string | undefined ) { return normalizeSlashes( currentDirectory != null ? resolve(currentDirectory!, fileName) : resolve(fileName) ); } function startsWith(str: string, prefix: string): boolean { return str.lastIndexOf(prefix, 0) === 0; } function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. const reservedCharacterPattern = /[^\w\s\/]/g; /** * @internal * See also: getRegularExpressionForWildcard, which seems to do almost the same thing */ export function getPatternFromSpec(spec: string, basePath: string) { const pattern = spec && getSubPatternFromSpec(spec, basePath, excludeMatcher); return pattern && `^(${pattern})${'($|/)'}`; } function getSubPatternFromSpec( spec: string, basePath: string, { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter, }: WildcardMatcher ): string { let subpattern = ''; let hasWrittenComponent = false; const components = getNormalizedPathComponents(spec, basePath); const lastComponent = last(components); // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. components[0] = removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push('**', '*'); } let optionalCount = 0; for (let component of components) { if (component === '**') { subpattern += doubleAsteriskRegexFragment; } else { if (hasWrittenComponent) { subpattern += directorySeparator; } subpattern += component.replace( reservedCharacterPattern, replaceWildcardCharacter ); } hasWrittenComponent = true; } while (optionalCount > 0) { subpattern += ')?'; optionalCount--; } return subpattern; } interface WildcardMatcher { singleAsteriskRegexFragment: string; doubleAsteriskRegexFragment: string; replaceWildcardCharacter: (match: string) => string; } const directoriesMatcher: WildcardMatcher = { singleAsteriskRegexFragment: '[^/]*', /** * Regex for the ** wildcard. Matches any num of subdirectories. When used for including * files or directories, does not match subdirectories that start with a . character */ doubleAsteriskRegexFragment: `(/[^/.][^/]*)*?`, replaceWildcardCharacter: (match) => replaceWildcardCharacter( match, directoriesMatcher.singleAsteriskRegexFragment ), }; const excludeMatcher: WildcardMatcher = { singleAsteriskRegexFragment: '[^/]*', doubleAsteriskRegexFragment: '(/.+?)?', replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment), }; function getNormalizedPathComponents( path: string, currentDirectory: string | undefined ) { return reducePathComponents(getPathComponents(path, currentDirectory)); } function getPathComponents(path: string, currentDirectory = '') { path = combinePaths(currentDirectory, path); return pathComponents(path, getRootLength(path)); } function reducePathComponents(components: readonly string[]) { if (!some(components)) return []; const reduced = [components[0]]; for (let i = 1; i < components.length; i++) { const component = components[i]; if (!component) continue; if (component === '.') continue; if (component === '..') { if (reduced.length > 1) { if (reduced[reduced.length - 1] !== '..') { reduced.pop(); continue; } } else if (reduced[0]) continue; } reduced.push(component); } return reduced; } function getRootLength(path: string) { const rootLength = getEncodedRootLength(path); return rootLength < 0 ? ~rootLength : rootLength; } function getEncodedRootLength(path: string): number { if (!path) return 0; const ch0 = path.charCodeAt(0); // POSIX or UNC if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) { if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\") const p1 = path.indexOf( ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2 ); if (p1 < 0) return path.length; // UNC: "//server" or "\\server" return p1 + 1; // UNC: "//server/" or "\\server\" } // DOS if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) { const ch2 = path.charCodeAt(2); if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\" if (path.length === 2) return 2; // DOS: "c:" (but not "c:d") } // URL const schemeEnd = path.indexOf(urlSchemeSeparator); if (schemeEnd !== -1) { const authorityStart = schemeEnd + urlSchemeSeparator.length; const authorityEnd = path.indexOf(directorySeparator, authorityStart); if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" // For local "file" URLs, include the leading DOS volume (if present). // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a // special case interpreted as "the machine from which the URL is being interpreted". const scheme = path.slice(0, schemeEnd); const authority = path.slice(authorityStart, authorityEnd); if ( scheme === 'file' && (authority === '' || authority === 'localhost') && isVolumeCharacter(path.charCodeAt(authorityEnd + 1)) ) { const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd( path, authorityEnd + 2 ); if (volumeSeparatorEnd !== -1) { if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) { // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" return ~(volumeSeparatorEnd + 1); } if (volumeSeparatorEnd === path.length) { // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" // but not "file:///c:d" or "file:///c%3ad" return ~volumeSeparatorEnd; } } } return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" } return ~path.length; // URL: "file://server", "http://server" } // relative return 0; } function ensureTrailingDirectorySeparator(path: string) { if (!hasTrailingDirectorySeparator(path)) { return path + directorySeparator; } return path; } function hasTrailingDirectorySeparator(path: string) { return ( path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)) ); } function isAnyDirectorySeparator(charCode: number): boolean { return ( charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash ); } function removeTrailingDirectorySeparator(path: string) { if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } const directorySeparator = '/'; const altDirectorySeparator = '\\'; const urlSchemeSeparator = '://'; function isVolumeCharacter(charCode: number) { return ( (charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) || (charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z) ); } function getFileUrlVolumeSeparatorEnd(url: string, start: number) { const ch0 = url.charCodeAt(start); if (ch0 === CharacterCodes.colon) return start + 1; if ( ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3 ) { const ch2 = url.charCodeAt(start + 2); if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3; } return -1; } function some<T>(array: readonly T[] | undefined): array is readonly T[]; function some<T>( array: readonly T[] | undefined, predicate: (value: T) => boolean ): boolean; function some<T>( array: readonly T[] | undefined, predicate?: (value: T) => boolean ): boolean { if (array) { if (predicate) { for (const v of array) { if (predicate(v)) { return true; } } } else { return array.length > 0; } } return false; } /* @internal */ const enum CharacterCodes { _3 = 0x33, a = 0x61, z = 0x7a, A = 0x41, Z = 0x5a, asterisk = 0x2a, // * backslash = 0x5c, // \ colon = 0x3a, // : percent = 0x25, // % question = 0x3f, // ? slash = 0x2f, // / } function pathComponents(path: string, rootLength: number) { const root = path.substring(0, rootLength); const rest = path.substring(rootLength).split(directorySeparator); if (rest.length && !lastOrUndefined(rest)) rest.pop(); return [root, ...rest]; } function lastOrUndefined<T>(array: readonly T[]): T | undefined { return array.length === 0 ? undefined : array[array.length - 1]; } function last<T>(array: readonly T[]): T { // Debug.assert(array.length !== 0); return array[array.length - 1]; } function replaceWildcardCharacter( match: string, singleAsteriskRegexFragment: string ) { return match === '*' ? singleAsteriskRegexFragment : match === '?' ? '[^/]' : '\\' + match; } /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. */ function isImplicitGlob(lastPathComponent: string): boolean { return !/[.*?]/.test(lastPathComponent); }
the_stack
import assert from 'assert'; import { r } from '../src'; import config from './config'; import { uuid } from './util/common'; describe('pool legacy', () => { let dbName: string; let tableName: string; let pks: string[]; before(async () => { await r.connectPool(config); dbName = uuid(); tableName = uuid(); const result1 = await r.dbCreate(dbName).run(); assert.equal(result1.dbs_created, 1); const result2 = await r .db(dbName) .tableCreate(tableName) .run(); assert.equal(result2.tables_created, 1); const result3 = await r .db(dbName) .table(tableName) .insert(Array(100).fill({})) .run(); assert.equal(result3.inserted, 100); pks = result3.generated_keys; }); after(async () => { await r.getPoolMaster().drain(); }); it('`db` should work', async () => { const result = await r .db(dbName) .info() .run(); assert.equal(result.name, dbName); assert.equal(result.type, 'DB'); }); it('`table` should work', async () => { const result1 = await r .db(dbName) .table(tableName) .info() .run(); assert.equal(result1.name, tableName); assert.equal(result1.type, 'TABLE'); assert.equal(result1.primary_key, 'id'); assert.equal(result1.db.name, dbName); const result2 = await r .db(dbName) .table(tableName) .run(); assert.equal(result2.length, 100); }); it('`table` should work with readMode', async () => { const result1 = await r .db(dbName) .table(tableName, { readMode: 'majority' }) .run(); assert.equal(result1.length, 100); const result2 = await r .db(dbName) .table(tableName, { readMode: 'majority' }) .run(); assert.equal(result2.length, 100); }); it('`table` should throw with non valid otpions', async () => { try { await r .db(dbName) // @ts-ignore .table(tableName, { nonValidKey: false }) .run(); assert.fail('should throw'); } catch (e) { assert( e.message.startsWith( 'Unrecognized optional argument `non_valid_key` in:' ) ); } }); it('`get` should work', async () => { const result = await r .db(dbName) .table(tableName) .get(pks[0]) .run(); assert.deepEqual(result, { id: pks[0] }); }); it('`get` should throw if no argument is passed', async () => { try { // @ts-ignore await r .db(dbName) .table(tableName) .get() .run(); assert.fail('should throw'); } catch (e) { // assert(e instanceof r.Error.ReqlDriverError) assert(e instanceof Error); assert.equal( e.message, '`get` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`getAll` should work with multiple values - primary key', async () => { let table = r.db(dbName).table(tableName); let query = table.getAll.apply(table, pks); let result = await query.run(); assert.equal(result.length, 100); table = r.db(dbName).table(tableName); query = table.getAll.apply(table, pks.slice(0, 50)); result = await query.run(); assert.equal(result.length, 50); }); it('`getAll` should work with no argument - primary key', async () => { // @ts-ignore const result = await r .db(dbName) .table(tableName) .getAll() .run(); assert.equal(result.length, 0); }); it('`getAll` should work with no argument - index', async () => { const result = await r .db(dbName) .table(tableName) .getAll({ index: 'id' }) .run(); assert.equal(result.length, 0); }); it('`getAll` should work with multiple values - secondary index 1', async () => { const result1 = await r .db(dbName) .table(tableName) .update({ field: 0 }) .run(); assert.equal(result1.replaced, 100); const result2 = await r .db(dbName) .table(tableName) .sample(20) .update({ field: 10 }) .run(); assert.equal(result2.replaced, 20); const result3 = await r .db(dbName) .table(tableName) .indexCreate('field') .run(); assert.deepEqual(result3, { created: 1 }); const result4 = await r .db(dbName) .table(tableName) .indexWait('field') .pluck('index', 'ready') .run(); assert.deepEqual(result4, [{ index: 'field', ready: true }]); const result5 = await r .db(dbName) .table(tableName) .getAll(10, { index: 'field' }) .run(); assert(result5); assert.equal(result5.length, 20); }); it('`getAll` should return native dates (and cursor should handle them)', async () => { await r .db(dbName) .table(tableName) .insert({ field: -1, date: r.now() }) .run(); const result1 = await r .db(dbName) .table(tableName) .getAll(-1, { index: 'field' }) .run(); assert(result1[0].date instanceof Date); // Clean for later await r .db(dbName) .table(tableName) .getAll(-1, { index: 'field' }) .delete() .run(); }); it('`getAll` should work with multiple values - secondary index 2', async () => { const result1 = await r .db(dbName) .table(tableName) .indexCreate('fieldAddOne', doc => doc('field').add(1)) .run(); assert.deepEqual(result1, { created: 1 }); const result2 = await r .db(dbName) .table(tableName) .indexWait('fieldAddOne') .pluck('index', 'ready') .run(); assert.deepEqual(result2, [{ index: 'fieldAddOne', ready: true }]); const result3 = await r .db(dbName) .table(tableName) .getAll(11, { index: 'fieldAddOne' }) .run(); assert(result3); assert.equal(result3.length, 20); }); it('`between` should wrok -- secondary index', async () => { const result = await r .db(dbName) .table(tableName) .between(5, 20, { index: 'fieldAddOne' }) .run(); assert(result); assert.equal(result.length, 20); }); it('`between` should wrok -- all args', async () => { const result = await r .db(dbName) .table(tableName) .between(5, 20, { index: 'fieldAddOne', leftBound: 'open', rightBound: 'closed' }) .run(); assert(result); assert.equal(result.length, 20); }); it('`between` should throw if no argument is passed', async () => { try { // @ts-ignore await r .db(dbName) .table(tableName) .between() .run(); assert.fail('should throw'); } catch (e) { // assert(e instanceof r.Error.ReqlDriverError) assert(e instanceof Error); assert.equal( e.message, '`between` takes at least 2 arguments, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`between` should throw if non valid arg', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .between(1, 2, { nonValidKey: true }) .run(); assert.fail('should throw'); } catch (e) { // assert(e instanceof r.Error.ReqlDriverError) assert(e instanceof Error); assert( e.message.startsWith( 'Unrecognized optional argument `non_valid_key` in:' ) ); } }); it('`filter` should work -- with an object', async () => { const result = await r .db(dbName) .table(tableName) .filter({ field: 10 }) .run(); assert(result); assert.equal(result.length, 20); }); it('`filter` should work -- with an object -- looking for an undefined field', async () => { const result = await r .db(dbName) .table(tableName) .filter({ nonExistingField: 10 }) .run(); assert(result); assert.equal(result.length, 0); }); it('`filter` should work -- with an anonymous function', async () => { const result = await r .db(dbName) .table(tableName) .filter(doc => doc('field').eq(10)) .run(); assert(result); assert.equal(result.length, 20); }); it('`filter` should work -- default true', async () => { const result = await r .db(dbName) .table(tableName) .filter({ nonExistingField: 10 }, { default: true }) .run(); assert(result); assert.equal(result.length, 100); }); it('`filter` should work -- default false', async () => { const result = await r .db(dbName) .table(tableName) .filter({ nonExistingField: 10 }, { default: false }) .run(); assert(result); assert.equal(result.length, 0); }); it('`filter` should work -- default false', async () => { try { await r .expr([{ a: 1 }, {}]) .filter(r.row('a'), { default: r.error() }) .run(); assert.fail('should throw'); } catch (e) { assert(e.message.match(/^No attribute `a` in object:/)); } }); it('`filter` should throw if no argument is passed', async () => { try { // @ts-ignore await r .db(dbName) .table(tableName) .filter() .run(); assert.fail('should throw'); } catch (e) { // assert(e instanceof r.Error.ReqlDriverError) assert(e instanceof Error); assert.equal( e.message, '`filter` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`filter` should throw with a non valid option', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .filter(() => true, { nonValidKey: false }) .run(); assert.fail('should throw'); } catch (e) { assert( e.message.startsWith( 'Unrecognized optional argument `non_valid_key` in:' ) ); } }); });
the_stack
import * as React from 'react'; import * as strings from 'ControlStrings'; import styles from './RteColorPicker.module.scss'; import SwatchColorPickerGroup from './SwatchColorPickerGroup'; import { IRteColorPickerProps, IRteColorPickerState } from './RteColorPicker.types'; import { DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { TooltipHost } from 'office-ui-fabric-react/lib/Tooltip'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { Callout } from 'office-ui-fabric-react/lib/Callout'; import { ISwatchColor } from './SwatchColorPickerGroup.types'; import { ThemeColorHelper } from '../../common/utilities/ThemeColorHelper'; export default class RteColorPicker extends React.Component<IRteColorPickerProps, IRteColorPickerState> { private wrapperRef: any = undefined; constructor(props: IRteColorPickerProps) { super(props); this.state = { isCalloutVisible: false }; } /** * Default React render method */ public render(): React.ReactElement<IRteColorPickerProps> { const { buttonLabel, defaultButtonLabel, fillThemeColor, id, previewColor } = this.props; return ( <div> <div ref={(ref) => this.wrapperRef = ref}> <TooltipHost content={buttonLabel} id={id} calloutProps={{ gapSpace: 0 }}> <DefaultButton className={styles.colorPickerButton} aria-describedby={id} onClick={() => this.handleColorChanged(previewColor)}> {/* Added border to white */} <svg className={`${styles.previewSvg} ${(previewColor === "rgba(0, 0, 0, 0)" || previewColor === "#ffffff") ? styles.border : ""}`} fill={previewColor} viewBox="0 0 20 20"> <rect className={styles.previewRectangle} width="100%" height="100%"></rect> </svg> <div className={styles.buttonLabel}>{buttonLabel}</div> <Icon iconName="CaretDownSolid8" className={styles.previewIcon} /> </DefaultButton> </TooltipHost> </div> <Callout isBeakVisible={false} directionalHint={4} className={styles.pickerCallout} setInitialFocus={true} gapSpace={0} role={"alertdialog"} hidden={!this.state.isCalloutVisible} target={this.wrapperRef} onDismiss={() => this.setState({ isCalloutVisible: false })}> <TooltipHost content={defaultButtonLabel} id={`${id}DefaultButton`} calloutProps={{ gapSpace: 0 }}> <DefaultButton className={styles.colorPickerButton} aria-describedby={`${id}DefaultButton`} onClick={this.handleSwitchToDefault}> <svg className={`${styles.previewSvg} ${styles.defaultSvg} ${fillThemeColor ? styles.fillThemeColor : styles.fillDefaultColor} ${fillThemeColor ? "" : styles.border}`} viewBox="0 0 20 20"> <rect className={styles.previewRectangle} width="100%" height="100%"></rect> </svg> <div className={styles.buttonLabel}>{defaultButtonLabel}</div> </DefaultButton> </TooltipHost> { this.props.colorPickerGroups.map(cpg => { return (this.getSwatchColorPickerGroup(cpg)); }) } </Callout> </div> ); } /** * Handle switch to default */ private handleSwitchToDefault = () => { this.setState({ isCalloutVisible: !this.state.isCalloutVisible }); this.props.switchToDefaultColor(); } /** * Handle color change */ private handleColorChanged = (color: string) => { this.setState({ isCalloutVisible: !this.state.isCalloutVisible }); this.props.onColorChanged(color); } /** * Get swatch color picker group */ private getSwatchColorPickerGroup = (pickerGroup: string) => { let groupName: string = undefined; switch (pickerGroup) { case "themeColors": groupName = strings.ThemeColorsGroupName; break; case "highlightColors": groupName = strings.HighlightColorsGroupName; break; case "standardColors": groupName = strings.StandardColorsGroupName; break; case "customColors": groupName = strings.CustomColorsGroupName; break; default: groupName = strings.HighlightColorsGroupName; break; } let groupColors: ISwatchColor[] = []; switch (pickerGroup) { case "themeColors": groupColors = [ { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorDarker), id: "#1c561c", label: strings.ThemeColorDarker }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorDark), id: "#267426", label: strings.ThemeColorDark }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorDarkAlt), id: "#2d8a2d", label: strings.ThemeColorDarkAlt }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorPrimary), id: "#339933", label: strings.ThemeColorPrimary }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorSecondary), id: "#44a544", label: strings.ThemeColorSecondary }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorTertiary), id: "#a6a6a6", label: strings.ThemeColorTertiary }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorNeutralSecondary), id: "#666666", label: strings.ThemeColorNeutralSecondary }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorNeutralPrimaryAlt), id: "#3c3c3c", label: strings.ThemeColorNeutralPrimaryAlt }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorNeutralPrimary), id: "#333333", label: strings.ThemeColorNeutralPrimary }, { color: ThemeColorHelper.GetThemeColor(styles.ThemeColorNeutralDark), id: "#212121", label: strings.ThemeColorNeutralDark } ]; break; case "highlightColors": groupColors = [ { color: "#FFFF00", id: "#FFFF00", label: strings.HighlightColorYellow }, { color: "#00FF00", id: "#00FF00", label: strings.HighlightColorGreen }, { color: "#00FFFF", id: "#00FFFF", label: strings.HighlightColorAqua }, { color: "#FF00FF", id: "#FF00FF", label: strings.HighlightColorMagenta }, { color: "#0000FF", id: "#0000FF", label: strings.HighlightColorBlue }, { color: "#FF0000", id: "#FF0000", label: strings.HighlightColorRed }, { color: "#000080", id: "#000080", label: strings.HighlightColorDarkblue }, { color: "#008080", id: "#008080", label: strings.HighlightColorTeal }, { color: "#008000", id: "#008000", label: strings.HighlightColorDarkgreen }, { color: "#800080", id: "#800080", label: strings.HighlightColorPurple }, { color: "#800000", id: "#800000", label: strings.HighlightColorMaroon }, { color: "#808000", id: "#808000", label: strings.HighlightColorGold }, { color: "#808080", id: "#808080", label: strings.HighlightColorDarkgrey }, { color: "#C0C0C0", id: "#C0C0C0", label: strings.HighlightColorGrey }, { color: "#000000", id: "#000000", label: strings.HighlightColorBlack } ]; break; case 'customColors': groupColors = this.props.customColors; break; default: groupColors = [ { color: "#a80000", id: "#a80000", label: strings.StandardColorDarkred }, { color: "#e81123", id: "#e81123", label: strings.StandardColorRed }, { color: "#ffb900", id: "#ffb900", label: strings.StandardColorOrange }, { color: "#fff100", id: "#fff100", label: strings.StandardColorYellow }, { color: "#bad80a", id: "#bad80a", label: strings.StandardColorLightgreen }, { color: "#107c10", id: "#107c10", label: strings.StandardColorGreen }, { color: "#00bcf2", id: "#00bcf2", label: strings.StandardColorLightblue }, { color: "#0078d4", id: "#0078d4", label: strings.StandardColorBlue }, { color: "#002050", id: "#002050", label: strings.StandardColorDarkblue }, { color: "#5c2d91", id: "#5c2d91", label: strings.StandardColorPurple } ]; break; } return ( <SwatchColorPickerGroup key={pickerGroup} groupText={groupName} onColorChanged={this.handleColorChanged} groupColors={groupColors} selectedColor={this.props.selectedColor} /> ); } }
the_stack
import { Color } from '../../../protocol/color'; import { Move } from '../../../protocol/move'; import { Repertoire } from '../../../protocol/storage'; import { Annotator } from '../annotation/annotator'; import { NullAnnotator } from '../annotation/nullannotator'; import { Config } from '../common/config'; import { ViewInfo } from '../common/viewinfo'; import { AddMoveFailureReason, AddMoveResult } from './addmoveresult'; import { FenNormalizer } from './fennormalizer'; import { FenToPgnMap } from './fentopgnmap'; import { PgnToNodeMap } from './pgntonodemap'; import { TreeNode } from './treenode'; declare var Chess: any; export class TreeModel { private chess_: any; private rootNode_: TreeNode | null; private selectedNode_: TreeNode | null; private pgnToNode_: PgnToNodeMap; private fenToPgn_: FenToPgnMap; private repertoireColor_: Color; private repertoireName_: string; private numNodes_: number; constructor() { this.chess_ = null; this.rootNode_ = null; this.selectedNode_ = null; this.pgnToNode_ = {}; this.fenToPgn_ = {}; this.repertoireColor_ = Color.WHITE; this.repertoireName_ = ''; this.numNodes_ = 0; this.makeEmpty_(); } getChessForState(): any { return this.chess_; } isEmpty(): boolean { if (!this.rootNode_ || !this.selectedNode_) { throw new Error('Model not ready.'); } const viewInfo = this.rootNode_.toViewInfo( this.selectedNode_, this.pgnToNode_, this.fenToPgn_, this.repertoireColor_, NullAnnotator.INSTANCE); return !viewInfo.numChildren; } addMove(pgn: string, move: Move | string): AddMoveResult { if (this.numNodes_ >= Config.MAXIMUM_TREE_NODES_PER_REPERTOIRE) { return { success: false, failureReason: AddMoveFailureReason.EXCEEDED_MAXIMUM_NUM_NODES }; } if (!pgn) { this.chess_.reset(); } if (pgn && !this.chess_.load_pgn(pgn)) { throw new Error('Tried to add move from invalid PGN: ' + pgn); } if (this.chess_.history().length >= Config.MAXIMUM_LINE_DEPTH_IN_PLY) { return { success: false, failureReason: AddMoveFailureReason.EXCEEDED_MAXIMUM_LINE_DEPTH }; } const chessMove = typeof move === 'string' ? move : { from: move.fromSquare, to: move.toSquare, promotion: 'q' }; if (!this.chess_.move(chessMove)) { return { success: false, failureReason: AddMoveFailureReason.ILLEGAL_MOVE }; } let childPosition = this.chess_.fen(); let childPgn = this.chess_.pgn(); let childNode = this.pgnToNode_[childPgn]; if (!childNode) { // This is a new position. Add it to the tree. let history = this.chess_.history({verbose: true}); const lastMove = history[history.length - 1]; childNode = this.addNewMove_( pgn, childPosition, childPgn, this.chess_.moves().length, { fromSquare: lastMove.from, toSquare: lastMove.to }, lastMove.san); } // Select the new child node. this.selectedNode_ = childNode; return { success: true, failureReason: null }; } private addNewMove_( parentPgn: string, childPosition: string, childPgn: string, numLegalMoves: number, lastMove: Move, lastMoveString: string): TreeNode { const parentNode = this.pgnToNode_[parentPgn]; if (!parentNode) { throw new Error('No node exists for PGN: ' + parentPgn); } const childNode = parentNode.addChild( childPosition, childPgn, numLegalMoves, lastMove, lastMoveString); this.pgnToNode_[childPgn] = childNode; const normalizedFen = FenNormalizer.normalize(childPosition, numLegalMoves); if (!this.fenToPgn_[normalizedFen]) { this.fenToPgn_[normalizedFen] = []; } this.fenToPgn_[normalizedFen].push(childPgn); this.numNodes_++; return childNode; } canRemoveSelectedPgn(): boolean { if (!this.selectedNode_) { throw new Error('Model not ready.'); } return this.selectedNode_.parentOrSelf() != this.selectedNode_; } removeSelectedPgn(): void { if (!this.selectedNode_) { throw new Error('Model not ready.'); } const nodeToDelete = this.selectedNode_; if (!nodeToDelete.pgn) { // Can't delete the start position. return; } // Select the parent of the node to delete. this.selectedNode_ = nodeToDelete.parentOrSelf(); this.selectedNode_.removeChildPgn(nodeToDelete.pgn); this.chess_.load_pgn(this.selectedNode_.pgn); // Remove all the descendent nodes from the PGN to node map. let numDeletedNodes = 0; nodeToDelete.traverseDepthFirst( viewInfo => { delete this.pgnToNode_[viewInfo.pgn]; const normalizedFen = FenNormalizer.normalize( viewInfo.position, viewInfo.numLegalMoves); if (!this.fenToPgn_[normalizedFen]) { throw new Error('Unexpected state.'); } this.fenToPgn_[normalizedFen] = this.fenToPgn_[normalizedFen] .filter(e => e != viewInfo.pgn); numDeletedNodes++; }, this.selectedNode_, this.pgnToNode_, this.fenToPgn_, this.repertoireColor_, NullAnnotator.INSTANCE); this.numNodes_ -= numDeletedNodes; } /** * Traverses the nodes in the tree depth-first and pre-order. * * That is, parents are visited before their children and children are visited * before siblings. */ traverseDepthFirst<ANNOTATION>( callbackFn: (v: ViewInfo<ANNOTATION>) => void, annotator: Annotator<ANNOTATION>): void { if (!this.rootNode_ || !this.selectedNode_) { throw new Error('Model not ready.'); } this.rootNode_.traverseDepthFirst( callbackFn, this.selectedNode_, this.pgnToNode_, this.fenToPgn_, this.repertoireColor_, annotator); } getRepertoireColor(): Color { return this.repertoireColor_; } flipRepertoireColor(): void { const newColor = this.repertoireColor_ == Color.WHITE ? Color.BLACK : Color.WHITE; this.setRepertoireColor(newColor); } setRepertoireColor(color: Color): void { this.repertoireColor_ = color; } getRepertoireName(): string { return this.repertoireName_; } setRepertoireName(repertoireName: string): void { this.repertoireName_ = repertoireName; } selectPgn(pgn: string): void { if (!pgn) { this.chess_.reset(); } if (pgn && !this.chess_.load_pgn(pgn)) { throw new Error('Tried to select invalid PGN: ' + pgn); } let node = this.pgnToNode_[pgn]; if (!node) { throw new Error('No node exists for PGN: ' + pgn); } this.selectedNode_ = node; } hasPreviousPgn(): boolean { if (!this.selectedNode_) { throw new Error('Model not ready.'); } return this.selectedNode_.parentOrSelf() != this.selectedNode_; } selectPreviousPgn(): void { if (!this.selectedNode_) { throw new Error('Model not ready.'); } this.selectedNode_ = this.selectedNode_.parentOrSelf(); this.chess_.load_pgn(this.selectedNode_.pgn); } hasNextPgn(): boolean { if (!this.selectedNode_) { throw new Error('Model not ready.'); } return this.selectedNode_.firstChildOrSelf() != this.selectedNode_; } selectNextPgn(): void { if (!this.selectedNode_) { throw new Error('Model not ready.'); } this.selectedNode_ = this.selectedNode_.firstChildOrSelf(); this.chess_.load_pgn(this.selectedNode_.pgn); } hasPreviousSiblingPgn(): boolean { if (!this.selectedNode_) { throw new Error('Model not ready.'); } return this.selectedNode_.previousSiblingOrSelf( false /* stopWithManyChildren */) != this.selectedNode_; } selectPreviousSiblingPgn(): void { if (!this.selectedNode_) { throw new Error('Model not ready.'); } this.selectedNode_ = this.selectedNode_.previousSiblingOrSelf( false /* stopWithManyChildren */); this.chess_.load_pgn(this.selectedNode_.pgn); } hasNextSiblingPgn(): boolean { if (!this.selectedNode_) { throw new Error('Model not ready.'); } return this.selectedNode_.nextSiblingOrSelf( false /* stopWithManyChildren */) != this.selectedNode_; } selectNextSiblingPgn(): void { if (!this.selectedNode_) { throw new Error('Model not ready.'); } this.selectedNode_ = this.selectedNode_.nextSiblingOrSelf( false /* stopWithManyChildren */); this.chess_.load_pgn(this.selectedNode_.pgn); } getSelectedViewInfo<ANNOTATION>(annotator: Annotator<ANNOTATION>): ViewInfo<ANNOTATION> { if (!this.selectedNode_) { throw new Error('Model not ready.'); } return this.selectedNode_.toViewInfo( this.selectedNode_, this.pgnToNode_, this.fenToPgn_, this.repertoireColor_, annotator); } serializeAsRepertoire(): Repertoire { if (!this.rootNode_) { throw new Error('Model not ready.'); } return { name: this.repertoireName_, color: this.repertoireColor_, root: this.rootNode_.serializeAsRepertoireNode() }; } exportToPgn(): string { if (!this.rootNode_) { throw new Error('Model not ready.'); } const rootPgn = this.rootNode_.exportChildrenToPgn( false /* forceFirstChildVerbose */); return rootPgn ? rootPgn + ' *' : '*'; } private makeEmpty_(): void { this.chess_ = new Chess(); const initialFen = FenNormalizer.normalize( this.chess_.fen(), this.chess_.moves().length); const initialPgn = this.chess_.pgn(); this.rootNode_ = new TreeNode( null /* parent */, initialFen, initialPgn, this.chess_.moves().length, null /* lastMove */, '' /* lastMoveString */, 0); this.pgnToNode_ = {}; this.pgnToNode_[initialPgn] = this.rootNode_; this.fenToPgn_ = {}; this.fenToPgn_[initialFen] = [initialPgn]; this.selectedNode_ = this.rootNode_; this.repertoireColor_ = Color.WHITE; this.numNodes_ = 1; } loadRepertoire(repertoire: Repertoire): void { this.makeEmpty_(); if (repertoire) { this.repertoireName_ = repertoire.name; this.repertoireColor_ = repertoire.color; if (repertoire.root) { this.parseRecursive_(repertoire.root); } } this.selectPgn(''); } private parseRecursive_(node: any): void { const children = node.children || node.c; for (let i = 0; i < children.length; i++) { let child = children[i]; if (child.fen) { this.addNewMove_( node.pgn, child.fen, child.pgn, child.nlm, { fromSquare: child.lmf, toSquare: child.lmt }, child.lms); } else { // The repertoire was saved with the legacy storage representation which // did not store the position. In order to construct the model with this // representation, a Chess object must be initialized for each position // which is expensive. console.log('Parsing legacy storage format.'); this.addMove( node.pgn, { fromSquare: child.lastMoveFrom, toSquare: child.lastMoveTo }); } this.parseRecursive_(child); } } }
the_stack
import { h, VNode, createProjector } from 'maquette'; import * as Langs from '../definitions/languages'; import * as Graph from '../definitions/graph'; import _ from 'lodash'; import { Md5 } from 'ts-md5'; import * as Values from '../definitions/values'; import { Log } from '../common/log'; import axios from 'axios'; // import { Position } from 'monaco-editor'; type Position = {row:number, col: string} interface SpreadsheetBlock extends Langs.Block { language : string } type SpreadsheetState = { id: number block: SpreadsheetBlock ColIndices: Array<string>, RowIndices: Array<number> Cols : Array<string>, Rows: Array<number> Active: Position | null Cells: Map<string, string> } interface SpreadsheetCodeNode extends Graph.Node { kind: 'code', framesInScope: Langs.ScopeDictionary } type SpreadsheetInput = { url:string } interface SpreadsheetBlock extends Langs.Block { language: string dataframe: SpreadsheetInput } type CellSelectedEvent = { kind: 'selected', pos: Position} type CellEditedEvent = { kind: 'edited', pos: Position} type SpreadsheetEvent = CellSelectedEvent | CellEditedEvent async function getValue(preview:boolean, url:string) : Promise<any> { let headers = {'Accept': 'application/json'} if (preview) url = url.concat("?nrow=10") try { let response = await axios.get(url, {headers: headers}); return response.data } catch (error) { throw error; } } const spreadsheetEditor : Langs.Editor<SpreadsheetState, SpreadsheetEvent> = { initialize: (id:number, block:Langs.Block) => { let spreadsheetBlock = <SpreadsheetBlock> block if (spreadsheetBlock.dataframe.url.length == 0){ let newState = { id: id, block: spreadsheetBlock, ColIndices: [], RowIndices: [], Cols : [], Rows: [], Active: null, Cells: new Map() } newState.Cols.forEach(col => { newState.Rows.forEach(row => { let position:Position = {row:row, col:col} newState.Cells.set(JSON.stringify(position), "") }); }); Log.trace('spreadsheet', "New State initialised (default)") return newState } else { let source = [{"id": 11, "language": "javascript"}, {"id": 12, "language": "javascript"}] let colNames = Object.keys(source[0]) let newState = { id: id, block: <SpreadsheetBlock>block, ColIndices: 'XABCDEFG'.substr(0, colNames.length+1).split(''), RowIndices: _.range(0,source.length+2), Cols : colNames, Rows: _.range(0,source.length+2), Active: null, Cells: new Map() } newState.RowIndices.forEach((row, rIndex) => { newState.ColIndices.forEach((col, cIndex) => { // Log.trace('spreadsheet', "Row[%s] Col[%s]: %s", row, col, row.toString().concat(col.toString())) let position:Position = {row:row, col:col} let value:string = " " if ((rIndex == 0) && (col == 'X')) value = ' ' else if (rIndex == 0) value = col else if (rIndex == 1) { let colName: string | undefined = newState.Cols[cIndex-1] if (colName) value = colName else value = rIndex.toString() } else if (col == 'X') value = rIndex.toString() else { let colName = newState.Cols[cIndex-1] value = source[rIndex-2][colName] } // Log.trace('spreadsheet', "Position [%s]: %s", JSON.stringify(position), value) newState.Cells.set(JSON.stringify(position), value) }); }); return newState } }, update: (state:SpreadsheetState, event:SpreadsheetEvent) => { Log.trace("spreadsheet","Spreadsheet being updated: "+JSON.stringify(event)) switch (event.kind) { case 'edited': return state; case 'selected': return {...state, Active: event.pos} } }, render: (cell:Langs.BlockState, state:SpreadsheetState, context:Langs.EditorContext<SpreadsheetEvent>):VNode => { let spreadsheetNode = <SpreadsheetCodeNode>cell.code function renderTable(){ Log.trace('spreadsheet', "Rendering Table: %s", JSON.stringify(state)) let rowsComponents:Array<any> = [] let headerComponents:Array<any> = [] let colComponents:Array<any> = [] for (let c = 0; c < state.ColIndices.length; c++) { let position:Position = {row:0, col:state.ColIndices[c]} let headerValue:string | undefined = state.Cells.get(JSON.stringify(position)) if (headerValue) headerComponents.push(h('th',{key: "spreadsheetColumnHeader"+c, class:"spreadsheet-th"}, [headerValue])) } rowsComponents.push(h('tr',{key: "spreadsheetColHeader"},[headerComponents])) for (let r = 1; r < state.RowIndices.length; r++) { colComponents = [] for (let c = 0; c < state.ColIndices.length; c++) { let position:Position = {row:state.RowIndices[r], col:state.ColIndices[c]} let cellValue:string | undefined = state.Cells.get(JSON.stringify(position)) if (cellValue) { let cell = renderCell(position, state) colComponents.push(cell) } else { colComponents.push(h('td',{key: "spreadsheetColumn"+r+c, class:"spreadsheet-td"}, [" "])) } }; rowsComponents.push(h('tr',{key: "spreadsheetRow"+r, class:"spreadsheet-tr"},[colComponents])) } function renderEditor(pos:Position): VNode{ let inputComponent:VNode = h('input', {key:"spreadsheetInput"+pos.row.toString()+pos.col+cell.editor.id, type: "text"},[]) let editorComponent:VNode = h('td', {key: "spreadsheetColumn"+pos.row.toString()+pos.col+cell.editor.id, class: "spreadsheet-td input", onchange:()=>{ Log.trace("spreadsheet","Cell is edited") }}, [inputComponent]) return editorComponent } function renderView(state: SpreadsheetState, pos:Position){ let viewComponent:VNode; if (pos.col == " ") viewComponent = h('th', { key: "spreadsheetRowHeader"+pos.row.toString()+pos.col, class:"spreadsheet-th"}, [pos.row.toString()]) else { let value:string|undefined = state.Cells.get(JSON.stringify(pos)) let displayComponent:VNode = h('p', {key:"spreadsheetDisplay"+pos.row.toString()+pos.col+cell.editor.id}, [value==undefined? "...":value.toString()]) viewComponent = h('td', {key: "spreadsheetColumn"+pos.row.toString()+pos.col+cell.editor.id, class: "spreadsheet-td", onclick:()=>{ Log.trace("spreadsheet","Cell is clicked") context.trigger({kind:"selected", pos: pos}) }}, [displayComponent]) } return viewComponent } function renderCell(pos:Position, state: SpreadsheetState):VNode { if ((state.Active != null) && (state.Active.row == pos.row) && (state.Active.col == pos.col)) { Log.trace("spreadsheet", "Active state position: ".concat(JSON.stringify(state.Active))) return renderEditor(pos) } else { return renderView(state, pos) } } // function getKey(pos:Position, state:SpreadsheetState):IteratorResult<Position> | undefined { // let keys = state.Cells.keys() // for (let k = 0; k < state.Cells.size; k++) { // let key:IteratorResult<Position> = keys.next() // if ((key.value.col == pos.col) && (key.value.row == pos.row)) // return key // } // return undefined // } let table:VNode = h('table', {id: "spreadsheet-table"+cell.editor.id, key: "spreadsheet-table"+cell.editor.id, class:'spreadsheet-table'},[rowsComponents]); return table } let dataframeKeys:Array<string> = Object.keys(spreadsheetNode.framesInScope) let selectedDataFrame:string = "" let frameSelector:VNode = h('div', {}, [ h('span', {}, [ "Input: " ]), h('select', { onchange:(e) => { selectedDataFrame = (<any>e.target).value let selectedFrameValue = spreadsheetNode.framesInScope[selectedDataFrame].value if (selectedFrameValue != null) { let selectedFrame = <Values.DataFrame>selectedFrameValue context.rebindSubsequent(cell,selectedFrame.url) } else { context.rebindSubsequent(cell,"") } } }, [""].concat(dataframeKeys).map(f => h('option', { key:f, value:f}, [f==""?"(no frame selected)":f]) )) ]) return h('div', {id:"spreadsheet"+cell.editor.id, key: "spreadsheet"+cell.editor.id}, [frameSelector,renderTable()]) } } export class spreadsheetLanguagePlugin implements Langs.LanguagePlugin { readonly language: string = "spreadsheet" readonly iconClassName: string = "fas fa-file-spreadsheet" readonly editor: Langs.Editor<Langs.EditorState, any> = spreadsheetEditor readonly datastoreURI: string; constructor (language: string,iconClassName:string, datastoreUri: string) { this.datastoreURI = datastoreUri this.language = language this.iconClassName = iconClassName } getDefaultCode (id:number) { return "" } parse (url:string) : Langs.Block { // Log.trace('spreadsheet', "Parse Spreadsheet for url: %s", JSON.stringify(url)) let block:SpreadsheetBlock = { language: "spreadsheet", dataframe:{url: url}} return block } async bind (context: Langs.BindingContext, block: Langs.Block) : Promise<Langs.BindingResult> { let ssBlock = <SpreadsheetBlock> block Log.trace("spreadsheet", "Bind spreadsheet block: %s", JSON.stringify(ssBlock)) let node:SpreadsheetCodeNode = { kind: 'code', language: this.language, hash: <string>Md5.hashStr(JSON.stringify(this.save(block))), antecedents: [], value: null, errors: [], framesInScope: context.scope } // Log.trace("spreadsheet", "Context.scope: %s", JSON.stringify(context.scope)) return { code: node, exports: [], resources: [] }; } async evaluate (context:Langs.EvaluationContext, node:Graph.Node) : Promise<Langs.EvaluationResult> { Log.trace("spreadsheet","Spreadsheet being evaluated") let val:Values.Printout = {kind:"printout", data:"Eval-ed spreadsheet node"} return { kind: "success", value: val } } save (block:Langs.Block) { let spreadsheetBlock = <SpreadsheetBlock>block return spreadsheetBlock.language } }
the_stack
import { IExpression } from "./reflector/expression-reflector"; import { Times } from "./times"; import { Interaction } from "./interactions"; import { Tracker } from "./tracker/tracker"; import { StaticProvider } from "./static.injector/interface/provider"; import { InjectionFactory, TypeOfInjectionFactory } from "./injector/injection-factory"; import { Type } from "./static.injector/type"; import { InjectionToken } from "./static.injector/injection_token"; export const enum PlayableUpdateReason { /** * The playable is update because it's setup is about to be played */ OwnSetupWouldBePlayed, /** * The playable is update because another setup is about to be played */ OtherSetupWouldBePlayed } /** * Provides playable logic for a setup */ export interface IPlayable { /** * Tests if setup is playable */ isPlayable(): boolean; /** * Invokes as the setup is about to be played, so the playable logic can change it's state. * * @param reason The reason why this update is called {@link PlayableUpdateReason} * @example * ```typescript * * const playable1 = new PlayableOnce(); * const playable2 = new PlayableOnce(); * * const mock = new Mock<(val: number) => void)>() * // setup A * .setup(instance => instance(1)) * .play(playable1) * .returns(1) * // setup B * .setup(instance => instance(2)) * .play(playable2) * .returns(2); * * const actual = mock.object()(1); * // at this point the update of playable1 should be called with OwnSetupWouldBePlayed * // because setup A would be played * // and the update of playable2 should be called with OtherSetupWouldBePlayed * ``` */ update(reason: PlayableUpdateReason): void; } /** * Sets a behaviour rule for a particular use case * * @param T The type of mocked object. */ export interface IPresetBuilder<T, TValue = any> { /** * Returns the provided value as a result of interaction in case of * - get property value * - invocation a function * * Controls write operation in case of * - property assignment (true - the assignment is allowed, false - the assignment is not allowed) * * @param value The value */ returns(value: TValue): IMock<T>; /** * Throws the provided exception. */ throws<TException>(exception: TException): IMock<T>; /** * @param callback A callback function that will intercept the interaction. * The function may returns a value that will be provided as result (see {@link IPresetBuilder.returns}) * @example * ```typescript * * const ipcRendererMock = new StrictMock<typeof ipcRenderer>() * .setup(instance => instance.on(ipcRendererChannelName, It.IsAny())) * .callback(({args: [channel, listener]}) => listener(undefined, response)); * ``` */ callback(callback: (interaction: Interaction) => TValue): IMock<T>; /** * Plays the setup on target invocation when predicate returns true otherwise the setup will be ignored. * As predicate {@link PlayTimes} could be used. */ play(predicate: IPlayable): IPresetBuilder<T, TValue>; /** * Replicates interactions with original object. * The mock object keeps tracking all interactions and reflects them on the original object. * * @example * ```typescript * * const value = 2; * * class Origin { * public property = value; *} * * const origin = new Origin(); * const mock = new Mock<Origin>() * .setup(() => It.IsAny()) * .mimics(origin); * * const actual = mock.object().property; * expect(actual).toBe(2); * ``` */ mimics(origin: T): IMock<T>; } /** * The main API of the framework. * * @example * ```typescript * * const value = 'value'; * const object = new Mock<Function>() * .setup(instance => instance(1)) * .returns(value) * .object(); * * const actual = object(1); * * expect(actual).toBe(value); * ``` * --- * #### Latest setups have more precedence over earlier setups. * @example * ```typescript * * const object = new Mock<Function>() * .setup(instance => instance(1)) * .returns(1) * .setup(instance => instance(1)) * .returns(2) * .object(); * * const actual = object(1); * * expect(actual).toBe(2); * ``` * * @param T The type of mocked object. Could be any type including: * - Function, * - arrow function, * - interface, * - class, * - object and etc. */ export interface IMock<T> { /** * You can name the mock. The name will be displayed with any relative output, so you can easily distinct * output of several mocks. On the mocked object you can find this name at 'mockName' property of the [[Handler]]. */ readonly name?: string; /** * Returns the tracker object that responsible for storing history of interactions with the mocked object. */ readonly tracker: Tracker; /** * Returns options object */ readonly options: IMockOptions<T>; /** * Returns instance of mocked object */ object(): T; /** * Defines a configuration for particular interaction with the mocked object. * * @example * ```typescript * * // a function invoke with 1 as parameter * .setup(instance => instance(1)) * * // apply function invoke on a function with null as the first parameter and a placeholder for the second parameter * .setup(instance => instance.apply(null, It.IsAny())) * * // accessing to a property * .setup(instance => instance.property) * * //accessing to a named function with name 'test' of an object and the first parameter is 1 * .setup(instance => It.Is((expression: NamedMethodExpression) => { * return expression.name === 'test' && expression.args[0] === 1 * })) * * //setting propertyA to value of 'a' * .setup(instance => {instance.propertyA = 'a'}) * ``` * @param expression A function that accepts a * [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) * and either plays expected interaction or returns a predicate function. * Refer {@link It} class for parameter placeholders or predicate functions. * Refer the integration tests for more examples. * @returns PresetBuilder config interface for the provided expression. */ setup<E extends IExpression<T>, R = E extends (...args: any[]) => infer M ? M : any>(expression: E): IPresetBuilder<T, R>; /** * Asserts expected interactions with the mocked object. * * @param expression Expected expression * @param times The default value is {@link Times.Once()} */ verify(expression: IExpression<T>, times?: Times): IMock<T>; /** * Set the prototype of the mocked object. * * @example * ```typescript * * class PrototypeClass {} * * const mock = new Mock<{}>(); * const object = mock.object(); * * Object.setPrototypeOf(object, PrototypeClass.prototype); * * expect(object instanceof PrototypeClass).toBe(true); * ``` */ prototypeof(prototype?: any): IMock<T>; /** * @experimental * @hidden */ insequence(sequence: ISequenceVerifier, expression: IExpression<T>): IMock<T>; /** * Retrieves an instance from the injector based on the provided token. * * @returns The instance from the injector if defined, otherwise null. */ resolve<S, R = S extends InjectionFactory ? TypeOfInjectionFactory<S> : S>(token: Type<S> | InjectionToken<S>): R; } /** * @hidden * @experimental */ export interface ISequenceVerifier { add<T>(mock: IMock<T>, expression: IExpression<T>): ISequenceVerifier; verify(times?: Times): void; } /** * A mock object exposes a symbol property to access to its Moq API. * This property is read only and trackable. * Since this property makes sense only in context of the moq library * and is not specific for mocked types it is not possible to define an interaction behaviour with Setup API. * * @example * ```typescript * * const mock = new Mock<() => void>() * .object(); * * mock[MoqAPI] * .setup(instance => instance()) * .returns(12); * * const actual = mock(); * * expect(actual).toBe(12); * ``` */ export const MoqAPI = Symbol("MoqAPI"); /** * The Mock internally depends on angular based injector to construct its dependencies. */ export interface IInjectorConfig { /** * Returns array of StaticProviders to construct an angular based injector. * * @param options The final version of mock options. Options that passed to Mock constructor are merged with * the global mock options ({@link Mock.options}). Some components depend on the options and the injector * should be able to resolve it. To configure the injector property the implementation could do the following: * ``` typescript * return [ * {provide: MOCK_OPTIONS, useValue: options, deps: []}, * ]; * ``` * @param providers An array of additional providers that could be added to the final configuration. */ get(options: IMockOptions<unknown>, ...providers: StaticProvider[]): StaticProvider[]; } /** * Mock instance options. * Could be passed as parameter on mock instantiating or could be set globally on {@link Mock.options}. */ export interface IMockOptions<T> { /** * You can name the mock. The name will be displayed with any relative output, so you can easily distinct * output of several mocks. On the mocked object you can find this name at 'mockName' property of the [[Handler]]. */ name?: string; /** * The target object for Proxy that is used under the hood. * typeof operation is applied to this target. * The default value is a function. */ target?: T; /** * The Mock internally based on angular injector to construct its dependencies. * An instance of {@link IInjectorConfig} implementation could be passed as parameter in order to * changed the mock behaviour. The default value is an instance of {@link DefaultInjectorConfig}. * There is also {@link EqualMatchingInjectorConfig} that would setup Mock to use equal logic for comparing values. */ injectorConfig?: IInjectorConfig; }
the_stack
import mongoose from 'mongoose'; import { schemaComposer, InputTypeComposer, SchemaComposer, graphql } from 'graphql-compose'; import { composeWithMongoose } from '../../../composeWithMongoose'; import { composeMongoose } from '../../../composeMongoose'; import { _createOperatorsField, addFilterOperators, processFilterOperators, OPERATORS_FIELDNAME, } from '../filterOperators'; import { toMongoFilterDottedObject } from '../../../utils/toMongoDottedObject'; import { UserModel } from '../../../__mocks__/userModel'; let itc: InputTypeComposer<any>; beforeEach(() => { schemaComposer.clear(); schemaComposer.createInputTC({ name: 'BillingAddressUserFieldInput', fields: { street: 'String', state: 'String', country: 'String', }, }); itc = schemaComposer.createInputTC({ name: 'UserFilterInput', fields: { _id: 'String', employment: 'String', name: 'String', age: 'Int', skills: ['String'], billingAddress: 'BillingAddressUserFieldInput', }, }); }); describe('Resolver helper `filter` ->', () => { describe('_createOperatorsField()', () => { it('should add OPERATORS_FIELDNAME to filterType', () => { _createOperatorsField(itc, UserModel, { baseTypeName: 'TypeNameOperators', }); expect(itc.hasField(OPERATORS_FIELDNAME)).toBe(true); expect(itc.getFieldTC(OPERATORS_FIELDNAME).getTypeName()).toBe('TypeNameOperators'); }); it('should have only provided fields via options', () => { _createOperatorsField(itc, UserModel, { baseTypeName: 'TypeNameOperators', operators: { age: ['lt'], }, }); const operatorsTC = itc.getFieldITC(OPERATORS_FIELDNAME); expect(operatorsTC.hasField('age')).toBe(true); }); it('should have only provided operators via options for field', () => { _createOperatorsField(itc, UserModel, { baseTypeName: 'TypeNameOperators', operators: { age: ['lt', 'gte'], }, }); const operatorsTC = itc.getFieldITC(OPERATORS_FIELDNAME); const ageTC = operatorsTC.getFieldITC('age'); expect(ageTC.getFieldNames()).toEqual(expect.arrayContaining(['lt', 'gte'])); }); it('should handle nested fields recursively', () => { _createOperatorsField(itc, UserModel, { baseTypeName: 'TypeNameOperators', operators: { age: ['lt', 'gte'], billingAddress: { country: ['nin'], state: ['in'] }, }, }); const operatorsTC = itc.getFieldITC(OPERATORS_FIELDNAME); const billingAddressTC = operatorsTC.getFieldITC('billingAddress'); expect(billingAddressTC.getFieldNames()).toEqual(expect.arrayContaining(['country'])); const countryBillingAddressTC = billingAddressTC.getFieldITC('country'); expect(countryBillingAddressTC.getFieldNames()).toEqual(expect.arrayContaining(['nin'])); expect(billingAddressTC.getFieldNames()).toEqual(expect.arrayContaining(['state'])); const stateBillingAddressTC = billingAddressTC.getFieldITC('state'); expect(stateBillingAddressTC.getFieldNames()).toEqual(expect.arrayContaining(['in'])); }); it('should not recurse on circular schemas to avoid maximum call stack size exceeded', () => { const PersonSchema = new mongoose.Schema({ name: String, }); PersonSchema.add({ spouse: PersonSchema, friends: [PersonSchema], }); const PersonModel = mongoose.model('Person', PersonSchema); const tc = composeWithMongoose(PersonModel); expect(tc.getFieldNames()).toEqual( expect.arrayContaining(['_id', 'name', 'spouse', 'friends']) ); }); it('should reuse existed operatorsType', () => { const existedITC = itc.schemaComposer.getOrCreateITC('ExistedType'); _createOperatorsField(itc, UserModel, { baseTypeName: 'ExistedType' }); expect(itc.getFieldType(OPERATORS_FIELDNAME)).toBe(existedITC.getType()); }); }); describe('addFilterOperators()', () => { it('should add OPERATORS_FIELDNAME via _createOperatorsField()', () => { addFilterOperators(itc, UserModel, { baseTypeName: 'UserFilter', suffix: 'Input' }); expect(itc.hasField(OPERATORS_FIELDNAME)).toBe(true); expect(itc.getFieldTC(OPERATORS_FIELDNAME).getTypeName()).toBe('UserFilterOperatorsInput'); }); it('should add OR field', () => { addFilterOperators(itc, UserModel, {}); const fields = itc.getFieldNames(); expect(fields).toEqual(expect.arrayContaining(['OR', 'name', 'age'])); expect(itc.getFieldTC('OR').getType()).toBe(itc.getType()); }); it('should add AND field', () => { addFilterOperators(itc, UserModel, {}); const fields = itc.getFieldNames(); expect(fields).toEqual(expect.arrayContaining(['AND', 'name', 'age'])); expect(itc.getFieldTC('AND').getType()).toBe(itc.getType()); }); it('should respect operators configuration', () => { // onlyIndexed: false by default addFilterOperators(itc, UserModel, { operators: { name: ['exists'] } }); const fields = itc.getFieldNames(); expect(fields).toEqual(expect.arrayContaining(['name'])); expect(itc.hasField('_operators')).toBe(true); expect(itc.getFieldITC('_operators').getFieldNames()).toEqual([ '_id', 'employment', 'name', 'billingAddress', ]); expect(itc.getFieldITC('_operators').getFieldITC('name').getFieldNames()).toEqual(['exists']); }); it('should respect operators configuration and allow onlyIndexed', () => { // By default when using onlyIndex, add all indexed fields, then if operators are supplied allow them as well addFilterOperators(itc, UserModel, { baseTypeName: 'User', onlyIndexed: true, operators: { name: ['exists'] }, }); const fields = itc.getFieldNames(); expect(fields).toEqual(expect.arrayContaining(['name'])); expect(itc.hasField('_operators')).toBe(true); expect(itc.getFieldITC('_operators').getFieldNames()).toEqual([ '_id', 'employment', 'name', 'billingAddress', ]); expect(itc.getFieldITC('_operators').getFieldITC('name').getFieldNames()).toEqual(['exists']); expect(itc.getFieldITC('_operators').getFieldITC('employment').getFieldNames()).toEqual([ 'gt', 'gte', 'lt', 'lte', 'ne', 'in', 'nin', 'regex', 'exists', ]); expect(itc.getFieldITC('_operators').getFields()).toEqual( expect.not.arrayContaining(['age']) ); }); }); describe('processFilterOperators()', () => { it('should call query.find if args.filter.OPERATORS_FIELDNAME is provided', () => { const filter = { [OPERATORS_FIELDNAME]: { age: { gt: 10, lt: 20 } }, }; expect(processFilterOperators(filter)).toEqual({ age: { $gt: 10, $lt: 20 } }); }); it('should process nested fields', () => { const filter = { [OPERATORS_FIELDNAME]: { age: { gt: 10, lt: 20 }, address: { country: { in: ['US'] } }, }, }; expect(processFilterOperators(filter)).toEqual({ age: { $gt: 10, $lt: 20 }, address: { country: { $in: ['US'] } }, }); }); it('should convert OR query', () => { const filter = { OR: [ { name: { first: 'Pavel', }, age: 30, }, { age: 40, }, ], }; expect(toMongoFilterDottedObject(processFilterOperators(filter))).toEqual({ $or: [ { age: 30, 'name.first': 'Pavel' }, { age: 40, }, ], }); }); it('should convert AND query', () => { const filter = { AND: [ { name: { first: 'Pavel', }, }, { age: 40, }, ], }; expect(toMongoFilterDottedObject(processFilterOperators(filter))).toEqual({ $and: [ { 'name.first': 'Pavel' }, { age: 40, }, ], }); }); it('should convert nested AND/OR query', () => { const filter = { OR: [ { AND: [ { name: { first: 'Pavel' } }, { OR: [{ age: 30 }, { age: 35 }], }, ], }, { age: 40, }, ], }; expect(toMongoFilterDottedObject(processFilterOperators(filter))).toEqual({ $or: [ { $and: [ { 'name.first': 'Pavel' }, { $or: [{ age: 30 }, { age: 35 }], }, ], }, { age: 40, }, ], }); }); }); describe('integration tests', () => { it('should not throw error: must define one or more fields', async () => { const OrderDetailsSchema = new mongoose.Schema( { productID: Number, unitPrice: Number, quantity: Number, discount: Number, }, { _id: false, } ); const OrderSchema = new mongoose.Schema( { orderID: { type: Number, description: 'Order unique ID', unique: true, }, customerID: String, employeeID: Number, orderDate: Date, requiredDate: Date, shippedDate: Date, shipVia: Number, freight: Number, shipName: String, details: { type: [OrderDetailsSchema], index: true, description: 'List of ordered products', }, }, { collection: 'northwind_orders', } ); const OrderModel = mongoose.model<any>('Order', OrderSchema); const OrderTC = composeMongoose(OrderModel); const orderFindOneResolver = OrderTC.mongooseResolvers.findOne(); const sc = new SchemaComposer(); sc.Query.addFields({ order: orderFindOneResolver, }); const schema = sc.buildSchema(); const res = await graphql.graphql({ schema, source: `{ __typename }`, }); expect(res?.errors?.[0]?.message).not.toBe( 'Input Object type FilterFindOneOrderDetailsOperatorsInput must define one or more fields.' ); }); }); });
the_stack
import * as Bluebird from 'bluebird'; import { Server } from '@hapi/hapi'; import * as hostile from 'hostile'; import * as joi from 'joi'; import { spawn } from 'child_process'; import { log, useLogger, Logger } from './logger'; import * as susie from 'susie'; import * as os from 'os'; import { createProxy } from './createProxy'; import { registerCleanup, removeCleanup, runCleanups } from './cleanupQueue'; import { ProxyConfig } from './ProxyConfig'; import { applyConfigDefaults } from './applyConfigDefaults'; import { setCertPath } from './getCertPath'; const hostileSet = Bluebird.promisify<void, string, string>(hostile.set, { context: hostile }); const hostileRemove = Bluebird.promisify<void, string, string>(hostile.remove, { context: hostile }); type IpHost = [string, string]; const hostileGet = Bluebird.promisify<IpHost[], boolean>(hostile.get, { context: hostile }); interface HostAdditionSuccessResponse { success: true; added?: boolean; hostname: string; } interface HostAdditionErrorResponse { success: false; error: string; } export type HostAdditionResponse = | HostAdditionSuccessResponse | HostAdditionErrorResponse; async function adminServer({ port }): Promise<Server> { log.info(`Starting admin server on port ${port}`); const server = new Server({ port: port || 1591, debug: { request: ['*'] } }); server.validator(joi); const portProxies = {}; const secret = process.env.ADMIN_SECRET || ''; if (secret.length < 20) { throw new Error( 'Cannot start without env ADMIN_SECRET set to at least 20 characters' ); } await server.register(susie); server.route([ { method: 'GET', path: `/${secret}/-/health`, handler(request, h) { return 'OK'; } }, { method: 'POST', path: `/${secret}/-/shutdown`, handler(request, h) { setTimeout(() => { runCleanups().then(() => server.stop()); }, 0); return 'OK'; } }, { method: 'POST', path: `/${secret}/hosts`, options: { validate: { payload: { hostname: joi.string() } }, async handler(request, h): Promise<HostAdditionResponse> { try { const hostname = (request.payload as any).hostname; const hosts: any[] = await hostileGet(false); const exists = hosts.some( ([ip, host]) => ip === '127.0.0.1' && host.split(/\s+/).indexOf(hostname) !== -1 ); await hostileSet('127.0.0.1', hostname); return { success: true, added: !exists, hostname }; } catch (e) { return { success: false, error: e.toString() }; } } } }, { method: 'DELETE', path: `/${secret}/hosts/{hostname}`, options: { async handler(request, h) { const hostname = (request.params as any).hostname; return hostileRemove('127.0.0.1', hostname).then(() => { return { success: true, hostname }; }); } } }, { method: 'POST', path: `/${secret}/trust`, options: { validate: { payload: { certFilename: joi.string(), homeDirectory: joi.string() } }, async handler(request, h) { const { certFilename, homeDirectory } = request.payload as any; // TODO: check if mac or linux here let executable: string | null = null; let args: string[] | null = null; if (os.platform() === 'darwin') { executable = 'security'; args = [ 'add-trusted-cert', '-d', '-r', 'trustRoot', '-p', 'ssl', '-k', '/Library/Keychains/System.keychain', certFilename ]; } if (os.platform() === 'linux') { // For linux, it's important to clear any existing certificate out first await untrustCertificate({ homeDirectory, certFilename }); executable = 'certutil'; args = [ '-d', `sql:${homeDirectory}/.pki/nssdb`, '-A', '-t', 'P,,', '-n', certFilename, '-i', certFilename ]; } if (executable) { try { log.info(`Trusting certificate ${certFilename}`); const result = await spawnProcess(executable, args); const success = result.code === 0; return { success, code: result.code, stdout: result.stdout, stderr: result.stderr }; } catch (e) { log.error(`Error spawning ${e}`, e); return { success: false }; } } // If we got here, then we don't know how to trust certificates on this platform return { success: false, reason: 'unsupported platform:' + os.platform() }; } } }, { method: 'POST', path: `/${secret}/untrust`, options: { validate: { payload: { certFilename: joi.string(), homeDirectory: joi.string() } }, async handler(request, h) { const { certFilename, homeDirectory } = request.payload as any; return await untrustCertificate({ certFilename, homeDirectory }); } } }, { method: 'POST', path: `/${secret}/port-proxy`, options: { validate: { payload: { target: joi.string(), localPort: joi.number(), certificatePath: joi.string(), cors: [ joi.boolean(), joi.object({ origin: joi.array().items(joi.string()), maxAge: joi.number(), headers: joi.array().items(joi.string()), additionalHeaders: joi.array().items(joi.string()), exposedHeaders: joi.array().items(joi.string()), additionalExposedHeaders: joi.array().items(joi.string()), credentials: joi.boolean() }) ] } }, handler(request, h) { const payload: any = request.payload; const proxyConfig: ProxyConfig = { target: 'http://localhost:' + payload.localPort, localUrl: payload.target, createPrivilegedPortProxy: false, cors: payload.cors || undefined, writeEtcHosts: false }; const appliedConfig = applyConfigDefaults(proxyConfig, process.cwd()); setCertPath(payload.certificatePath); const tls = /^https:/i.test( appliedConfig.localParsedUrl.protocol || '' ); const localPort = parseInt(appliedConfig.localParsedUrl.port || '0', 10) || (tls ? 443 : 80); log.info('Starting privileged port proxy'); return createProxy(appliedConfig) .then((proxy) => proxy.start().then(() => proxy)) .then((proxy) => { const cleanup = () => proxy.stop(); registerCleanup(cleanup); portProxies[localPort] = { tls, localPort: payload.localPort, cleanup }; return { success: true }; }) .catch((e) => { return { success: false, message: e.toString(), code: e.code }; }); } } }, { method: 'POST', path: `/${secret}/stop-port-proxy`, options: { validate: { payload: { port: joi.number() } }, handler() { const cleanup = portProxies[port].cleanup; delete portProxies[port]; removeCleanup(cleanup); return cleanup().then(() => ({ success: true })); } } }, { method: 'GET', path: `/${secret}/port-proxies`, handler() { return Object.keys(portProxies).reduce((all, port) => { all[port] = { tls: portProxies[port].tls, localPort: portProxies[port].localPort }; return all; }, {}); } }, { method: 'GET', path: `/${secret}/log`, handler(request, h: any) { const response = h.event({ data: { tags: ['internal'], message: 'Admin log starting' } }); useLogger( { name: 'remote-log', log(message) { // Strip the `data` tag out, as it often can't be serialized h.event({ data: { message: message.message, tags: message.tags, code: message.code } }); } }, ['app', 'request', 'debug', 'info', 'warn', 'error'] ); registerCleanup(() => { // Close the stream h.event(null); }); return response; } } ]); return server; } async function untrustCertificate(options) { const { certFilename, homeDirectory } = options; let executable: string | undefined = undefined; let args: string[] | undefined = undefined; if (os.platform() === 'darwin') { executable = 'security'; args = ['remove-trusted-cert', '-d', certFilename]; } if (os.platform() === 'linux') { executable = 'certutil'; args = ['-d', `sql:${homeDirectory}/.pki/nssdb`, '-D', '-n', certFilename]; } if (executable) { try { log.info(`Untrusting certificate ${certFilename}`); const result = await spawnProcess(executable, args); const success = result.code === 0; return { success, code: result.code, stdout: result.stdout, stderr: result.stderr }; } catch (e) { log.error(`Error spawning ${e}`, e); return { success: false }; } } // If we got here, then we don't know how to trust certificates on this platform return { success: false, reason: 'unsupported platform:' + os.platform() }; } function spawnProcess( command, args, options = {} ): Promise<{ code: number; stdout: string; stderr: string }> { return new Promise((resolve, reject) => { log.debug(`Spawning "${command}" ${args.map((a) => `"${a}"`).join(' ')}`); const process = spawn(command, args); const output: Buffer[] = []; const errors: Buffer[] = []; let stdout: Buffer; let stderr: Buffer; process.stdout.on('data', (data) => { if (typeof data === 'string') { output.push(Buffer.from(data)); } else { output.push(data); } }); process.stdout.on('end', () => { stdout = Buffer.concat(output); }); process.stderr.on('end', () => { stderr = Buffer.concat(errors); }); process.on('close', (code) => { resolve({ code: code || 0, stdout: stdout.toString('utf-8'), stderr: stderr.toString('utf-8') }); }); }); } export default adminServer;
the_stack
import { StateManager } from '../state-manager' import { del } from 'idb-keyval' export interface Todo { id: string text: string isComplete: boolean dateCreated: number } export interface State { todos: Record<string, Todo> items: string[] } export class TodoState extends StateManager<State> { isReady = false log: string[] = [] commands: string[] = [] patches: string[] = [] persists: string[] = [] get history() { return this.stack } // Internal API ------------------------- onCommand = (state: State, id?: string) => { if (id) { this.commands.push(id) } } onPatch = (state: State, id?: string) => { if (id) { this.patches.push(id) } } onPersist = (state: State, id?: string) => { if (id) { this.persists.push(id) } } onReady = () => { this.isReady = true } protected onStateWillChange = (state: State, id?: string) => { this.log.push('before:' + id) } protected onStateDidChange = (state: State, id?: string) => { this.log.push('after:' + id) } protected cleanup = (state: State) => { Object.entries(state.todos).forEach(([id, todo]) => { if (!todo) delete state.todos[id] }) return state } // Public API --------------------------- /** * Create a new todo. */ createTodo = () => { const id = Date.now().toString() return this.setState( { before: { todos: { [id]: undefined } }, after: { todos: { [id]: { id, text: '', isComplete: false, dateCreated: new Date().getTime(), }, }, }, }, 'create_todo' ) } /** * Toggle a todo between complete / not-complete. * @param id The id of the todo to change. */ toggleTodoComplete = (id: string) => { const todo = this.state.todos[id] return this.setState( { before: { todos: { [id]: { isComplete: todo.isComplete } } }, after: { todos: { [id]: { isComplete: !todo.isComplete } } }, }, 'toggle_todo' ) } /** * Patch the text of a todo. * @param id The id of the todo to change. * @param text The todo's new text. */ patchTodoText = (id: string, text: string) => { return this.patchState( { todos: { [id]: { text } }, }, 'update_todo_text' ) } /** * Set the text of a todo. (Undoable) * @param id * @param text */ setTodoText = (id: string, text: string) => { const todo = this.snapshot.todos[id] // Don't update if text is the same as the original text if (text === todo.text) return this return this.setState( { before: { todos: { [id]: { text: todo.text } } }, after: { todos: { [id]: { text } } }, }, 'set_todo_text' ) } // Test which id gets used (it should be the last one) setTodoTextWithCommandId = (id: string, text: string) => { const todo = this.snapshot.todos[id] if (text === todo.text) return this return this.setState( { id: 'save_todo_text', before: { todos: { [id]: { text: todo.text } } }, after: { todos: { [id]: { text } } }, }, 'set_todo_text' ) } // Test which id gets used (it should be the last one) setTodoTextWithJustCommandId = (id: string, text: string) => { const todo = this.snapshot.todos[id] if (text === todo.text) return this return this.setState({ id: 'save_todo_text', before: { todos: { [id]: { text: todo.text } } }, after: { todos: { [id]: { text } } }, }) } /** * Remove all todos that are marked as completed. */ clearCompleted = () => { const completed = Object.values(this.state.todos).filter( (todo) => todo.isComplete ) return this.setState( { before: { todos: Object.fromEntries(completed.map((todo) => [todo.id, todo])), }, after: { todos: Object.fromEntries( completed.map((todo) => [todo.id, undefined]) ), }, }, 'clear_completed' ) } /** * Load an entirely new state. */ loadTodos = (state: State) => { return this.replaceState(state, 'load_todos') } addItem = () => { const before = [...this.state.items] // Bad! Mutation! this.state.items.push('a') return this.setState( { before: { items: before }, after: { items: this.state.items }, }, 'add_item' ) } patchAndPersist = () => { this.patchState({ items: ['new'], }) this.persist() } } const initialState: State = { todos: { todo0: { id: 'todo0', text: 'Scrub the dog.', isComplete: false, dateCreated: 1629575640560, }, todo1: { id: 'todo1', text: 'Sharpen the dishes.', isComplete: false, dateCreated: 1629275340560, }, }, items: [], } describe('State manager', () => { it('Creates a state manager', () => { new TodoState(initialState) }) it('Patches the state', () => { del('t0') const todoState = new TodoState(initialState, 't0') todoState.patchTodoText('todo0', 'hello world') expect(todoState.state.todos.todo0.text).toBe('hello world') todoState.undo() expect(todoState.state.todos.todo0.text).toBe('hello world') }) it('Replaces the state', (done) => { del('t0') const todoState = new TodoState(initialState, 't0') todoState.loadTodos({ todos: { a: { id: 'a', text: 'placeholder a', isComplete: false, dateCreated: 1629575640560, }, b: { id: 'b', text: 'placeholder b', isComplete: false, dateCreated: 1629575640560, }, }, items: [], }) expect(todoState.state.todos.todo0).toBe(undefined) expect(todoState.state.todos.todo1).toBe(undefined) expect(todoState.state.todos.a.text).toBe('placeholder a') expect(todoState.state.todos.b.text).toBe('placeholder b') // Does NOT persist state const todoState2 = new TodoState(initialState, 't0') setTimeout(() => { expect(todoState2.state.todos.todo0.isComplete).toBe(false) done() }, 100) }) it('Does an command', (done) => { del('t0') const todoState = new TodoState(initialState, 't0') expect(todoState.state.todos.todo0.isComplete).toBe(false) todoState.toggleTodoComplete('todo0') expect(todoState.state.todos.todo0.isComplete).toBe(true) // Persists state const todoState2 = new TodoState(initialState, 't0') setTimeout(() => { expect(todoState2.state.todos.todo0.isComplete).toBe(true) done() }, 100) }) it('Undoes an command', (done) => { del('t0') const todoState = new TodoState(initialState, 't0') todoState.toggleTodoComplete('todo0') expect(todoState.state.todos.todo0.isComplete).toBe(true) todoState.undo() expect(todoState.state.todos.todo0.isComplete).toBe(false) const todoState2 = new TodoState(initialState, 't0') setTimeout(() => { expect(todoState2.state.todos.todo0.isComplete).toBe(false) done() }, 100) }) it('Redoes an command', (done) => { del('t0') const todoState = new TodoState(initialState, 't0') todoState.toggleTodoComplete('todo0') expect(todoState.state.todos.todo0.isComplete).toBe(true) todoState.undo() todoState.redo() expect(todoState.state.todos.todo0.isComplete).toBe(true) const todoState2 = new TodoState(initialState, 't0') setTimeout(() => { expect(todoState2.state.todos.todo0.isComplete).toBe(true) done() }, 100) }) it('Resets the history', (done) => { del('t0') const todoState = new TodoState(initialState, 't0') todoState.toggleTodoComplete('todo0') expect(todoState.state.todos.todo0.isComplete).toBe(true) todoState.resetHistory() todoState.undo() expect(todoState.state.todos.todo0.isComplete).toBe(true) const todoState2 = new TodoState(initialState, 't0') setTimeout(() => { expect(todoState2.state.todos.todo0.isComplete).toBe(true) done() }, 100) }) it('Resets the state', (done) => { del('t0') const todoState = new TodoState(initialState, 't0') todoState.toggleTodoComplete('todo0') expect(todoState.state.todos.todo0.isComplete).toBe(true) const todoState1 = new TodoState(initialState, 't0') todoState1.toggleTodoComplete('todo0') expect(todoState1.state.todos.todo0.isComplete).toBe(true) todoState1.reset() // The state should be reset expect(todoState1.state.todos.todo0.isComplete).toBe(false) // Undo and redo should be false expect(todoState1.canUndo).toBe(false) expect(todoState1.canRedo).toBe(false) // The reset should not be undoable todoState1.undo() expect(todoState1.state.todos.todo0.isComplete).toBe(false) // The reset state should be persisted const todoState2 = new TodoState(initialState, 't0') setTimeout(() => { expect(todoState2.state.todos.todo0.isComplete).toBe(false) done() }, 100) }) it('Replaces when the version changes', (done) => { const todoState1 = new TodoState(initialState, 'upgrade_test_1', 1) todoState1.toggleTodoComplete('todo0') expect(todoState1.state.todos.todo0.isComplete).toBe(true) // Upgrade and remove the completed todos const todoState2 = new TodoState( { ...initialState, todos: { ...initialState.todos, todo3: { ...initialState.todos.todo0, text: 'Added in new initial state!', }, }, }, 'upgrade_test_1', 2 ) // Small timeout to allow for the idb promises to resolve setTimeout(() => { expect(todoState2.state.todos.todo3?.text).toBe( 'Added in new initial state!' ) done() }, 100) }) it('Upgrades when the version changes if upgrade is provided', (done) => { const todoState1 = new TodoState(initialState, 'upgrade_test_2', 1) todoState1.toggleTodoComplete('todo0') expect(todoState1.state.todos.todo0.isComplete).toBe(true) // Upgrade and remove the completed todos const todoState2 = new TodoState( initialState, 'upgrade_test_2', 2, (prev) => { return { todos: { ...Object.fromEntries( Object.entries(prev.todos) .filter(([id, todo]) => !todo.isComplete) .map(([id, todo]) => [id, todo]) ), }, items: prev.items, } } ) // Small timeout to allow for the idb promises to resolve setTimeout(() => { expect(Object.values(todoState2.state.todos).length).toBe(1) done() }, 100) }) it('Upgrades when the version changes if upgrade is provided more', (done) => { const todoState1 = new TodoState(initialState, 'upgrade_test_3', 10) todoState1.toggleTodoComplete('todo0') expect(todoState1.state.todos.todo0.isComplete).toBe(true) // Upgrade and remove the completed todos const todoState2 = new TodoState( initialState, 'upgrade_test_3', 11, (prev) => { return { todos: { ...Object.fromEntries( Object.entries(prev.todos) .filter(([id, todo]) => !todo.isComplete) .map(([id, todo]) => [id, todo]) ), }, items: prev.items, flag: 'OKOKOK', } } ) // Small timeout to allow for the idb promises to resolve setTimeout(() => { expect(Object.values(todoState2.state.todos).length).toBe(1) expect((todoState2.state as any)['flag']).toBe('OKOKOK') done() }, 100) }) it('Correctly sets canUndo', () => { const state = new TodoState(initialState) expect(state.canUndo).toBe(false) state.toggleTodoComplete('todo0') expect(state.canUndo).toBe(true) state.undo() expect(state.canUndo).toBe(false) state.reset() expect(state.canUndo).toBe(false) }) it('Correctly sets canRedo', () => { const state = new TodoState(initialState) expect(state.canRedo).toBe(false) state.toggleTodoComplete('todo0') state.undo() expect(state.canRedo).toBe(true) state.redo() expect(state.canRedo).toBe(false) state.reset() expect(state.canRedo).toBe(false) }) it('Correctly resets, even with mutations.', () => { const state = new TodoState(initialState) state.addItem() expect(state.state.items.length).toBe(1) state.reset() expect(state.state.items.length).toBe(0) }) it('Calls onStateDidChange', () => { const state = new TodoState(initialState) state .addItem() .toggleTodoComplete('todo0') .toggleTodoComplete('todo0') .patchTodoText('todo0', 'hey') .undo() .redo() .reset() expect(state.log).toStrictEqual([ 'before:add_item', 'after:add_item', 'before:toggle_todo', 'after:toggle_todo', 'before:toggle_todo', 'after:toggle_todo', 'before:update_todo_text', 'after:update_todo_text', 'before:undo', 'after:undo', 'before:redo', 'after:redo', 'before:reset', 'after:reset', ]) }) it('Is extensible with a constructor', () => { interface State { count: 0 } class ExtendState extends StateManager<State> { constructor() { super({ count: 0 }, 'someId') } } new ExtendState() }) it('Is patches and persists', (done) => { const state = new TodoState(initialState, 'pp-test') state.patchAndPersist() expect(state.state.items.length).toBe(1) state.undo() expect(state.state.items.length).toBe(1) const state2 = new TodoState(initialState, 'pp-test') setTimeout(() => { expect(state2.state.items.length).toBe(1) done() }, 100) }) it('Allows classes to expose the stack property', () => { const todoState = new TodoState(initialState, 'pp-test') todoState.setTodoTextWithJustCommandId('todo0', 'hey world') expect(todoState.history).toMatchSnapshot('history_stack') }) it('Uses the command id OR the provided id', () => { const todoState = new TodoState(initialState, 'pp-test') todoState.setTodoTextWithCommandId('todo0', 'hey world') expect(todoState.log).toStrictEqual([ 'before:set_todo_text', 'after:set_todo_text', ]) expect(todoState.history).toMatchSnapshot('history_stack') }) it('Uses the command id if id arg is not provided', () => { const todoState = new TodoState(initialState, 'pp-test') todoState.setTodoTextWithJustCommandId('todo0', 'hey world') expect(todoState.log).toStrictEqual([ 'before:save_todo_text', 'after:save_todo_text', ]) expect(todoState.history).toMatchSnapshot('history_stack') }) it('Calls onReady if an id is set', async () => { const todoState = new TodoState(initialState, 'pp-test-2') await todoState.ready expect(todoState.isReady).toBe(true) }) it('Calls onReady if an id is not set', async () => { const todoState = new TodoState(initialState) await todoState.ready expect(todoState.isReady).toBe(true) }) it('Calls onPersist after persisting state.', async () => { const state = new TodoState(initialState) .addItem() .toggleTodoComplete('todo0') .toggleTodoComplete('todo0') .patchTodoText('todo0', 'hey') .undo() .redo() .reset() await state.ready expect(state.persists).toStrictEqual([ 'add_item', 'toggle_todo', 'toggle_todo', 'undo', 'undo', 'reset', ]) }) it('Calls onPatch after patching state.', async () => { const state = new TodoState(initialState) .addItem() .toggleTodoComplete('todo0') .toggleTodoComplete('todo0') .patchTodoText('todo0', 'hey') .undo() .redo() .reset() await state.ready expect(state.patches).toStrictEqual(['update_todo_text']) }) it('Calls onCommand after running a command.', async () => { const state = new TodoState(initialState) .addItem() .toggleTodoComplete('todo0') .toggleTodoComplete('todo0') .patchTodoText('todo0', 'hey') .undo() .redo() .reset() await state.ready expect(state.commands).toStrictEqual([ 'add_item', 'toggle_todo', 'toggle_todo', ]) }) })
the_stack
module android.view { import Activity = android.app.Activity; import Intent = android.content.Intent; import Drawable = android.graphics.drawable.Drawable; import Menu = android.view.Menu; import View = android.view.View; /** * Interface for direct access to a previously created menu item. * <p> * An Item is returned by calling one of the {@link android.view.Menu#add} * methods. * <p> * For a feature set of specific menu types, see {@link Menu}. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ export class MenuItem { private mId:number = 0; private mGroup:number = 0; private mCategoryOrder:number = 0; private mOrdering:number = 0; private mTitle:string; private mIntent:Intent; private mIconDrawable:Drawable; private mVisible = true; private mEnable = true; private mClickListener:MenuItem.OnMenuItemClickListener; private mActionView:View; private mMenu:Menu; /** * Instantiates this menu item. * * @param group Item ordering grouping control. The item will be added after all other * items whose order is <= this number, and before any that are larger than * it. This can also be used to define groups of items for batch state * changes. Normally use 0. * @param id Unique item ID. Use 0 if you do not need a unique ID. * @param categoryOrder The ordering for this item. * @param title The text to display for the item. */ constructor(menu:Menu, group:number, id:number, categoryOrder:number, ordering:number, title:string) { this.mMenu = menu; this.mId = id; this.mGroup = group; this.mCategoryOrder = categoryOrder; this.mOrdering = ordering; this.mTitle = title; } /** * Return the identifier for this menu item. The identifier can not * be changed after the menu is created. * * @return The menu item's identifier. */ getItemId():number { return this.mId; } /** * Return the group identifier that this menu item is part of. The group * identifier can not be changed after the menu is created. * * @return The menu item's group identifier. */ getGroupId():number { return this.mGroup; } /** * Return the category and order within the category of this item. This * item will be shown before all items (within its category) that have * order greater than this value. * <p> * An order integer contains the item's category (the upper bits of the * integer; set by or/add the category with the order within the * category) and the ordering of the item within that category (the * lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM}, * {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE}, * {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list. * * @return The order of this item. */ getOrder():number { return this.mOrdering; } /** * Change the title associated with this item. * * @param title The new text to be displayed. * @return This Item so additional setters can be called. */ setTitle(title:string):MenuItem { this.mTitle = title; return this; } ///** // * Change the title associated with this item. // * <p> // * Some menu types do not sufficient space to show the full title, and // * instead a condensed title is preferred. See {@link Menu} for more // * information. // * // * @param title The resource id of the new text to be displayed. // * @return This Item so additional setters can be called. // * @see #setTitleCondensed(CharSequence) // */ //setTitle(title:number):MenuItem ; /** * Retrieve the current title of the item. * * @return The title. */ getTitle():string { return this.mTitle; } ///** // * Change the condensed title associated with this item. The condensed // * title is used in situations where the normal title may be too long to // * be displayed. // * // * @param title The new text to be displayed as the condensed title. // * @return This Item so additional setters can be called. // */ //setTitleCondensed(title:string):MenuItem ; // ///** // * Retrieve the current condensed title of the item. If a condensed // * title was never set, it will return the normal title. // * // * @return The condensed title, if it exists. // * Otherwise the normal title. // */ //getTitleCondensed():string ; /** * Change the icon associated with this item. This icon will not always be * shown, so the title should be sufficient in describing this item. See * {@link Menu} for the menu types that support icons. * * @param icon The new icon (as a Drawable) to be displayed. * @return This Item so additional setters can be called. */ setIcon(icon:Drawable):MenuItem { this.mIconDrawable = icon; return this; } ///** // * Change the icon associated with this item. This icon will not always be // * shown, so the title should be sufficient in describing this item. See // * {@link Menu} for the menu types that support icons. // * <p> // * This method will set the resource ID of the icon which will be used to // * lazily get the Drawable when this item is being shown. // * // * @param iconRes The new icon (as a resource ID) to be displayed. // * @return This Item so additional setters can be called. // */ //setIcon(iconRes:number):MenuItem ; /** * Returns the icon for this item as a Drawable (getting it from resources if it hasn't been * loaded before). * * @return The icon as a Drawable. */ getIcon():Drawable { return this.mIconDrawable; } /** * Change the Intent associated with this item. By default there is no * Intent associated with a menu item. If you set one, and nothing * else handles the item, then the default behavior will be to call * {@link android.content.Context#startActivity} with the given Intent. * * <p>Note that setIntent() can not be used with the versions of * {@link Menu#add} that take a Runnable, because {@link Runnable#run} * does not return a value so there is no way to tell if it handled the * item. In this case it is assumed that the Runnable always handles * the item, and the intent will never be started. * * @see #getIntent * @param intent The Intent to associated with the item. This Intent * object is <em>not</em> copied, so be careful not to * modify it later. * @return This Item so additional setters can be called. */ setIntent(intent:Intent):MenuItem { this.mIntent = intent; return this; } /** * Return the Intent associated with this item. This returns a * reference to the Intent which you can change as desired to modify * what the Item is holding. * * @see #setIntent * @return Returns the last value supplied to {@link #setIntent}, or * null. */ getIntent():Intent { return this.mIntent; } // ///** // * Change both the numeric and alphabetic shortcut associated with this // * item. Note that the shortcut will be triggered when the key that // * generates the given character is pressed alone or along with with the alt // * key. Also note that case is not significant and that alphabetic shortcut // * characters will be displayed in lower case. // * <p> // * See {@link Menu} for the menu types that support shortcuts. // * // * @param numericChar The numeric shortcut key. This is the shortcut when // * using a numeric (e.g., 12-key) keyboard. // * @param alphaChar The alphabetic shortcut key. This is the shortcut when // * using a keyboard with alphabetic keys. // * @return This Item so additional setters can be called. // */ //setShortcut(numericChar:string, alphaChar:string):MenuItem ; // ///** // * Change the numeric shortcut associated with this item. // * <p> // * See {@link Menu} for the menu types that support shortcuts. // * // * @param numericChar The numeric shortcut key. This is the shortcut when // * using a 12-key (numeric) keyboard. // * @return This Item so additional setters can be called. // */ //setNumericShortcut(numericChar:string):MenuItem ; // ///** // * Return the char for this menu item's numeric (12-key) shortcut. // * // * @return Numeric character to use as a shortcut. // */ //getNumericShortcut():string ; // ///** // * Change the alphabetic shortcut associated with this item. The shortcut // * will be triggered when the key that generates the given character is // * pressed alone or along with with the alt key. Case is not significant and // * shortcut characters will be displayed in lower case. Note that menu items // * with the characters '\b' or '\n' as shortcuts will get triggered by the // * Delete key or Carriage Return key, respectively. // * <p> // * See {@link Menu} for the menu types that support shortcuts. // * // * @param alphaChar The alphabetic shortcut key. This is the shortcut when // * using a keyboard with alphabetic keys. // * @return This Item so additional setters can be called. // */ //setAlphabeticShortcut(alphaChar:string):MenuItem ; // ///** // * Return the char for this menu item's alphabetic shortcut. // * // * @return Alphabetic character to use as a shortcut. // */ //getAlphabeticShortcut():string ; // ///** // * Control whether this item can display a check mark. Setting this does // * not actually display a check mark (see {@link #setChecked} for that); // * rather, it ensures there is room in the item in which to display a // * check mark. // * <p> // * See {@link Menu} for the menu types that support check marks. // * // * @param checkable Set to true to allow a check mark, false to // * disallow. The default is false. // * @see #setChecked // * @see #isCheckable // * @see Menu#setGroupCheckable // * @return This Item so additional setters can be called. // */ //setCheckable(checkable:boolean):MenuItem ; // ///** // * Return whether the item can currently display a check mark. // * // * @return If a check mark can be displayed, returns true. // * // * @see #setCheckable // */ //isCheckable():boolean ; // ///** // * Control whether this item is shown with a check mark. Note that you // * must first have enabled checking with {@link #setCheckable} or else // * the check mark will not appear. If this item is a member of a group that contains // * mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)}, // * the other items in the group will be unchecked. // * <p> // * See {@link Menu} for the menu types that support check marks. // * // * @see #setCheckable // * @see #isChecked // * @see Menu#setGroupCheckable // * @param checked Set to true to display a check mark, false to hide // * it. The default value is false. // * @return This Item so additional setters can be called. // */ //setChecked(checked:boolean):MenuItem ; // ///** // * Return whether the item is currently displaying a check mark. // * // * @return If a check mark is displayed, returns true. // * // * @see #setChecked // */ //isChecked():boolean ; /** * Sets the visibility of the menu item. Even if a menu item is not visible, * it may still be invoked via its shortcut (to completely disable an item, * set it to invisible and {@link #setEnabled(boolean) disabled}). * * @param visible If true then the item will be visible; if false it is * hidden. * @return This Item so additional setters can be called. */ setVisible(visible:boolean):MenuItem { this.mVisible = visible; return this; } /** * Return the visibility of the menu item. * * @return If true the item is visible; else it is hidden. */ isVisible():boolean { return this.mVisible; } /** * Sets whether the menu item is enabled. Disabling a menu item will not * allow it to be invoked via its shortcut. The menu item will still be * visible. * * @param enabled If true then the item will be invokable; if false it is * won't be invokable. * @return This Item so additional setters can be called. */ setEnabled(enabled:boolean):MenuItem { this.mEnable = enabled; return this; } /** * Return the enabled state of the menu item. * * @return If true the item is enabled and hence invokable; else it is not. */ isEnabled():boolean { return this.mEnable; } ///** // * Check whether this item has an associated sub-menu. I.e. it is a // * sub-menu of another menu. // * // * @return If true this item has a menu; else it is a // * normal item. // */ //hasSubMenu():boolean ; // ///** // * Get the sub-menu to be invoked when this item is selected, if it has // * one. See {@link #hasSubMenu()}. // * // * @return The associated menu if there is one, else null // */ //getSubMenu():SubMenu ; /** * Set a custom listener for invocation of this menu item. In most * situations, it is more efficient and easier to use * {@link Activity#onOptionsItemSelected(MenuItem)} or * {@link Activity#onContextItemSelected(MenuItem)}. * * @param menuItemClickListener The object to receive invokations. * @return This Item so additional setters can be called. * @see Activity#onOptionsItemSelected(MenuItem) * @see Activity#onContextItemSelected(MenuItem) */ setOnMenuItemClickListener(menuItemClickListener:MenuItem.OnMenuItemClickListener):MenuItem { this.mClickListener = menuItemClickListener; return this; } /** * Set an action view for this menu item. An action view will be displayed in place * of an automatically generated menu item element in the UI when this item is shown * as an action within a parent. * <p> * <strong>Note:</strong> Setting an action view overrides the action provider * set via {@link #setActionProvider(ActionProvider)}. * </p> * * @param view View to use for presenting this item to the user. * @return This Item so additional setters can be called. * * @see #setShowAsAction(int) */ setActionView(view:View):MenuItem { this.mActionView = view; return this; } /** * Returns the currently set action view for this menu item. * * @return This item's action view * * @see #setActionView(View) * @see #setShowAsAction(int) */ getActionView():View { return this.mActionView; } /** * Invokes the item by calling various listeners or callbacks. * * @return true if the invocation was handled, false otherwise */ invoke():boolean { if (this.mClickListener != null && this.mClickListener.onMenuItemClick(this)) { return true; } if (this.mMenu.dispatchMenuItemSelected(this.mMenu.getRootMenu(), this)) { return true; } //if (this.mItemCallback != null) { // this.mItemCallback.run(); // return true; //} if (this.mIntent != null) { try { (<android.app.Activity>this.mMenu.getContext()).startActivity(this.mIntent); return true; } catch (e){ android.util.Log.e("MenuItem", "Can't find activity to handle intent; ignoring", e); } } //if (this.mActionProvider != null && this.mActionProvider.onPerformDefaultAction()) { // return true; //} return false; } } export module MenuItem{ /** * Interface definition for a callback to be invoked when a menu item is * clicked. * * @see Activity#onContextItemSelected(MenuItem) * @see Activity#onOptionsItemSelected(MenuItem) */ export interface OnMenuItemClickListener { /** * Called when a menu item has been invoked. This is the first code * that is executed; if it returns true, no other callbacks will be * executed. * * @param item The menu item that was invoked. * * @return Return true to consume this click and prevent others from * executing. */ onMenuItemClick(item:MenuItem):boolean ; } } }
the_stack
import * as Debug from 'debug'; import * as path from 'path'; import * as depGraphLib from '@snyk/dep-graph'; import * as snyk from '..'; import { apiOrOAuthTokenExists, getAuthHeader } from '../api-token'; import { makeRequest } from '../request'; import config from '../config'; import * as os from 'os'; const get = require('lodash.get'); import { isCI } from '../is-ci'; import * as analytics from '../analytics'; import { DepTree, MonitorMeta, MonitorResult, PolicyOptions, MonitorOptions, Options, Contributor, ProjectAttributes, Tag, } from '../types'; import * as projectMetadata from '../project-metadata'; import { MonitorError, ConnectionTimeoutError, FailedToRunTestError, } from '../errors'; import { pruneGraph } from '../prune'; import { GRAPH_SUPPORTED_PACKAGE_MANAGERS } from '../package-managers'; import { countTotalDependenciesInTree } from './count-total-deps-in-tree'; import { filterOutMissingDeps } from './filter-out-missing-deps'; import { dropEmptyDeps } from './drop-empty-deps'; import { pruneTree } from './prune-dep-tree'; import { findAndLoadPolicy } from '../policy'; import { PluginMetadata } from '@snyk/cli-interface/legacy/plugin'; import { CallGraph, CallGraphError, ScannedProject, } from '@snyk/cli-interface/legacy/common'; import { isGitTarget } from '../project-metadata/types'; import { serializeCallGraphWithMetrics } from '../reachable-vulns'; import { getNameDepTree, getNameDepGraph, getProjectName, getTargetFile, } from './utils'; import { countPathsToGraphRoot } from '../utils'; import * as alerts from '../alerts'; import { abridgeErrorMessage } from '../error-format'; const debug = Debug('snyk'); const ANALYTICS_PAYLOAD_MAX_LENGTH = 1024; interface MonitorBody { meta: Meta; policy: string; package?: DepTree; callGraph?: CallGraph; target: {}; targetFileRelativePath: string; targetFile: string; contributors?: Contributor[]; } interface Meta { method?: string; hostname: string; id: string; ci: boolean; pid: number; node: string; master: boolean; name: string; version: string; org?: string; pluginName: string; pluginRuntime: string; dockerImageId?: string; dockerBaseImage?: string; projectName: string; } export async function monitor( root: string, meta: MonitorMeta, scannedProject: ScannedProject, options: Options & MonitorOptions & PolicyOptions, pluginMeta: PluginMetadata, targetFileRelativePath?: string, contributors?: Contributor[], projectAttributes?: ProjectAttributes, tags?: Tag[], ): Promise<MonitorResult> { apiOrOAuthTokenExists(); const packageManager = meta.packageManager; analytics.add('packageManager', packageManager); analytics.add('isDocker', !!meta.isDocker); if (scannedProject.depGraph) { return await monitorDepGraph( root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors, projectAttributes, tags, ); } if (GRAPH_SUPPORTED_PACKAGE_MANAGERS.includes(packageManager)) { return await monitorDepGraphFromDepTree( root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors, projectAttributes, tags, ); } return await monitorDepTree( root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors, projectAttributes, tags, ); } async function monitorDepTree( root: string, meta: MonitorMeta, scannedProject: ScannedProject, pluginMeta: PluginMetadata, options: MonitorOptions & PolicyOptions, targetFileRelativePath?: string, contributors?: Contributor[], projectAttributes?: ProjectAttributes, tags?: Tag[], ): Promise<MonitorResult> { let treeMissingDeps: string[] = []; const packageManager = meta.packageManager; let depTree = scannedProject.depTree; if (!depTree) { debug( 'scannedProject is missing depGraph or depTree, cannot run test/monitor', ); throw new FailedToRunTestError( 'Your monitor request could not be completed. Please email support@snyk.io', ); } let prePruneDepCount; if (meta.prune) { debug('prune used, counting total dependencies'); prePruneDepCount = countTotalDependenciesInTree(depTree); analytics.add('prePruneDepCount', prePruneDepCount); debug('total dependencies: %d', prePruneDepCount); debug('pruning dep tree'); depTree = await pruneTree(depTree, meta.packageManager); debug('finished pruning dep tree'); } if (['npm', 'yarn'].includes(meta.packageManager)) { const { filteredDepTree, missingDeps } = filterOutMissingDeps(depTree); depTree = filteredDepTree; treeMissingDeps = missingDeps; } let targetFileDir; if (targetFileRelativePath) { const { dir } = path.parse(targetFileRelativePath); targetFileDir = dir; } const policy = await findAndLoadPolicy( root, meta.isDocker ? 'docker' : packageManager!, options, depTree, targetFileDir, ); const target = await projectMetadata.getInfo(scannedProject, meta, depTree); if (isGitTarget(target) && target.branch) { analytics.add('targetBranch', target.branch); } depTree = dropEmptyDeps(depTree); let callGraphPayload; if ( options.reachableVulns && (scannedProject.callGraph as CallGraphError)?.innerError ) { const err = scannedProject.callGraph as CallGraphError; analytics.add( 'callGraphError', abridgeErrorMessage( err.innerError.toString(), ANALYTICS_PAYLOAD_MAX_LENGTH, ), ); alerts.registerAlerts([ { type: 'error', name: 'missing-call-graph', msg: err.message, }, ]); } else if (scannedProject.callGraph) { const { callGraph, nodeCount, edgeCount } = serializeCallGraphWithMetrics( scannedProject.callGraph as CallGraph, ); debug( `Adding call graph to payload, node count: ${nodeCount}, edge count: ${edgeCount}`, ); const callGraphMetrics = get(pluginMeta, 'meta.callGraphMetrics', {}); analytics.add('callGraphMetrics', { callGraphEdgeCount: edgeCount, callGraphNodeCount: nodeCount, ...callGraphMetrics, }); callGraphPayload = callGraph; } if (!depTree) { debug( 'scannedProject is missing depGraph or depTree, cannot run test/monitor', ); throw new FailedToRunTestError( 'Your monitor request could not be completed. Please email support@snyk.io', ); } const { res, body } = await makeRequest({ body: { meta: { method: meta.method, hostname: os.hostname(), id: snyk.id || depTree.name, ci: isCI(), pid: process.pid, node: process.version, master: snyk.config.isMaster, name: getNameDepTree(scannedProject, depTree, meta), version: depTree.version, org: config.org ? decodeURIComponent(config.org) : undefined, pluginName: pluginMeta.name, pluginRuntime: pluginMeta.runtime, missingDeps: treeMissingDeps, dockerImageId: pluginMeta.dockerImageId, dockerBaseImage: depTree.docker ? depTree.docker.baseImage : undefined, dockerfileLayers: depTree.docker ? depTree.docker.dockerfileLayers : undefined, projectName: getProjectName(scannedProject, meta), prePruneDepCount, // undefined unless 'prune' is used, monitorGraph: false, versionBuildInfo: JSON.stringify(scannedProject.meta?.versionBuildInfo), gradleProjectName: scannedProject.meta?.gradleProjectName, platform: scannedProject.meta?.platform, }, policy: policy ? policy.toString() : undefined, package: depTree, callGraph: callGraphPayload, // we take the targetFile from the plugin, // because we want to send it only for specific package-managers target, // WARNING: be careful changing this as it affects project uniqueness targetFile: getTargetFile(scannedProject, pluginMeta), targetFileRelativePath, targetReference: meta.targetReference, contributors, projectAttributes, tags, } as MonitorBody, gzip: true, method: 'PUT', headers: { authorization: getAuthHeader(), 'content-encoding': 'gzip', }, url: config.API + '/monitor/' + packageManager, json: true, }); if (res.statusCode && res.statusCode >= 200 && res.statusCode <= 299) { return body as MonitorResult; } else { const userMessage = body && body.userMessage; if (!userMessage && res.statusCode === 504) { throw new ConnectionTimeoutError(); } else { throw new MonitorError(res.statusCode, userMessage); } } } export async function monitorDepGraph( root: string, meta: MonitorMeta, scannedProject: ScannedProject, pluginMeta: PluginMetadata, options: MonitorOptions & PolicyOptions, targetFileRelativePath?: string, contributors?: Contributor[], projectAttributes?: ProjectAttributes, tags?: Tag[], ): Promise<MonitorResult> { const packageManager = meta.packageManager; analytics.add('monitorDepGraph', true); let depGraph = scannedProject.depGraph; if (!depGraph) { debug( 'scannedProject is missing depGraph or depTree, cannot run test/monitor', ); throw new FailedToRunTestError( 'Your monitor request could not be completed. Please email support@snyk.io', ); } let targetFileDir; if (targetFileRelativePath) { const { dir } = path.parse(targetFileRelativePath); targetFileDir = dir; } const policy = await findAndLoadPolicy( root, meta.isDocker ? 'docker' : packageManager!, options, undefined, targetFileDir, ); const target = await projectMetadata.getInfo(scannedProject, meta); if (isGitTarget(target) && target.branch) { analytics.add('targetBranch', target.branch); } const pruneIsRequired = options.pruneRepeatedSubdependencies; depGraph = await pruneGraph(depGraph, packageManager, pruneIsRequired); let callGraphPayload; if ( options.reachableVulns && (scannedProject.callGraph as CallGraphError)?.innerError ) { const err = scannedProject.callGraph as CallGraphError; analytics.add( 'callGraphError', abridgeErrorMessage( err.innerError.toString(), ANALYTICS_PAYLOAD_MAX_LENGTH, ), ); alerts.registerAlerts([ { type: 'error', name: 'missing-call-graph', msg: err.message, }, ]); } else if (scannedProject.callGraph) { const { callGraph, nodeCount, edgeCount } = serializeCallGraphWithMetrics( scannedProject.callGraph as CallGraph, ); debug( `Adding call graph to payload, node count: ${nodeCount}, edge count: ${edgeCount}`, ); const callGraphMetrics = get(pluginMeta, 'meta.callGraphMetrics', {}); analytics.add('callGraphMetrics', { callGraphEdgeCount: edgeCount, callGraphNodeCount: nodeCount, ...callGraphMetrics, }); callGraphPayload = callGraph; } if (!depGraph) { debug( 'scannedProject is missing depGraph or depTree, cannot run test/monitor', ); throw new FailedToRunTestError( 'Your monitor request could not be completed. Please email support@snyk.io', ); } const { res, body } = await makeRequest({ body: { meta: { method: meta.method, hostname: os.hostname(), id: snyk.id || depGraph.rootPkg.name, ci: isCI(), pid: process.pid, node: process.version, master: snyk.config.isMaster, name: getNameDepGraph(scannedProject, depGraph, meta), version: depGraph.rootPkg.version, org: config.org ? decodeURIComponent(config.org) : undefined, pluginName: pluginMeta.name, pluginRuntime: pluginMeta.runtime, projectName: getProjectName(scannedProject, meta), monitorGraph: true, versionBuildInfo: JSON.stringify(scannedProject.meta?.versionBuildInfo), gradleProjectName: scannedProject.meta?.gradleProjectName, }, policy: policy ? policy.toString() : undefined, depGraphJSON: depGraph, // depGraph will be auto serialized to JSON on send // we take the targetFile from the plugin, // because we want to send it only for specific package-managers target, targetFile: getTargetFile(scannedProject, pluginMeta), targetFileRelativePath, targetReference: meta.targetReference, contributors, callGraph: callGraphPayload, projectAttributes, tags, } as MonitorBody, gzip: true, method: 'PUT', headers: { authorization: getAuthHeader(), 'content-encoding': 'gzip', }, url: `${config.API}/monitor/${packageManager}/graph`, json: true, }); if (res.statusCode && res.statusCode >= 200 && res.statusCode <= 299) { return body as MonitorResult; } else { const userMessage = body && body.userMessage; if (!userMessage && res.statusCode === 504) { throw new ConnectionTimeoutError(); } else { throw new MonitorError(res.statusCode, userMessage); } } } async function monitorDepGraphFromDepTree( root: string, meta: MonitorMeta, scannedProject: ScannedProject, pluginMeta: PluginMetadata, options: MonitorOptions & PolicyOptions, targetFileRelativePath?: string, contributors?: Contributor[], projectAttributes?: ProjectAttributes, tags?: Tag[], ): Promise<MonitorResult> { const packageManager = meta.packageManager; let treeMissingDeps: string[] | undefined; let depTree = scannedProject.depTree; if (!depTree) { debug( 'scannedProject is missing depGraph or depTree, cannot run test/monitor', ); throw new FailedToRunTestError( 'Your monitor request could not be completed. Please email support@snyk.io', ); } let targetFileDir; if (targetFileRelativePath) { const { dir } = path.parse(targetFileRelativePath); targetFileDir = dir; } const policy = await findAndLoadPolicy( root, meta.isDocker ? 'docker' : packageManager!, options, // TODO: fix this and send only send when we used resolve-deps for node // it should be a ExpandedPkgTree type instead depTree, targetFileDir, ); if (['npm', 'yarn'].includes(meta.packageManager)) { const { filteredDepTree, missingDeps } = filterOutMissingDeps(depTree); depTree = filteredDepTree; treeMissingDeps = missingDeps; } const depGraph: depGraphLib.DepGraph = await depGraphLib.legacy.depTreeToGraph( depTree, packageManager, ); const target = await projectMetadata.getInfo(scannedProject, meta, depTree); if (isGitTarget(target) && target.branch) { analytics.add('targetBranch', target.branch); } let prunedGraph = depGraph; let prePruneDepCount; if (meta.prune) { debug('Trying to prune the graph'); prePruneDepCount = countPathsToGraphRoot(depGraph); debug('pre prunedPathsCount: ' + prePruneDepCount); prunedGraph = await pruneGraph(depGraph, packageManager, meta.prune); } if (!depTree) { debug( 'scannedProject is missing depGraph or depTree, cannot run test/monitor', ); throw new FailedToRunTestError( 'Your monitor request could not be completed. Please email support@snyk.io', ); } const { res, body } = await makeRequest({ body: { meta: { method: meta.method, hostname: os.hostname(), id: snyk.id || depTree.name, ci: isCI(), pid: process.pid, node: process.version, master: snyk.config.isMaster, name: getNameDepGraph(scannedProject, depGraph, meta), version: depGraph.rootPkg.version, org: config.org ? decodeURIComponent(config.org) : undefined, pluginName: pluginMeta.name, pluginRuntime: pluginMeta.runtime, dockerImageId: pluginMeta.dockerImageId, dockerBaseImage: depTree.docker ? depTree.docker.baseImage : undefined, dockerfileLayers: depTree.docker ? depTree.docker.dockerfileLayers : undefined, projectName: getProjectName(scannedProject, meta), prePruneDepCount, // undefined unless 'prune' is used missingDeps: treeMissingDeps, monitorGraph: true, }, policy: policy ? policy.toString() : undefined, depGraphJSON: prunedGraph, // depGraph will be auto serialized to JSON on send // we take the targetFile from the plugin, // because we want to send it only for specific package-managers target, targetFile: getTargetFile(scannedProject, pluginMeta), targetFileRelativePath, targetReference: meta.targetReference, contributors, projectAttributes, tags, } as MonitorBody, gzip: true, method: 'PUT', headers: { authorization: getAuthHeader(), 'content-encoding': 'gzip', }, url: `${config.API}/monitor/${packageManager}/graph`, json: true, }); if (res.statusCode && res.statusCode >= 200 && res.statusCode <= 299) { return body as MonitorResult; } else { const userMessage = body && body.userMessage; if (!userMessage && res.statusCode === 504) { throw new ConnectionTimeoutError(); } else { throw new MonitorError(res.statusCode, userMessage); } } }
the_stack
import {makeConfig, SHADOWSOCKS_URI, SIP002_URI} from 'ShadowsocksConfig'; import * as uuidv4 from 'uuidv4'; import * as errors from '../model/errors'; import * as events from '../model/events'; import {Server, ServerRepository} from '../model/server'; import {ShadowsocksConfig} from './config'; import {NativeNetworking} from './net'; import {Tunnel, TunnelFactory, TunnelStatus} from './tunnel'; export class OutlineServer implements Server { // We restrict to AEAD ciphers because unsafe ciphers are not supported in go-tun2socks. // https://shadowsocks.org/en/spec/AEAD-Ciphers.html private static readonly SUPPORTED_CIPHERS = ['chacha20-ietf-poly1305', 'aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm']; errorMessageId?: string; private config: ShadowsocksConfig; constructor( public readonly id: string, public readonly accessKey: string, private _name: string, private tunnel: Tunnel, private net: NativeNetworking, private eventQueue: events.EventQueue) { this.config = accessKeyToShadowsocksConfig(accessKey); this.tunnel.onStatusChange((status: TunnelStatus) => { let statusEvent: events.OutlineEvent; switch (status) { case TunnelStatus.CONNECTED: statusEvent = new events.ServerConnected(this); break; case TunnelStatus.DISCONNECTED: statusEvent = new events.ServerDisconnected(this); break; case TunnelStatus.RECONNECTING: statusEvent = new events.ServerReconnecting(this); break; default: console.warn(`Received unknown tunnel status ${status}`); return; } eventQueue.enqueue(statusEvent); }); } get name() { return this._name; } set name(newName: string) { this._name = newName; this.config.name = newName; } get address() { return `${this.config.host}:${this.config.port}`; } get isOutlineServer() { return this.accessKey.includes('outline=1'); } async connect() { try { await this.tunnel.start(this.config); } catch (e) { // e originates in "native" code: either Cordova or Electron's main process. // Because of this, we cannot assume "instanceof OutlinePluginError" will work. if (e.errorCode) { throw errors.fromErrorCode(e.errorCode); } throw e; } } async disconnect() { try { await this.tunnel.stop(); } catch (e) { // All the plugins treat disconnection errors as ErrorCode.UNEXPECTED. throw new errors.RegularNativeError(); } } checkRunning(): Promise<boolean> { return this.tunnel.isRunning(); } checkReachable(): Promise<boolean> { return this.net.isServerReachable(this.config.host, this.config.port); } static isServerCipherSupported(cipher?: string) { return cipher !== undefined && OutlineServer.SUPPORTED_CIPHERS.includes(cipher); } } // DEPRECATED: V0 server persistence format. export interface ServersStorageV0 { [serverId: string]: ShadowsocksConfig; } // V1 server persistence format. export type ServersStorageV1 = OutlineServerJson[]; interface OutlineServerJson { readonly id: string; readonly accessKey: string; readonly name: string; } // Maintains a persisted set of servers and liaises with the core. export class OutlineServerRepository implements ServerRepository { // Name by which servers are saved to storage. public static readonly SERVERS_STORAGE_KEY_V0 = 'servers'; public static readonly SERVERS_STORAGE_KEY = 'servers_v1'; private serverById!: Map<string, OutlineServer>; private lastForgottenServer: OutlineServer|null = null; constructor( private readonly net: NativeNetworking, private readonly createTunnel: TunnelFactory, private eventQueue: events.EventQueue, private storage: Storage) { this.loadServers(); } getAll() { return Array.from(this.serverById.values()); } getById(serverId: string) { return this.serverById.get(serverId); } add(accessKey: string) { const config = accessKeyToShadowsocksConfig(accessKey); const server = this.createServer(uuidv4(), accessKey, config.name); this.serverById.set(server.id, server); this.storeServers(); this.eventQueue.enqueue(new events.ServerAdded(server)); } rename(serverId: string, newName: string) { const server = this.serverById.get(serverId); if (!server) { console.warn(`Cannot rename nonexistent server ${serverId}`); return; } server.name = newName; this.storeServers(); this.eventQueue.enqueue(new events.ServerRenamed(server)); } forget(serverId: string) { const server = this.serverById.get(serverId); if (!server) { console.warn(`Cannot remove nonexistent server ${serverId}`); return; } this.serverById.delete(serverId); this.lastForgottenServer = server; this.storeServers(); this.eventQueue.enqueue(new events.ServerForgotten(server)); } undoForget(serverId: string) { if (!this.lastForgottenServer) { console.warn('No forgotten server to unforget'); return; } else if (this.lastForgottenServer.id !== serverId) { console.warn('id of forgotten server', this.lastForgottenServer, 'does not match', serverId); return; } this.serverById.set(this.lastForgottenServer.id, this.lastForgottenServer); this.storeServers(); this.eventQueue.enqueue(new events.ServerForgetUndone(this.lastForgottenServer)); this.lastForgottenServer = null; } validateAccessKey(accessKey: string) { const alreadyAddedServer = this.serverFromAccessKey(accessKey); if (alreadyAddedServer) { throw new errors.ServerAlreadyAdded(alreadyAddedServer); } let config = null; try { config = SHADOWSOCKS_URI.parse(accessKey); } catch (error) { throw new errors.ServerUrlInvalid(error.message || 'failed to parse access key'); } if (config.host.isIPv6) { throw new errors.ServerIncompatible('unsupported IPv6 host address'); } if (!OutlineServer.isServerCipherSupported(config.method.data)) { throw new errors.ShadowsocksUnsupportedCipher(config.method.data || 'unknown'); } } private serverFromAccessKey(accessKey: string): OutlineServer|undefined { for (const server of this.serverById.values()) { if (accessKeysMatch(accessKey, server.accessKey)) { return server; } } return undefined; } private storeServers() { const servers: ServersStorageV1 = []; for (const server of this.serverById.values()) { servers.push({ id: server.id, accessKey: server.accessKey, name: server.name, }); } const json = JSON.stringify(servers); this.storage.setItem(OutlineServerRepository.SERVERS_STORAGE_KEY, json); } // Loads servers from storage, raising an error if there is any problem loading. private loadServers() { if (this.storage.getItem(OutlineServerRepository.SERVERS_STORAGE_KEY)) { console.debug('server storage migrated to V1'); this.loadServersV1(); return; } this.loadServersV0(); } private loadServersV0() { this.serverById = new Map<string, OutlineServer>(); const serversJson = this.storage.getItem(OutlineServerRepository.SERVERS_STORAGE_KEY_V0); if (!serversJson) { console.debug(`no V0 servers found in storage`); return; } let configById: ServersStorageV0 = {}; try { configById = JSON.parse(serversJson); } catch (e) { throw new Error(`could not parse saved V0 servers: ${e.message}`); } for (const serverId of Object.keys(configById)) { const config = configById[serverId]; try { this.loadServer( {id: serverId, accessKey: shadowsocksConfigToAccessKey(config), name: config.name}); } catch (e) { // Don't propagate so other stored servers can be created. console.error(e); } } } private loadServersV1() { this.serverById = new Map<string, OutlineServer>(); const serversStorageJson = this.storage.getItem(OutlineServerRepository.SERVERS_STORAGE_KEY); if (!serversStorageJson) { console.debug(`no servers found in storage`); return; } let serversJson: ServersStorageV1 = []; try { serversJson = JSON.parse(serversStorageJson); } catch (e) { throw new Error(`could not parse saved servers: ${e.message}`); } for (const serverJson of serversJson) { try { this.loadServer(serverJson); } catch (e) { // Don't propagate so other stored servers can be created. console.error(e); } } } private loadServer(serverJson: OutlineServerJson) { const server = this.createServer(serverJson.id, serverJson.accessKey, serverJson.name); this.serverById.set(serverJson.id, server); } private createServer(id: string, accessKey: string, name: string): OutlineServer { const server = new OutlineServer(id, accessKey, name, this.createTunnel(id), this.net, this.eventQueue); try { this.validateAccessKey(accessKey); } catch (e) { if (e instanceof errors.ShadowsocksUnsupportedCipher) { // Don't throw for backward-compatibility. server.errorMessageId = 'unsupported-cipher'; } else { throw e; } } return server; } } // Parses an access key string into a ShadowsocksConfig object. export function accessKeyToShadowsocksConfig(accessKey: string): ShadowsocksConfig { try { const config = SHADOWSOCKS_URI.parse(accessKey); return { host: config.host.data, port: config.port.data, method: config.method.data, password: config.password.data, name: config.tag.data, }; } catch (error) { throw new errors.ServerUrlInvalid(error.message || 'failed to parse access key'); } } // Enccodes a Shadowsocks proxy configuration into an access key string. export function shadowsocksConfigToAccessKey(config: ShadowsocksConfig): string { return SIP002_URI.stringify(makeConfig({ host: config.host, port: config.port, method: config.method, password: config.password, tag: config.name, })); } // Compares access keys proxying parameters. function accessKeysMatch(a: string, b: string): boolean { try { const l = accessKeyToShadowsocksConfig(a); const r = accessKeyToShadowsocksConfig(b); return l.host === r.host && l.port === r.port && l.password === r.password && l.method === r.method; } catch (e) { console.debug(`failed to parse access key for comparison`); } return false; }
the_stack
import ApolloClient from 'apollo-client'; import { DocumentNode } from 'apollo-link'; import { MockedResponse } from 'apollo-link-mock'; import gql from 'graphql-tag'; import React, { HTMLAttributes, ReactElement, createContext, useContext, } from 'react'; import { renderToString } from 'react-dom/server'; import { GraphQLError } from 'graphql'; import { ApolloProvider } from '../ApolloContext'; import createClient from '../__testutils__/createClient'; import { getMarkupFromTree } from '../getMarkupFromTree'; import { QueryHookOptions, useQuery } from '../useQuery'; jest.mock('../internal/actHack'); const AUTH_QUERY = gql` { isAuthorized } `; interface AuthQueryResult { isAuthorized: boolean; } const USER_QUERY = gql` { currentUser { firstName } } `; interface UserQueryResult { currentUser: { firstName: string }; } const GRAPQHL_ERROR_QUERY = gql` query GrapqhlErrorQuery { authorized } `; const NETWORK_ERROR_QUERY = gql` query NetworkErrorQuery { isAuthorized } `; const MOCKS: MockedResponse[] = [ { request: { query: AUTH_QUERY }, result: { data: { isAuthorized: true } }, }, { request: { query: USER_QUERY }, result: { data: { currentUser: { firstName: 'James' } } }, }, { request: { query: GRAPQHL_ERROR_QUERY, variables: {} }, result: { data: { __typename: 'Query' }, errors: [new GraphQLError('Simulating GraphQL error')], }, }, { error: new Error('Simulating network error'), request: { query: NETWORK_ERROR_QUERY, variables: {} }, }, ]; function createMockClient() { return createClient({ mocks: MOCKS, addTypename: false }); } function useAuthDetails(options?: QueryHookOptions<{}>) { const { data, loading } = useQuery<AuthQueryResult>(AUTH_QUERY, options); return Boolean(!loading && data && data.isAuthorized); } interface UserDetailsProps extends QueryHookOptions<{}> { readonly query?: DocumentNode; } function UserDetails({ query = USER_QUERY, ...props }: UserDetailsProps) { const { data, loading } = useQuery<UserQueryResult>(query, props); return ( <> {loading ? 'Loading' : !data ? 'No Data (skipped)' : !data.currentUser ? 'No Current User (failed)' : data.currentUser.firstName} </> ); } interface UserWrapperProps extends UserDetailsProps { readonly client: ApolloClient<object>; } function UserDetailsWrapper({ client, ...props }: UserWrapperProps) { return ( <ApolloProvider client={client}> <UserDetails {...props} /> </ApolloProvider> ); } describe.each([[true], [false]])( 'getMarkupFromTree with "suspend: %s"', suspend => { it('should run through all of the queries that want SSR', async () => { const client = createMockClient(); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: <UserDetailsWrapper client={client} suspend={suspend} />, }) ).resolves.toMatchInlineSnapshot(`"James"`); }); it('should allow network-only fetchPolicy as an option and still render prefetched data', async () => { const client = createMockClient(); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: ( <UserDetailsWrapper client={client} suspend={suspend} fetchPolicy="network-only" /> ), }) ).resolves.toMatchInlineSnapshot(`"James"`); }); it('should allow cache-and-network fetchPolicy as an option and still render prefetched data', async () => { const client = createMockClient(); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: ( <UserDetailsWrapper client={client} suspend={suspend} fetchPolicy="cache-and-network" /> ), }) ).resolves.toMatchInlineSnapshot(`"James"`); }); it('should pick up queries deep in the render tree', async () => { const client = createMockClient(); const Container = () => ( <div> <span>Hi</span> <div> <UserDetailsWrapper client={client} suspend={suspend} fetchPolicy="cache-and-network" /> </div> </div> ); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: <Container />, }) ).resolves.toMatchInlineSnapshot( `"<div><span>Hi</span><div>James</div></div>"` ); }); it('should handle nested queries that depend on each other', async () => { const client = createMockClient(); const AuthorizedUser = () => { const authorized = useAuthDetails({ suspend }); return ( <div> <div>Authorized: {String(authorized)}</div> <UserDetails suspend={suspend} skip={!authorized} /> </div> ); }; const Container = () => { return ( <ApolloProvider client={client}> <AuthorizedUser /> </ApolloProvider> ); }; await expect( getMarkupFromTree({ renderFunction: renderToString, tree: <Container />, }) ).resolves.toMatchInlineSnapshot( `"<div><div>Authorized: <!-- -->true</div>James</div>"` ); }); it('should return the first of multiple errors thrown by nested wrapped components', async () => { const client = createMockClient(); const fooError = new Error('foo'); const BorkedComponent = () => { throw fooError; }; const Container = (props: QueryHookOptions<{}>) => ( <div> <UserDetailsWrapper {...props} client={client} /> <BorkedComponent /> <BorkedComponent /> </div> ); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: <Container suspend={suspend} />, }) ).rejects.toBe(fooError); }); it('should handle network errors thrown by queries', async () => { const client = createMockClient(); const tree = ( <UserDetailsWrapper client={client} suspend={suspend} query={NETWORK_ERROR_QUERY} /> ); await expect( getMarkupFromTree({ tree, renderFunction: renderToString }) ).rejects.toMatchInlineSnapshot( `[Error: Network error: Simulating network error]` ); expect(renderToString(tree)).toMatchInlineSnapshot( `"No Current User (failed)"` ); }); it('should handle GraphQL errors thrown by queries', async () => { const client = createMockClient(); const tree = ( <UserDetailsWrapper client={client} suspend={suspend} query={GRAPQHL_ERROR_QUERY} /> ); await expect( getMarkupFromTree({ tree, renderFunction: renderToString }) ).rejects.toMatchInlineSnapshot( `[Error: GraphQL error: Simulating GraphQL error]` ); expect(renderToString(tree)).toMatchInlineSnapshot( `"No Current User (failed)"` ); }); it('should correctly skip queries', async () => { const client = createMockClient(); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: <UserDetailsWrapper client={client} skip suspend={suspend} />, }) ).resolves.toMatchInlineSnapshot(`"No Data (skipped)"`); expect(client.cache.extract()).toEqual({}); }); it('should use the correct default props for a query', async () => { const client = createMockClient(); await getMarkupFromTree({ renderFunction: renderToString, tree: <UserDetailsWrapper client={client} suspend={suspend} />, }); expect(client.cache.extract()).toMatchInlineSnapshot(` Object { "$ROOT_QUERY.currentUser": Object { "firstName": "James", }, "ROOT_QUERY": Object { "currentUser": Object { "generated": true, "id": "$ROOT_QUERY.currentUser", "type": "id", "typename": undefined, }, }, } `); }); it("shouldn't run queries if ssr is turned to off", async () => { const client = createMockClient(); await expect( getMarkupFromTree({ renderFunction: renderToString, tree: ( <UserDetailsWrapper client={client} ssr={false} suspend={suspend} /> ), }) ).resolves.toMatchInlineSnapshot(`"No Data (skipped)"`); expect(client.cache.extract()).toEqual({}); }); it('should not require `ApolloProvider` to be the root component', async () => { const client = createMockClient(); const Root = (props: { children: React.ReactNode }) => <div {...props} />; return expect( getMarkupFromTree({ renderFunction: renderToString, tree: ( <Root> <UserDetailsWrapper client={client} suspend={suspend} /> </Root> ), }) ).resolves.toMatchInlineSnapshot(`"<div>James</div>"`); }); } ); it('runs onBeforeRender', async () => { const client = createMockClient(); const context: { headTags: Array<ReactElement<object>> } = { headTags: [] }; const Context = createContext(context); function Title(props: HTMLAttributes<HTMLTitleElement>) { const ctx = useContext(Context); ctx.headTags.push(<title {...props} />); return null; } let step = 0; await getMarkupFromTree({ onBeforeRender: () => { switch (++step) { case 1: { // First attempt, nothing happened yet. expect(context.headTags).toHaveLength(0); break; } case 2: { // Second attempt, we should have populated context. expect(context.headTags).toHaveLength(1); break; } } }, renderFunction: renderToString, tree: ( <> <Title>Hello!</Title> <UserDetailsWrapper client={client} /> </> ), }); // Second attempt should create duplicates. expect(context.headTags).toHaveLength(2); expect.assertions(3); });
the_stack
import { assert } from "node-opcua-assert"; import * as ec from "node-opcua-basic-types"; import { BinaryStream, BinaryStreamSizeCalculator, OutputBinaryStream } from "node-opcua-binary-stream"; import { checkDebugFlag, make_debugLog, make_warningLog } from "node-opcua-debug"; import * as factories from "node-opcua-factory"; import { NodeId, resolveNodeId } from "node-opcua-nodeid"; import { Argument } from "node-opcua-service-call"; import { StatusCode, StatusCodes } from "node-opcua-status-code"; import { Variant } from "node-opcua-variant"; import { DataType } from "node-opcua-variant"; import { VariantArrayType } from "node-opcua-variant"; import { NodeClass } from "node-opcua-data-model"; import { IAddressSpace, UAMethod, UAObject } from "node-opcua-address-space-base"; const debugLog = make_debugLog(__filename); const warningLog = make_warningLog(__filename); const doDebug = checkDebugFlag(__filename); function myfindBuiltInType(dataType: DataType): any { return factories.findBuiltInType(DataType[dataType]); } export interface ArgumentDef { dataType: DataType; valueRank?: undefined | number; } export function encode_ArgumentList(definition: ArgumentDef[], args: any[], stream: OutputBinaryStream): void { assert(definition.length === args.length); assert(Array.isArray(definition)); assert(Array.isArray(args)); assert(definition.length === args.length); assert(definition.length >= 0); // we only encode arguments by following the definition for (let i = 0; i < definition.length; i++) { const def = definition[i]; const value = args[i]; const encodeFunc = myfindBuiltInType(def.dataType).encode; // assert((def.valueRank === -1) || (def.valueRank === 0)); // todo : handle -3 -2 const isArray = def.valueRank && (def.valueRank === 1 || def.valueRank !== -1); if (isArray) { ec.encodeArray(value, stream, encodeFunc); } else { encodeFunc(value, stream); } } } export function decode_ArgumentList(definition: ArgumentDef[], stream: BinaryStream): any[] { if (!Array.isArray(definition)) { throw new Error( "This BaseDataType cannot be decoded because it has no definition.\n" + "Please construct a BaseDataType({definition : [{dataType: DataType.UInt32 }]});" ); } const args: any[] = []; let value; for (const def of definition) { const decodeFunc = myfindBuiltInType(def.dataType).decode; // xx assert(def.valueRank === -1 || def.valueRank==0); const isArray = def.valueRank === 1 || def.valueRank === -1; if (isArray) { value = ec.decodeArray(stream, decodeFunc); } else { value = decodeFunc(stream); } args.push(value); } return args; } export function binaryStoreSize_ArgumentList(description: ArgumentDef[], args: any[]): number { assert(Array.isArray(description)); assert(Array.isArray(args)); assert(args.length === description.length); const stream = new BinaryStreamSizeCalculator(); encode_ArgumentList(description, args, stream); return stream.length; } export function getMethodDeclaration_ArgumentList( addressSpace: IAddressSpace, objectId: NodeId, methodId: NodeId ): { statusCode: StatusCode; methodDeclaration?: UAMethod } { // find object in address space const obj = addressSpace.findNode(objectId) as UAObject; if (!obj) { // istanbul ignore next if (doDebug) { debugLog("cannot find node ", objectId.toString()); } return { statusCode: StatusCodes.BadNodeIdUnknown }; } let objectMethod = obj.getMethodById(methodId) as UAMethod; if (!objectMethod) { // the method doesn't belong to the object, nevertheless // the method can be called objectMethod = addressSpace.findNode(methodId) as UAMethod; if (!objectMethod || objectMethod.nodeClass !== NodeClass.Method) { warningLog("cannot find method with id", methodId.toString(), "object Id = ", objectId.toString()); return { statusCode: StatusCodes.BadMethodInvalid }; } } const methodDeclarationId = objectMethod.methodDeclarationId; const methodDeclaration = addressSpace.findNode(methodDeclarationId) as UAMethod; if (!methodDeclaration) { // return {statusCode: StatusCodes.BadMethodInvalid}; return { statusCode: StatusCodes.Good, methodDeclaration: objectMethod }; } // istanbul ignore next if (methodDeclaration.nodeClass !== NodeClass.Method) { throw new Error("Expecting a Method here"); } return { statusCode: StatusCodes.Good, methodDeclaration }; } /** * @private */ function isArgumentValid(addressSpace: IAddressSpace, argDefinition: Argument, arg: Variant): boolean { assert(Object.prototype.hasOwnProperty.call(argDefinition, "dataType")); assert(Object.prototype.hasOwnProperty.call(argDefinition, "valueRank")); const argDefDataType = addressSpace.findDataType(argDefinition.dataType); const argDataType = addressSpace.findDataType(resolveNodeId(arg.dataType)); // istanbul ignore next if (!argDefDataType) { debugLog("dataType ", argDefinition.dataType.toString(), "doesn't exist"); return false; } if (argDefinition.valueRank > 0 && arg.dataType === DataType.Null) { // this is valid to receive an empty array ith DataType.Null; return true; } // istanbul ignore next if (!argDataType) { debugLog(" cannot find dataType ", arg.dataType, resolveNodeId(arg.dataType)); debugLog(" arg = ", arg.toString()); debugLog(" def =", argDefinition.toString()); return false; } // istanbul ignore next if (doDebug) { debugLog(" checking argDefDataType ", argDefDataType.toString()); debugLog(" checking argDataType ", argDataType.toString()); } const isArray = arg.arrayType === VariantArrayType.Array; if (argDefinition.valueRank > 0) { return isArray; } else if (argDefinition.valueRank === -1) { // SCALAR if (isArray) { return false; } } if (argDataType.nodeId.value === argDefDataType!.nodeId.value) { return true; } // check that dataType is of the same type (derived ) return argDefDataType.isSupertypeOf(argDataType); } /** * @method verifyArguments_ArgumentList * @param addressSpace * @param methodInputArguments * @param inputArguments * @return statusCode,inputArgumentResults */ export function verifyArguments_ArgumentList( addressSpace: IAddressSpace, methodInputArguments: Argument[], inputArguments?: Variant[] ): { inputArgumentResults?: StatusCode[]; statusCode: StatusCode; } { if (!inputArguments) { // it is possible to not provide inputArguments when method has no arguments return methodInputArguments.length === 0 ? { statusCode: StatusCodes.Good } : { statusCode: StatusCodes.BadArgumentsMissing }; } const inputArgumentResults: StatusCode[] = methodInputArguments.map((methodInputArgument, index) => { const argument = inputArguments![index]; if (!argument) { return StatusCodes.BadNoData; } else if (!isArgumentValid(addressSpace, methodInputArgument, argument)) { return StatusCodes.BadTypeMismatch; } else { return StatusCodes.Good; } }); if (methodInputArguments.length > inputArguments.length) { // istanbul ignore next if (doDebug) { debugLog( "verifyArguments_ArgumentList " + "\n The client did specify too many input arguments for the method. " + "\n expected : " + methodInputArguments.length + "" + "\n actual : " + inputArguments.length ); } return { inputArgumentResults, statusCode: StatusCodes.BadArgumentsMissing }; } if (methodInputArguments.length < inputArguments.length) { // istanbul ignore next if (doDebug) { debugLog( " verifyArguments_ArgumentList " + "\n The client did not specify all of the input arguments for the method. " + "\n expected : " + methodInputArguments.length + "" + "\n actual : " + inputArguments.length ); } return { inputArgumentResults, statusCode: StatusCodes.BadTooManyArguments }; } return { inputArgumentResults, statusCode: inputArgumentResults.includes(StatusCodes.BadTypeMismatch) || inputArgumentResults.includes(StatusCodes.BadOutOfRange) ? StatusCodes.BadInvalidArgument : StatusCodes.Good }; } export function build_retrieveInputArgumentsDefinition( addressSpace: IAddressSpace ): (objectId: NodeId, methodId: NodeId) => Argument[] { const the_address_space = addressSpace; return (objectId: NodeId, methodId: NodeId) => { const response = getMethodDeclaration_ArgumentList(the_address_space, objectId, methodId); /* istanbul ignore next */ if (response.statusCode !== StatusCodes.Good) { debugLog(" StatusCode = " + response.statusCode.toString()); throw new Error( "Invalid Method " + response.statusCode.toString() + " ObjectId= " + objectId.toString() + "Method Id =" + methodId.toString() ); } const methodDeclaration = response.methodDeclaration!; // verify input Parameters const methodInputArguments = methodDeclaration.getInputArguments(); assert(Array.isArray(methodInputArguments)); return methodInputArguments; }; }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Smithchart} from '../../smithchart'; import { SmithchartMarginModel, SmithchartFontModel} from '../../smithchart/utils/utils-model'; import { measureText } from '../../smithchart/utils/helper'; import {getTemplateFunction, convertElementFromLabel, PathOption } from '../../smithchart/utils/helper'; import { SeriesMarkerModel, SeriesMarkerDataLabelModel} from '../../smithchart/series/series-model'; import { SmithchartRect, SmithchartSize, Point, PointRegion, SmithchartLabelPosition } from '../../smithchart/utils/utils'; import { DataLabelTextOptions, LabelOption } from '../../smithchart/utils/utils'; import { SeriesMarkerDataLabelConnectorLineModel } from '../../smithchart/series/series-model'; export class DataLabel { public textOptions: DataLabelTextOptions[] = []; public labelOptions: LabelOption[] = []; private connectorFlag: boolean; private prevLabel: DataLabelTextOptions; private allPoints: DataLabelTextOptions[] = []; public drawDataLabel(smithchart: Smithchart, seriesindex: number, groupElement: Element, pointsRegion: PointRegion[], bounds: SmithchartRect): void { this.textOptions = []; this.allPoints = []; const margin: SmithchartMarginModel = smithchart.margin; let pointIndex: number; const marker: SeriesMarkerModel = smithchart.series[seriesindex].marker; let region: Point; let labelPosition: SmithchartLabelPosition; let labelText: string; let textSize: SmithchartSize; const dataLabel: SeriesMarkerDataLabelModel = marker.dataLabel; const font: SmithchartFontModel = dataLabel.textStyle; const count: number = pointsRegion.length; for (let i: number = 0; i < count; i++) { labelText = smithchart.series[seriesindex].points[i].reactance.toString(); textSize = measureText(labelText, font); region = pointsRegion[i]['point']; const xPos: number = region.x - textSize.width / 2; const yPos: number = region.y - (textSize.height + marker['height'] + (margin.top)); const width: number = textSize.width + (margin.left / 2) + (margin.right / 2); const height: number = textSize.height + (margin.top / 2) + (margin.bottom / 2); pointIndex = i; labelPosition = new SmithchartLabelPosition(); labelPosition = { textX: xPos + (margin.left / 2), textY: yPos + (height / 2) + margin.top / 2, x: xPos, y: yPos }; this.textOptions[i] = { id: smithchart.element.id + '_Series' + seriesindex + '_Points' + pointIndex + '_dataLabel' + '_displayText' + i, x: labelPosition['textX'], y: labelPosition['textY'], fill: 'black', text: labelText, font: font, xPosition: xPos, yPosition: yPos, width: width, height: height, location: region, labelOptions: labelPosition, visible: true, connectorFlag: null }; } const labelOption: LabelOption = new LabelOption(); labelOption.textOptions = this.textOptions; this.labelOptions.push( labelOption); this.drawDatalabelSymbol(smithchart, seriesindex, dataLabel, groupElement, bounds, pointsRegion); } public calculateSmartLabels(points: object, seriesIndex: number): void { const length : number = points['textOptions'].length; const count: number = 0; for (let k: number = 0; k < length; k++) { this.allPoints[this.allPoints.length] = points['textOptions'][k]; this.connectorFlag = false; this.compareDataLabels(k, points, count, seriesIndex); this.labelOptions[seriesIndex]['textOptions'][k] = points['textOptions'][k]; this.labelOptions[seriesIndex]['textOptions'][k].connectorFlag = this.connectorFlag; } } private compareDataLabels(i: number, points: object, count: number, m: number): void { const length: number = this.allPoints.length; const padding: number = 10; let collide: boolean; let currentLabel: DataLabelTextOptions; let prevLabel: DataLabelTextOptions; for (let j: number = 0; j < length; j++) { prevLabel = this.allPoints[j]; currentLabel = this.allPoints[length - 1]; collide = this.isCollide(prevLabel, currentLabel); if (collide) { this.connectorFlag = true; switch (count) { case 0: // Right this.resetValues(currentLabel); this.prevLabel = prevLabel; currentLabel['xPosition'] = this.prevLabel['xPosition'] + (this.prevLabel['width'] / 2 + currentLabel['width'] / 2 + padding); currentLabel['x'] = currentLabel['xPosition'] + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 1: // Right Bottom this.resetValues(currentLabel); currentLabel['xPosition'] = this.prevLabel['xPosition'] + this.prevLabel['width'] / 2 + currentLabel['width'] / 2 + padding; currentLabel['x'] = currentLabel['xPosition'] + padding / 2; currentLabel['yPosition'] = currentLabel['location'].y + currentLabel['height'] / 2 + padding / 2; currentLabel['y'] = currentLabel['yPosition'] + ((currentLabel['height'] / 2)) + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 2: // Bottom this.resetValues(currentLabel); currentLabel['yPosition'] = currentLabel['location'].y + currentLabel['height'] / 2 + padding / 2; currentLabel['y'] = currentLabel['yPosition'] + (currentLabel['height'] / 2) + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 3: // Left Bottom this.resetValues(currentLabel); currentLabel['xPosition'] = this.prevLabel['xPosition'] - this.prevLabel['width'] / 2 - currentLabel['width'] / 2 - padding; currentLabel['x'] = currentLabel['xPosition'] + padding / 2; currentLabel['yPosition'] = currentLabel['height'] / 2 + currentLabel['location'].y + padding / 2; currentLabel['y'] = currentLabel['yPosition'] + ((currentLabel['height'] / 2)) + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 4: // Left this.resetValues(currentLabel); currentLabel['xPosition'] = (this.prevLabel['xPosition'] - this.prevLabel['width'] / 2 - currentLabel['width'] / 2 - padding); currentLabel['x'] = currentLabel['xPosition'] + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 5: //Left Top this.resetValues(currentLabel); currentLabel['xPosition'] = this.prevLabel['xPosition'] - this.prevLabel['width'] / 2 - currentLabel['width'] / 2 - padding; currentLabel['x'] = currentLabel['xPosition'] + padding / 2; currentLabel['yPosition'] = this.prevLabel['yPosition'] - currentLabel['height'] - padding; currentLabel['y'] = currentLabel['yPosition'] + currentLabel['height'] / 2 + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 6: // Top this.resetValues(currentLabel); currentLabel['yPosition'] = (this.prevLabel['yPosition']) - (currentLabel['height'] + padding); currentLabel['y'] = currentLabel['yPosition'] + (currentLabel['height'] / 2) + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 7: // Right Top this.resetValues(currentLabel); currentLabel['xPosition'] = this.prevLabel['xPosition'] + this.prevLabel['width'] / 2 + currentLabel['width'] / 2 + padding; currentLabel['x'] = currentLabel['xPosition'] + padding / 2; currentLabel['yPosition'] = this.prevLabel['yPosition'] - currentLabel['height'] - padding; currentLabel['y'] = currentLabel['yPosition'] + (currentLabel['height'] / 2) + padding / 2; count += 1; this.compareDataLabels(i, points, count, m); break; case 8: count = 0; this.compareDataLabels(i, points, count, m); break; } } } } private isCollide(dataLabel1: DataLabelTextOptions, dataLabel2: DataLabelTextOptions): boolean { let state: boolean = false; if (dataLabel1 !== dataLabel2) { state = !( // to compare data labels ((dataLabel1['y'] + dataLabel1['height']) < (dataLabel2['y'])) || (dataLabel1['y'] > (dataLabel2['y'] + dataLabel2['height'])) || ((dataLabel1['x'] + dataLabel1['width'] / 2) < dataLabel2['x'] - dataLabel2['width'] / 2) || (dataLabel1['x'] - dataLabel1['width'] / 2 > (dataLabel2['x'] + dataLabel2['width'] / 2))); } return state; } private resetValues(currentPoint: DataLabelTextOptions): void { currentPoint['xPosition'] = currentPoint['labelOptions']['x']; currentPoint['yPosition'] = currentPoint['labelOptions']['y']; currentPoint['x'] = currentPoint['labelOptions']['textX']; currentPoint['y'] = currentPoint['labelOptions']['textY']; } public drawConnectorLines(smithchart: Smithchart, seriesIndex: number, index: number, currentPoint: DataLabelTextOptions, groupElement: Element): void { const location: Point = currentPoint['location']; let endY: number; if (location.y > currentPoint['y']) { endY = (currentPoint['y']); } else { endY = (currentPoint['y'] - currentPoint['height'] / 2); // bottom } const connectorDirection: string = 'M' + ' ' + (location.x) + ' ' + (location.y) + ' ' + 'L' + ' ' + (currentPoint['x']) + ' ' + (endY); const connectorLineValues: SeriesMarkerDataLabelConnectorLineModel = smithchart.series[seriesIndex].marker.dataLabel.connectorLine; const stroke : string = connectorLineValues.color ? connectorLineValues.color : (smithchart.series[seriesIndex].fill || smithchart.seriesColors[seriesIndex % smithchart.seriesColors.length]); const options: PathOption = new PathOption( smithchart.element.id + '_dataLabelConnectorLine' + '_series' + seriesIndex + '_point' + index, 'none', connectorLineValues.width, stroke, 1, 'none', connectorDirection ); const element: Element = smithchart.renderer.drawPath(options); groupElement.appendChild(element); } private drawDatalabelSymbol(smithchart: Smithchart, seriesindex : number, dataLabel: SeriesMarkerDataLabelModel, groupElement: Element, bounds: SmithchartRect, pointsRegion: PointRegion[]): void { for (let i: number = 0; i < smithchart.series[seriesindex].points.length; i++) { if (dataLabel.template) { const labelTemplateElement: HTMLElement = createElement('div', { id: smithchart.element.id + '_seriesIndex_' + seriesindex + '_Label_Template_Group', className: 'template', styles: 'position: absolute;' /* 'top:' + bounds['x'] + 'px;' + 'left:' + bounds['y'] + 'px;' + 'height:' + smithchart.availableSize.height + 'px;' + 'width:' + smithchart.availableSize.width + 'px;'*/ }); document.getElementById(smithchart.element.id + '_Secondary_Element').appendChild(labelTemplateElement); const id: string = dataLabel.template + '_seriesIndex' + seriesindex + '_pointIndex' + i + smithchart.element.id; const data: object = {point: smithchart.series[seriesindex].points[i].reactance}; const templateFn: Function = getTemplateFunction(dataLabel.template); const templateElement: Element = templateFn(smithchart); const labelElement: HTMLElement = <HTMLElement>convertElementFromLabel( templateElement, id, data); labelTemplateElement.appendChild(labelElement); labelElement.style.left = pointsRegion[i].point.x - labelElement.offsetWidth / 2 + 'px'; labelElement.style.top = pointsRegion[i].point.y - labelElement.offsetHeight - smithchart.series[seriesindex].marker.height / 2 + 'px'; const left: number = parseInt(labelElement.style.left, 10); const top: number = parseInt(labelElement.style.top, 10); const width: number = labelElement.offsetWidth; const height: number = labelElement.offsetHeight; const region: Point = pointsRegion[i]['point']; const labelPosition: SmithchartLabelPosition = { textX: left, textY: top, x: left, y: top}; this.labelOptions[seriesindex]['textOptions'][i] = { id: id, x: left, y: top, fill: 'black', text: '', font: dataLabel.textStyle, xPosition: left, yPosition: top, width: width, height: height, location: region, labelOptions: labelPosition, visible: true, connectorFlag: null }; } } } }
the_stack
import { AbstractDataSource } from './AbstractDataSource'; import path from 'path'; import { DataItem, DataItemKind, DataSourceActionResult, MediaItem, SearchQuery, SearchQuerySortColumn, SearchQuerySortDirection, SearchResult, } from '../types'; import Knex from 'knex'; import fsLib from 'fs'; import { LocalFileSystemDataSourceOptions } from './LocalFileSystemDataSource'; import { LogService } from '../common/LogService'; import sqlite3 from 'sqlite3'; import { v4 as uuid } from 'uuid'; import { arrayDiff, isMediaItem, isNoteItem } from '../utils'; import Jimp from 'jimp/dist'; import type { TelemetryContextValue } from '../components/telemetry/TelemetryProvider'; import { TelemetryEvents } from '../components/telemetry/TelemetryEvents'; import { runWithoutClose } from '../common/runWithoutClose'; const fs = fsLib.promises; const logger = LogService.getLogger('LocalSqliteDataSource'); const NOTEBOOK_FILE = 'notebook.json'; const NOTEBOOK_FILE_BACKUP = 'notebook-backup.json'; const DB_FILE = 'notebook.sqlite'; const MEDIA_DIR = 'media'; const UTF8 = 'utf8'; const SQLITE_UNLOAD_TIMEOUT = 60 * 1000; export interface LocalSqliteDataSourceOptions { sourcePath: string; } export class LocalSqliteDataSource implements AbstractDataSource { private dbInstance?: Knex<any, unknown[]>; private dbInstanceUnloadTimer?: any; private structures: any = {}; private thumbnailExtensions: string[] = ['png', 'jpg', 'gif', 'jpeg', 'bmp', 'tiff']; private resolvePath(...p: string[]) { return path.join(this.options.sourcePath, ...p); } private createId(): string { return uuid(); } public static getDb(sourcePath: string) { return Knex({ client: 'sqlite3', connection: { filename: path.join(sourcePath, DB_FILE), }, useNullAsDefault: true, }); } private static async createSchemas(db: Knex) { await db.schema .createTable('items', table => { table.string('id').notNullable().primary().unique().index(); table.string('name').notNullable(); table.integer('created').notNullable(); table.integer('lastChange').notNullable(); table.enu('kind', ['collection', 'note', 'media']).defaultTo('note').notNullable(); table.string('noteType').nullable(); table.string('icon').nullable(); table.string('color').nullable(); }) .createTable('items_tags', table => { table.increments('id').notNullable().unique().primary().index(); table.string('tagName').notNullable().index(); table.string('noteId').index().references('id').inTable('items'); }) .createTable('items_childs', table => { table.increments('id').notNullable().unique().primary().index(); table.string('parentId').references('id').inTable('items'); table.string('childId').references('id').inTable('items'); table.integer('ordering').notNullable(); }) .createTable('media_data', table => { table.string('noteId').primary().unique().index().references('id').inTable('items'); table.string('type').notNullable(); table.string('extension').notNullable(); table.integer('size').notNullable(); table.boolean('hasThumbnail').notNullable(); table.string('referencePath').nullable(); }) // .createTable('tags_all', table => { // TODO not required? // table.string('name').notNullable().unique().primary().index(); // table.integer('usage').defaultTo(0); // }) .createTable('note_contents', table => { table.string('noteId').primary().index().unique().references('id').inTable('items'); table.string('content'); }); } private get db() { logger.log( `get db: ${this.dbInstance ? 'is cached' : 'is not cached'} ${ this.dbInstanceUnloadTimer ? 'and was timed for unloading' : 'and was not timed for unloading' }` ); if (!this.dbInstance) { this.dbInstance = LocalSqliteDataSource.getDb(this.options.sourcePath); if (this.dbInstanceUnloadTimer) { clearTimeout(this.dbInstanceUnloadTimer); } this.dbInstanceUnloadTimer = setTimeout(() => { logger.log(`get db: unloaded`); this.dbInstance?.destroy(); this.dbInstance = undefined; this.dbInstanceUnloadTimer = undefined; }, SQLITE_UNLOAD_TIMEOUT); } return this.dbInstance; } constructor(private options: LocalSqliteDataSourceOptions, private telemetry?: TelemetryContextValue) {} public static async init(options: LocalFileSystemDataSourceOptions) { await runWithoutClose(async () => { const sourcePath = options.sourcePath; const mediaDataPath = path.join(sourcePath, MEDIA_DIR); if (!fsLib.existsSync(sourcePath)) { await fs.mkdir(sourcePath, { recursive: true }); } if (!fsLib.existsSync(mediaDataPath)) { await fs.mkdir(mediaDataPath, { recursive: true }); } // Create and wait for database just so its created on file. We do not need a reference to it here. await new Promise(res => { new sqlite3.Database(path.join(sourcePath, DB_FILE), sqlite3.OPEN_CREATE, () => res()); }); const db = LocalSqliteDataSource.getDb(sourcePath); await LocalSqliteDataSource.createSchemas(db); await db.destroy(); await fs.writeFile(path.join(options.sourcePath, NOTEBOOK_FILE), JSON.stringify({ structures: {} })); await fs.writeFile(path.join(options.sourcePath, NOTEBOOK_FILE_BACKUP), JSON.stringify({ structures: {} })); }); } public async load(): Promise<DataSourceActionResult> { try { this.structures = JSON.parse(await fs.readFile(this.resolvePath(NOTEBOOK_FILE), { encoding: 'utf8' })).structures; this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.loadSuccess); } catch (e) { try { this.structures = JSON.parse( await fs.readFile(this.resolvePath(NOTEBOOK_FILE_BACKUP), { encoding: 'utf8' }) ).structures; this.telemetry?.trackException('Notebook malformed, backup was fine.'); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.loadFailedBackupFine); } catch (e) { this.telemetry?.trackException('Loading workspace failed, notebook and backup malformed.'); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.loadFailedBackupBroken); throw Error('Both notebook file and backup file are malformed.'); } } // Create items_childs ordering column if not existing already // as this column was added in v1.0.1 const itemsChildsColumns = await this.db.raw('PRAGMA table_info(items_childs)'); const doesOrderingColumnExist = !!itemsChildsColumns.find((col: any) => col.name === 'ordering'); if (!doesOrderingColumnExist) { await this.db.schema.alterTable('items_childs', table => { table.integer('ordering').notNullable().defaultTo(0); }); } } public async unload(): Promise<DataSourceActionResult> { await this.db.destroy(); } public reload(): Promise<DataSourceActionResult> { return Promise.resolve(undefined); } public async getDataItem<K extends DataItemKind>(id: string): Promise<DataItem<K> | null> { const [item] = await this.db('items').select('*').where('id', id).limit(1); if (!item) { return null; } const tags: Array<{ tagName: string }> = await this.db('items_tags') .select('tagName', 'noteId') .where('noteId', id); const childIds: Array<{ childId: string }> = await this.db('items_childs') .select('parentId', 'childId') .where('parentId', id) .orderBy('ordering', 'asc'); // TODO joined query? return { ...item, childIds: childIds.map(child => child.childId), tags: tags.map(tag => tag.tagName), }; } public async getNoteItemContent<C extends object>(id: string): Promise<C> { const [item] = await this.db('note_contents').select('content', 'noteId').where('noteId', id).limit(1); return item?.content ? JSON.parse(item.content) : null; } public async writeNoteItemContent<C extends object>(id: string, content: C): Promise<DataSourceActionResult> { await this.db('note_contents').where('noteId', id).update('content', JSON.stringify(content)); } private async breakSqlCommandsDown<T>(items: T[], doPerSetOfItems: (items: T[]) => Promise<void>) { const itemsAtATime = 100; for (let i = 0; i < items.length; i += itemsAtATime) { await doPerSetOfItems(items.slice(i, i + itemsAtATime)); } } public async createDataItem<K extends DataItemKind>( item: Omit<DataItem<K>, 'id'> & { id?: string } ): Promise<DataItem<K>> { const id = item.id ?? this.createId(); await this.db('items').insert([ { id: id, name: item.name, kind: item.kind, created: item.created, lastChange: item.lastChange, icon: item.icon, color: item.color, noteType: (item as any).noteType, }, ]); if (item.tags.length > 0) { await this.breakSqlCommandsDown( item.tags.map(tag => ({ tagName: tag, noteId: id, })), async setOfItems => await this.db('items_tags').insert(setOfItems) ); } let i = 0; if (item.childIds.length > 0) { await this.breakSqlCommandsDown( item.childIds.map(childId => ({ parentId: id, childId, ordering: i++, })), async setOfItems => await this.db('items_childs').insert(setOfItems) ); } if (isNoteItem(item as any)) { await this.db('note_contents').insert([ { noteId: id, content: '{}', }, ]); } else if (isMediaItem(item as any)) { // TODO } this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.createItem); return { ...item, id }; } public async removeItem(id: string): Promise<DataSourceActionResult> { const item = await this.getDataItem(id); if (!item) { return; } if (isNoteItem(item)) { await this.db('note_contents').where('noteId', id).del(); } else if (isMediaItem(item)) { // TODO } await this.db('items').where('id', id).del(); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.removeItem); } public async changeItem<K extends DataItemKind>( id: string, overwriteItem: DataItem<K> ): Promise<DataSourceActionResult> { const item = await this.getDataItem(id); if (!item) { throw Error(`Trying to change item ${id}, which does not exist.`); } const removedTags = !overwriteItem.tags ? [] : arrayDiff(item.tags, overwriteItem.tags); const addedTags = !overwriteItem.tags ? [] : arrayDiff(overwriteItem.tags, item.tags); const haveChildsChanged = overwriteItem.childIds && overwriteItem.childIds.toString() !== item.childIds.toString(); logger.log('Updating tags and childs', [], { addedTags, removedTags, haveChildsChanged }); if (addedTags.length > 0) { await this.db('items_tags').insert( addedTags.map(tag => ({ tagName: tag, noteId: id, })) ); } if (removedTags.length > 0) { await this.db('items_tags').where('noteId', id).and.whereIn('tagName', removedTags).del(); } if (haveChildsChanged) { await this.db('items_childs').where('parentId', id).and.whereIn('childId', item.childIds).del(); let i = 0; await this.db('items_childs').insert( overwriteItem.childIds.map(childId => ({ parentId: id, childId, ordering: i++, })) ); } await this.db('items') .where('id', id) .update({ name: overwriteItem.name ?? item.name, created: overwriteItem.created ?? item.created, lastChange: overwriteItem.lastChange ?? item.lastChange, kind: overwriteItem.kind ?? item.kind, noteType: (overwriteItem as any).noteType ?? (item as any).noteType, icon: overwriteItem.icon ?? item.icon, color: overwriteItem.color ?? item.color, }); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.changeItem); } public async getParentsOf<K extends DataItemKind>(childId: string): Promise<DataItem<K>[]> { // TODO transform to use join const parentIds: Array<{ parentId: string }> = await this.db('items_childs').select('*').where('childId', childId); return (await Promise.all(parentIds.map(({ parentId }) => this.getDataItem(parentId)))).filter(el => !!el) as any; } public async search(search: SearchQuery): Promise<SearchResult> { let query = this.db('items').select('items.*'); if (search.tags || search.notTags) { query = query.leftJoin('items_tags', 'items.id', 'items_tags.noteId'); } if (search.childs) { query = query.leftJoin({ childs: 'items_childs' }, 'items.id', 'childs.parentId'); } if (search.parents) { query = query.leftJoin({ parents: 'items_childs' }, 'items.id', 'parents.childId'); } if (search.containsInContents) { query = query.leftJoin('note_contents', 'items.id', 'note_contents.noteId'); } if (search.contains) { for (const contains of search.contains!) { if (!search.containsInContents) { query = query.andWhere('name', 'like', `%${contains}%`); } else { query = query.where(qb => { qb.orWhere('name', 'like', `%${contains}%`); qb.orWhere('note_contents.content', 'like', `%${contains}%`); }); } } } if (search.kind) { query = query.andWhere('kind', search.kind); } if (search.tags) { for (const tag of search.tags) { query = query.where('items_tags.tagName', tag); } } if (search.notTags) { for (const tag of search.notTags) { query = query.where(qb => { qb.where('items_tags.tagName', '<>', tag).orWhereNull('items_tags.tagName'); }); } } if (search.childs) { for (const child of search.childs) { query = query.where('childs.childId', child); } } if (search.parents) { query = query.where(qb => { for (const parent of search.parents!) { qb.orWhere('parents.parentId', parent); } }); } if (search.exactParents) { for (const parent of search.exactParents) { query = query.where('parents.parentId', parent); } } if (search.pagingValue) { query = query.where( search.sortColumn ?? SearchQuerySortColumn.Name, search.sortDirection === SearchQuerySortDirection.Descending ? '<' : '>', // TODO correct? search.pagingValue ); } query = query.groupBy('items.id'); // Prevent duplicates from joins if (search.limit) { query = query.limit(search.limit); } else { logger.warn('Performing search without limit!', [], { search }); } query = query.orderBy( search.sortColumn ?? SearchQuerySortColumn.Name, search.sortDirection === SearchQuerySortDirection.Descending ? 'desc' : 'asc' ); logger.log('Performing sqlite search ' + query.toQuery()); const itemIds: Array<{ id: string }> = await query; logger.log('Search yielded IDs: ', [], { itemIds, search, query: query.toQuery() }); // TODO extract getDataItem code into seperate call and use it to complete data items instead of refetching const items = (await Promise.all(itemIds.map(({ id }) => this.getDataItem(id)))).filter( item => !!item ) as DataItem[]; // TODO search content table logger.log('Search yielded items: ', [], { items, itemIds, search }); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.performSearch); return { results: items, nextPagingValue: items[items.length - 1]?.[search.sortColumn ?? SearchQuerySortColumn.Name], nextPageAvailable: !!search.limit && items.length === search.limit, }; } public async loadMediaItemContent(id: string): Promise<Buffer | Blob> { const mediaItem = (await this.getDataItem(id)) as MediaItem; return await fs.readFile(this.resolvePath(MEDIA_DIR, id + '.' + mediaItem.extension)); } public async loadMediaItemContentAsPath(id: string): Promise<string> { const mediaItem = (await this.getDataItem(id)) as MediaItem; return mediaItem.referencePath || this.resolvePath(MEDIA_DIR, id + '.' + mediaItem.extension); } public async loadMediaItemContentThumbnailAsPath(id: string): Promise<string | undefined> { const mediaItem = (await this.getDataItem(id)) as MediaItem; if (this.thumbnailExtensions.includes(mediaItem.extension)) { const thumbnailPath = this.resolvePath(MEDIA_DIR, id + '.thumb.' + mediaItem.extension); if (fsLib.existsSync(thumbnailPath)) { return thumbnailPath; } else { return undefined; } } else { return undefined; } } public async storeMediaItemContent( id: string, localPath: string, thumbnail: { width?: number; height?: number } | undefined ): Promise<DataSourceActionResult> { const mediaItem = (await this.getDataItem(id)) as MediaItem; logger.log('Storing media item content', [], { id, localPath, mediaItem, thumbnail }); if (!mediaItem.referencePath) { await fs.copyFile(localPath, this.resolvePath(MEDIA_DIR, id + '.' + mediaItem.extension)); } if (thumbnail && (thumbnail.width || thumbnail?.height) && this.thumbnailExtensions.includes(mediaItem.extension)) { logger.log('Preparing thumbnail', [], { thumbnail, mediaItem, localPath }); const file = await fs.readFile(localPath); const jimpImage = await Jimp.read(file); logger.log('Read original image', [], { jimpImage }); const resized = await jimpImage.resize(thumbnail.width || Jimp.AUTO, thumbnail.height || Jimp.AUTO); const buffer = await resized.getBufferAsync(resized.getMIME()); await fs.writeFile(this.resolvePath(MEDIA_DIR, id + '.thumb.' + mediaItem.extension), buffer); // .writeAsync(this.resolvePath(MEDIA_DIR, id + '.thumb.' + mediaItem.extension)); logger.log('Resized image and stored thumbnail', [], {}); } this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.storeMediaContent); } public async removeMediaItemContent(item: MediaItem): Promise<DataSourceActionResult> { const mediaPath = this.resolvePath(MEDIA_DIR, item.id + '.' + item.extension); const thumbPath = this.resolvePath(MEDIA_DIR, item.id + '.thumb.' + item.extension); logger.log('Removing media contents', [], { item, mediaPath, thumbPath, hasThumb: item.hasThumbnail }); await fs.unlink(mediaPath); if (item.hasThumbnail) { await fs.unlink(thumbPath); } } public async persist(): Promise<DataSourceActionResult> { await runWithoutClose(async () => { const notebookPath = this.resolvePath(NOTEBOOK_FILE); const backupPath = this.resolvePath(NOTEBOOK_FILE_BACKUP); for (let attempt = 0; attempt < 5; attempt++) { await fs.writeFile(notebookPath, JSON.stringify({ structures: this.structures })); try { JSON.parse(await fs.readFile(notebookPath, { encoding: UTF8 })); // parsing worked, save backup... await fs.writeFile(backupPath, JSON.stringify({ structures: this.structures })); JSON.parse(await fs.readFile(backupPath, { encoding: UTF8 })); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.persist); return; } catch (e) { this.telemetry?.trackException(`Persistence failed for the ${attempt} time`); this.telemetry?.trackEvent('dsqlite', 'persist_failed_' + attempt); this.telemetry?.trackEvent(...TelemetryEvents.SqliteDatasource.persistFailed); console.error(`Persisting failed`); logger.log(`Persistence failed for the ${attempt} time`); } } }); } public async getStructure(id: string): Promise<any> { return this.structures[id]; } public async storeStructure(id: string, structure: any): Promise<DataSourceActionResult> { this.structures[id] = structure; } }
the_stack
import cloneDeep from 'lodash/cloneDeep'; require('base-components/base-content.component.ts'); require( 'components/forms/schema-based-editors/schema-based-editor.directive.ts'); require( 'components/question-directives/question-editor/' + 'question-editor.component.ts'); require('directives/angular-html-bind.directive.ts'); require('domain/question/QuestionObjectFactory.ts'); require('domain/skill/MisconceptionObjectFactory.ts'); require('domain/skill/skill-backend-api.service.ts'); require('filters/format-rte-preview.filter.ts'); require('interactions/interactionsQuestionsRequires.ts'); require('objects/objectComponentsRequires.ts'); require( 'pages/contributor-dashboard-page/login-required-message/' + 'login-required-message.component.ts'); require( 'pages/contributor-dashboard-page/modal-templates/' + 'question-suggestion-review-modal.controller.ts'); require( 'pages/contributor-dashboard-page/modal-templates/' + 'translation-suggestion-review-modal.controller.ts'); require( 'pages/contributor-dashboard-page/services/' + 'contribution-and-review.service.ts'); require('services/alerts.service.ts'); require('services/context.service.ts'); require('services/suggestion-modal.service.ts'); require( // eslint-disable-next-line max-len 'pages/contributor-dashboard-page/contributor-dashboard-page.constants.ajs.ts'); angular.module('oppia').component('contributionsAndReview', { template: require('./contributions-and-review.component.html'), controller: [ '$filter', '$rootScope', '$uibModal', 'AlertsService', 'ContextService', 'ContributionAndReviewService', 'ContributionOpportunitiesService', 'QuestionObjectFactory', 'SkillBackendApiService', 'UrlInterpolationService', 'UserService', 'CORRESPONDING_DELETED_OPPORTUNITY_TEXT', 'IMAGE_CONTEXT', function( $filter, $rootScope, $uibModal, AlertsService, ContextService, ContributionAndReviewService, ContributionOpportunitiesService, QuestionObjectFactory, SkillBackendApiService, UrlInterpolationService, UserService, CORRESPONDING_DELETED_OPPORTUNITY_TEXT, IMAGE_CONTEXT) { var ctrl = this; ctrl.contributions = {}; var SUGGESTION_LABELS = { review: { text: 'Awaiting review', color: '#eeeeee' }, accepted: { text: 'Accepted', color: '#8ed274' }, rejected: { text: 'Revisions Requested', color: '#e76c8c' } }; var SUGGESTION_TYPE_QUESTION = 'add_question'; var SUGGESTION_TYPE_TRANSLATE = 'translate_content'; ctrl.TAB_TYPE_CONTRIBUTIONS = 'contributions'; ctrl.TAB_TYPE_REVIEWS = 'reviews'; var tabNameToOpportunityFetchFunction = { [SUGGESTION_TYPE_QUESTION]: { [ctrl.TAB_TYPE_CONTRIBUTIONS]: ( ContributionAndReviewService.getUserCreatedQuestionSuggestionsAsync ), [ctrl.TAB_TYPE_REVIEWS]: ( ContributionAndReviewService.getReviewableQuestionSuggestionsAsync) }, [SUGGESTION_TYPE_TRANSLATE]: { [ctrl.TAB_TYPE_CONTRIBUTIONS]: ( ContributionAndReviewService .getUserCreatedTranslationSuggestionsAsync), [ctrl.TAB_TYPE_REVIEWS]: ( ContributionAndReviewService .getReviewableTranslationSuggestionsAsync) } }; var getQuestionContributionsSummary = function( suggestionIdToSuggestions) { var questionContributionsSummaryList = []; Object.keys(suggestionIdToSuggestions).forEach(function(key) { var suggestion = suggestionIdToSuggestions[key].suggestion; var details = suggestionIdToSuggestions[key].details; var subheading = ''; if (details === null) { subheading = CORRESPONDING_DELETED_OPPORTUNITY_TEXT; } else { subheading = details.skill_description; } var change = suggestion.change; var requiredData = { id: suggestion.suggestion_id, heading: $filter('formatRtePreview')( change.question_dict.question_state_data.content.html), subheading: subheading, labelText: SUGGESTION_LABELS[suggestion.status].text, labelColor: SUGGESTION_LABELS[suggestion.status].color, actionButtonTitle: ( ctrl.activeTabType === ctrl.TAB_TYPE_REVIEWS ? 'Review' : 'View') }; questionContributionsSummaryList.push(requiredData); }); return questionContributionsSummaryList; }; var getTranslationContributionsSummary = function( suggestionIdToSuggestions) { var translationContributionsSummaryList = []; Object.keys(suggestionIdToSuggestions).forEach(function(key) { var suggestion = suggestionIdToSuggestions[key].suggestion; var details = suggestionIdToSuggestions[key].details; var subheading = ''; if (details === null) { subheading = CORRESPONDING_DELETED_OPPORTUNITY_TEXT; } else { subheading = ( details.topic_name + ' / ' + details.story_title + ' / ' + details.chapter_title); } var requiredData = { id: suggestion.suggestion_id, heading: getTranslationSuggestionHeading(suggestion), subheading: subheading, labelText: SUGGESTION_LABELS[suggestion.status].text, labelColor: SUGGESTION_LABELS[suggestion.status].color, actionButtonTitle: ( ctrl.activeTabType === ctrl.TAB_TYPE_REVIEWS ? 'Review' : 'View') }; translationContributionsSummaryList.push(requiredData); }); return translationContributionsSummaryList; }; var getTranslationSuggestionHeading = function(suggestion) { const changeTranslation = suggestion.change.translation_html; if (Array.isArray(changeTranslation)) { return $filter('formatRtePreview')(changeTranslation.join(', ')); } return $filter('formatRtePreview')(changeTranslation); }; var resolveSuggestionSuccess = function(suggestionId) { AlertsService.addSuccessMessage('Submitted suggestion review.'); ContributionOpportunitiesService.removeOpportunitiesEventEmitter.emit( [suggestionId]); }; var _showQuestionSuggestionModal = function( suggestion, contributionDetails, reviewable, misconceptionsBySkill) { var _templateUrl = UrlInterpolationService.getDirectiveTemplateUrl( '/pages/contributor-dashboard-page/modal-templates/' + 'question-suggestion-review.directive.html'); var targetId = suggestion.target_id; var suggestionId = suggestion.suggestion_id; var authorName = suggestion.author_name; var questionHeader = contributionDetails.skill_description; var question = QuestionObjectFactory.createFromBackendDict( suggestion.change.question_dict); var contentHtml = question.getStateData().content.html; var skillRubrics = contributionDetails.skill_rubrics; var skillDifficulty = suggestion.change.skill_difficulty; $uibModal.open({ templateUrl: _templateUrl, backdrop: 'static', size: 'lg', resolve: { suggestion: function() { return cloneDeep(suggestion); }, authorName: function() { return authorName; }, contentHtml: function() { return contentHtml; }, misconceptionsBySkill: function() { return misconceptionsBySkill; }, question: function() { return question; }, questionHeader: function() { return questionHeader; }, reviewable: function() { return reviewable; }, skillRubrics: function() { return skillRubrics; }, skillDifficulty: function() { return skillDifficulty; }, suggestionId: function() { return suggestionId; } }, controller: 'QuestionSuggestionReviewModalController' }).result.then(function(result) { ContributionAndReviewService.resolveSuggestiontoSkill( targetId, suggestionId, result.action, result.reviewMessage, result.skillDifficulty, resolveSuggestionSuccess, () => { AlertsService.addInfoMessage('Failed to submit suggestion.'); }); }, function() { // Note to developers: // This callback is triggered when the Cancel button is clicked. // No further action is needed. $rootScope.$applyAsync(); }); }; var _showTranslationSuggestionModal = function( suggestionIdToContribution, initialSuggestionId, reviewable) { var _templateUrl = UrlInterpolationService.getDirectiveTemplateUrl( '/pages/contributor-dashboard-page/modal-templates/' + 'translation-suggestion-review.directive.html'); var details = ctrl.contributions[initialSuggestionId].details; var subheading = ( details.topic_name + ' / ' + details.story_title + ' / ' + details.chapter_title); $uibModal.open({ templateUrl: _templateUrl, backdrop: 'static', size: 'lg', resolve: { suggestionIdToContribution: function() { return cloneDeep(suggestionIdToContribution); }, initialSuggestionId: function() { return initialSuggestionId; }, reviewable: function() { return reviewable; }, subheading: function() { return subheading; } }, controller: 'TranslationSuggestionReviewModalController' }).result.then(function(resolvedSuggestionIds) { ContributionOpportunitiesService.removeOpportunitiesEventEmitter.emit( resolvedSuggestionIds); resolvedSuggestionIds.forEach(function(suggestionId) { delete ctrl.contributions[suggestionId]; }); }, function() { // Note to developers: // This callback is triggered when the Cancel button is clicked. // No further action is needed. }); }; ctrl.isActiveTab = function(tabType, suggestionType) { return ( ctrl.activeTabType === tabType && ctrl.activeSuggestionType === suggestionType); }; ctrl.onClickViewSuggestion = function(suggestionId) { var suggestion = ctrl.contributions[suggestionId].suggestion; var reviewable = ctrl.activeTabType === ctrl.TAB_TYPE_REVIEWS; if (suggestion.suggestion_type === SUGGESTION_TYPE_QUESTION) { var contributionDetails = ctrl.contributions[suggestionId].details; var skillId = suggestion.change.skill_id; ContextService.setCustomEntityContext( IMAGE_CONTEXT.QUESTION_SUGGESTIONS, skillId); SkillBackendApiService.fetchSkillAsync(skillId).then((skillDict) => { var misconceptionsBySkill = {}; var skill = skillDict.skill; misconceptionsBySkill[skill.getId()] = skill.getMisconceptions(); _showQuestionSuggestionModal( suggestion, contributionDetails, reviewable, misconceptionsBySkill); $rootScope.$apply(); }); } if (suggestion.suggestion_type === SUGGESTION_TYPE_TRANSLATE) { const suggestionIdToContribution = {}; for (let suggestionId in ctrl.contributions) { var contribution = ctrl.contributions[suggestionId]; suggestionIdToContribution[suggestionId] = contribution; } ContextService.setCustomEntityContext( IMAGE_CONTEXT.EXPLORATION_SUGGESTIONS, suggestion.target_id); _showTranslationSuggestionModal( suggestionIdToContribution, suggestionId, reviewable); } }; var getContributionSummaries = function(suggestionIdToSuggestions) { if (ctrl.activeSuggestionType === SUGGESTION_TYPE_TRANSLATE) { return getTranslationContributionsSummary(suggestionIdToSuggestions); } else if (ctrl.activeSuggestionType === SUGGESTION_TYPE_QUESTION) { return getQuestionContributionsSummary(suggestionIdToSuggestions); } }; ctrl.switchToTab = function(tabType, suggestionType) { ctrl.activeSuggestionType = suggestionType; ctrl.activeTabType = tabType; ctrl.contributions = {}; ContributionOpportunitiesService.reloadOpportunitiesEventEmitter.emit(); }; ctrl.loadContributions = function() { if (!ctrl.activeTabType || !ctrl.activeSuggestionType) { return new Promise((resolve, reject) => { resolve({opportunitiesDicts: [], more: false}); }); } var fetchFunction = tabNameToOpportunityFetchFunction[ ctrl.activeSuggestionType][ctrl.activeTabType]; return fetchFunction().then(function(suggestionIdToSuggestions) { ctrl.contributions = suggestionIdToSuggestions; return { opportunitiesDicts: getContributionSummaries(ctrl.contributions), more: false }; }); }; ctrl.$onInit = function() { ctrl.contributions = []; ctrl.userDetailsLoading = true; ctrl.userIsLoggedIn = false; ctrl.activeTabType = ''; ctrl.activeSuggestionType = ''; ctrl.reviewTabs = []; ctrl.contributionTabs = [ { suggestionType: SUGGESTION_TYPE_QUESTION, text: 'Questions', enabled: false }, { suggestionType: SUGGESTION_TYPE_TRANSLATE, text: 'Translations', enabled: true } ]; UserService.getUserInfoAsync().then(function(userInfo) { ctrl.userIsLoggedIn = userInfo.isLoggedIn(); ctrl.userDetailsLoading = false; if (ctrl.userIsLoggedIn) { UserService.getUserContributionRightsDataAsync().then( function(userContributionRights) { var userCanReviewTranslationSuggestionsInLanguages = ( userContributionRights .can_review_translation_for_language_codes); var userCanReviewQuestionSuggestions = ( userContributionRights.can_review_questions); var userReviewableSuggestionTypes = []; var userCanSuggestQuestions = ( userContributionRights.can_suggest_questions); for (var index in ctrl.contributionTabs) { if (ctrl.contributionTabs[index].suggestionType === ( SUGGESTION_TYPE_QUESTION)) { ctrl.contributionTabs[index].enabled = ( userCanSuggestQuestions); } } if (userCanReviewQuestionSuggestions) { ctrl.reviewTabs.push({ suggestionType: SUGGESTION_TYPE_QUESTION, text: 'Review Questions' }); userReviewableSuggestionTypes.push(SUGGESTION_TYPE_QUESTION); } if ( userCanReviewTranslationSuggestionsInLanguages .length > 0) { ctrl.reviewTabs.push({ suggestionType: SUGGESTION_TYPE_TRANSLATE, text: 'Review Translations' }); userReviewableSuggestionTypes.push(SUGGESTION_TYPE_TRANSLATE); } if (userReviewableSuggestionTypes.length > 0) { ctrl.switchToTab( ctrl.TAB_TYPE_REVIEWS, userReviewableSuggestionTypes[0]); } else if (userCanSuggestQuestions) { ctrl.switchToTab( ctrl.TAB_TYPE_CONTRIBUTIONS, SUGGESTION_TYPE_QUESTION); } else { ctrl.switchToTab( ctrl.TAB_TYPE_CONTRIBUTIONS, SUGGESTION_TYPE_TRANSLATE); } // TODO(#8521): Remove the use of $rootScope.$apply() // once the controller is migrated to angular. $rootScope.$applyAsync(); }); } // TODO(#8521): Remove the use of $rootScope.$apply() // once the controller is migrated to angular. $rootScope.$applyAsync(); }); }; } ] });
the_stack
import { $QLike, ActiveUIView, extend, filter, HookRegOptions, isDefined, isFunction, isString, kebobString, noop, Obj, Param, parse, PathNode, ResolveContext, StateDeclaration, tail, trace, Transition, TransitionService, TypedMap, unnestR, ViewService, } from '@uirouter/core'; import { IAugmentedJQuery, IInterpolateService, IScope, ITranscludeFunction } from 'angular'; import { ng as angular } from '../angular'; import { Ng1Controller, Ng1StateDeclaration } from '../interface'; import { getLocals } from '../services'; import { Ng1ViewConfig } from '../statebuilders/views'; import { ng1_directive } from './stateDirectives'; /** @hidden */ export type UIViewData = { $cfg: Ng1ViewConfig; $uiView: ActiveUIView; }; /** @hidden */ export type UIViewAnimData = { $animEnter: Promise<any>; $animLeave: Promise<any>; $$animLeave: { resolve: () => any }; // "deferred" }; /** * `ui-view`: A viewport directive which is filled in by a view from the active state. * * ### Attributes * * - `name`: (Optional) A view name. * The name should be unique amongst the other views in the same state. * You can have views of the same name that live in different states. * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]). * * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated. * Uses [[$uiViewScroll]] to do the scrolling. * * - `onload`: Expression to evaluate whenever the view updates. * * #### Example: * A view can be unnamed or named. * ```html * <!-- Unnamed --> * <div ui-view></div> * * <!-- Named --> * <div ui-view="viewName"></div> * * <!-- Named (different style) --> * <ui-view name="viewName"></ui-view> * ``` * * You can only have one unnamed view within any template (or root html). If you are only using a * single view and it is unnamed then you can populate it like so: * * ```html * <div ui-view></div> * $stateProvider.state("home", { * template: "<h1>HELLO!</h1>" * }) * ``` * * The above is a convenient shortcut equivalent to specifying your view explicitly with the * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name: * * ```js * $stateProvider.state("home", { * views: { * "": { * template: "<h1>HELLO!</h1>" * } * } * }) * ``` * * But typically you'll only use the views property if you name your view or have more than one view * in the same template. There's not really a compelling reason to name a view if its the only one, * but you could if you wanted, like so: * * ```html * <div ui-view="main"></div> * ``` * * ```js * $stateProvider.state("home", { * views: { * "main": { * template: "<h1>HELLO!</h1>" * } * } * }) * ``` * * Really though, you'll use views to set up multiple views: * * ```html * <div ui-view></div> * <div ui-view="chart"></div> * <div ui-view="data"></div> * ``` * * ```js * $stateProvider.state("home", { * views: { * "": { * template: "<h1>HELLO!</h1>" * }, * "chart": { * template: "<chart_thing/>" * }, * "data": { * template: "<data_thing/>" * } * } * }) * ``` * * #### Examples for `autoscroll`: * ```html * <!-- If autoscroll present with no expression, * then scroll ui-view into view --> * <ui-view autoscroll/> * * <!-- If autoscroll present with valid expression, * then scroll ui-view into view if expression evaluates to true --> * <ui-view autoscroll='true'/> * <ui-view autoscroll='false'/> * <ui-view autoscroll='scopeVariable'/> * ``` * * Resolve data: * * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template. * * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which * depends on `$resolve` data. * * #### Example: * ```js * $stateProvider.state('home', { * template: '<my-component user="$resolve.user"></my-component>', * resolve: { * user: function(UserService) { return UserService.fetchUser(); } * } * }); * ``` */ export let uiView: ng1_directive; // eslint-disable-next-line prefer-const uiView = [ '$view', '$animate', '$uiViewScroll', '$interpolate', '$q', function $ViewDirective( $view: ViewService, $animate: any, $uiViewScroll: any, $interpolate: IInterpolateService, $q: $QLike ) { function getRenderer() { return { enter: function (element: JQuery, target: any, cb: Function) { if (angular.version.minor > 2) { $animate.enter(element, null, target).then(cb); } else { $animate.enter(element, null, target, cb); } }, leave: function (element: JQuery, cb: Function) { if (angular.version.minor > 2) { $animate.leave(element).then(cb); } else { $animate.leave(element, cb); } }, }; } function configsEqual(config1: Ng1ViewConfig, config2: Ng1ViewConfig) { return config1 === config2; } const rootData = { $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } }, $uiView: {}, }; const directive = { count: 0, restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', compile: function (tElement: JQuery, tAttrs: Obj, $transclude: ITranscludeFunction) { return function (scope: IScope, $element: IAugmentedJQuery, attrs: Obj) { const onloadExp = attrs['onload'] || '', autoScrollExp = attrs['autoscroll'], renderer = getRenderer(), inherited = $element.inheritedData('$uiView') || rootData, name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default'; let previousEl: JQuery, currentEl: JQuery, currentScope: IScope, viewConfig: Ng1ViewConfig; const activeUIView: ActiveUIView = { $type: 'ng1', id: directive.count++, // Global sequential ID for ui-view tags added to DOM name: name, // ui-view name (<div ui-view="name"></div> fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, // fully qualified name, describes location in DOM config: null, // The ViewConfig loaded (from a state.views definition) configUpdated: configUpdatedCallback, // Called when the matching ViewConfig changes get creationContext() { // The context in which this ui-view "tag" was created const fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited); // Allow <ui-view name="foo"><ui-view name="bar"></ui-view></ui-view> // See https://github.com/angular-ui/ui-router/issues/3355 const fromParentTag = parse('$uiView.creationContext')(inherited); return fromParentTagConfig || fromParentTag; }, }; trace.traceUIViewEvent('Linking', activeUIView); function configUpdatedCallback(config?: Ng1ViewConfig) { if (config && !(config instanceof Ng1ViewConfig)) return; if (configsEqual(viewConfig, config)) return; trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context); viewConfig = config; updateView(config); } $element.data('$uiView', { $uiView: activeUIView }); updateView(); const unregister = $view.registerUIView(activeUIView); scope.$on('$destroy', function () { trace.traceUIViewEvent('Destroying/Unregistering', activeUIView); unregister(); }); function cleanupLastView() { if (previousEl) { trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView')); previousEl.remove(); previousEl = null; } if (currentScope) { trace.traceUIViewEvent('Destroying scope', activeUIView); currentScope.$destroy(); currentScope = null; } if (currentEl) { const _viewData = currentEl.data('$uiViewAnim'); trace.traceUIViewEvent('Animate out', _viewData); renderer.leave(currentEl, function () { _viewData.$$animLeave.resolve(); previousEl = null; }); previousEl = currentEl; currentEl = null; } } function updateView(config?: Ng1ViewConfig) { const newScope = scope.$new(); const animEnter = $q.defer(), animLeave = $q.defer(); const $uiViewData: UIViewData = { $cfg: config, $uiView: activeUIView, }; const $uiViewAnim: UIViewAnimData = { $animEnter: animEnter.promise, $animLeave: animLeave.promise, $$animLeave: animLeave, }; /** * @ngdoc event * @name ui.router.state.directive:ui-view#$viewContentLoading * @eventOf ui.router.state.directive:ui-view * @eventType emits on ui-view directive scope * @description * * Fired once the view **begins loading**, *before* the DOM is rendered. * * @param {Object} event Event object. * @param {string} viewName Name of the view. */ newScope.$emit('$viewContentLoading', name); const cloned = $transclude(newScope, function (clone) { clone.data('$uiViewAnim', $uiViewAnim); clone.data('$uiView', $uiViewData); renderer.enter(clone, $element, function onUIViewEnter() { animEnter.resolve(); if (currentScope) currentScope.$emit('$viewContentAnimationEnded'); if ((isDefined(autoScrollExp) && !autoScrollExp) || scope.$eval(autoScrollExp)) { $uiViewScroll(clone); } }); cleanupLastView(); }); currentEl = cloned; currentScope = newScope; /** * @ngdoc event * @name ui.router.state.directive:ui-view#$viewContentLoaded * @eventOf ui.router.state.directive:ui-view * @eventType emits on ui-view directive scope * @description * * Fired once the view is **loaded**, *after* the DOM is rendered. * * @param {Object} event Event object. */ currentScope.$emit('$viewContentLoaded', config || viewConfig); currentScope.$eval(onloadExp); } }; }, }; return directive; }, ]; $ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q']; /** @hidden */ function $ViewDirectiveFill( $compile: angular.ICompileService, $controller: angular.IControllerService, $transitions: TransitionService, $view: ViewService, $q: angular.IQService ) { const getControllerAs = parse('viewDecl.controllerAs'); const getResolveAs = parse('viewDecl.resolveAs'); return { restrict: 'ECA', priority: -400, compile: function (tElement: JQuery) { const initial = tElement.html(); tElement.empty(); return function (scope: IScope, $element: JQuery) { const data: UIViewData = $element.data('$uiView'); if (!data) { $element.html(initial); $compile($element.contents() as any)(scope); return; } const cfg: Ng1ViewConfig = data.$cfg || <any>{ viewDecl: {}, getTemplate: noop }; const resolveCtx: ResolveContext = cfg.path && new ResolveContext(cfg.path); $element.html(cfg.getTemplate($element, resolveCtx) || initial); trace.traceUIViewFill(data.$uiView, $element.html()); const link = $compile($element.contents() as any); const controller = cfg.controller as angular.IControllerService; const controllerAs: string = getControllerAs(cfg); const resolveAs: string = getResolveAs(cfg); const locals = resolveCtx && getLocals(resolveCtx); scope[resolveAs] = locals; if (controller) { const controllerInstance = <Ng1Controller>( $controller(controller, extend({}, locals, { $scope: scope, $element: $element })) ); if (controllerAs) { scope[controllerAs] = controllerInstance; scope[controllerAs][resolveAs] = locals; } // TODO: Use $view service as a central point for registering component-level hooks // Then, when a component is created, tell the $view service, so it can invoke hooks // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element }); // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element })); $element.data('$ngControllerController', controllerInstance); $element.children().data('$ngControllerController', controllerInstance); registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg); } // Wait for the component to appear in the DOM if (isString(cfg.component)) { const kebobName = kebobString(cfg.component); const tagRegexp = new RegExp(`^(x-|data-)?${kebobName}$`, 'i'); const getComponentController = () => { const directiveEl = [].slice .call($element[0].children) .filter((el: Element) => el && el.tagName && tagRegexp.exec(el.tagName)); return directiveEl && angular.element(directiveEl).data(`$${cfg.component}Controller`); }; const deregisterWatch = scope.$watch(getComponentController, function (ctrlInstance) { if (!ctrlInstance) return; registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg); deregisterWatch(); }); } link(scope); }; }, }; } /** @hidden */ const hasComponentImpl = typeof (angular as any).module('ui.router')['component'] === 'function'; /** @hidden incrementing id */ let _uiCanExitId = 0; /** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */ function registerControllerCallbacks( $q: angular.IQService, $transitions: TransitionService, controllerInstance: Ng1Controller, $scope: IScope, cfg: Ng1ViewConfig ) { // Call $onInit() ASAP if ( isFunction(controllerInstance.$onInit) && !((cfg.viewDecl.component || cfg.viewDecl.componentProvider) && hasComponentImpl) ) { controllerInstance.$onInit(); } const viewState: Ng1StateDeclaration = tail(cfg.path).state.self; const hookOptions: HookRegOptions = { bind: controllerInstance }; // Add component-level hook for onUiParamsChanged if (isFunction(controllerInstance.uiOnParamsChanged)) { const resolveContext: ResolveContext = new ResolveContext(cfg.path); const viewCreationTrans = resolveContext.getResolvable('$transition$').data; // Fire callback on any successful transition const paramsUpdated = ($transition$: Transition) => { // Exit early if the $transition$ is the same as the view was created within. // Exit early if the $transition$ will exit the state the view is for. if ($transition$ === viewCreationTrans || $transition$.exiting().indexOf(viewState as StateDeclaration) !== -1) return; const toParams = $transition$.params('to') as TypedMap<any>; const fromParams = $transition$.params<TypedMap<any>>('from') as TypedMap<any>; const getNodeSchema = (node: PathNode) => node.paramSchema; const toSchema: Param[] = $transition$.treeChanges('to').map(getNodeSchema).reduce(unnestR, []); const fromSchema: Param[] = $transition$.treeChanges('from').map(getNodeSchema).reduce(unnestR, []); // Find the to params that have different values than the from params const changedToParams = toSchema.filter((param: Param) => { const idx = fromSchema.indexOf(param); return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]); }); // Only trigger callback if a to param has changed or is new if (changedToParams.length) { const changedKeys: string[] = changedToParams.map((x) => x.id); // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params. const newValues = filter(toParams, (val, key) => changedKeys.indexOf(key) !== -1); controllerInstance.uiOnParamsChanged(newValues, $transition$); } }; $scope.$on('$destroy', <any>$transitions.onSuccess({}, paramsUpdated, hookOptions)); } // Add component-level hook for uiCanExit if (isFunction(controllerInstance.uiCanExit)) { const id = _uiCanExitId++; const cacheProp = '_uiCanExitIds'; // Returns true if a redirect transition already answered truthy const prevTruthyAnswer = (trans: Transition) => !!trans && ((trans[cacheProp] && trans[cacheProp][id] === true) || prevTruthyAnswer(trans.redirectedFrom())); // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition const wrappedHook = (trans: Transition) => { let promise; const ids = (trans[cacheProp] = trans[cacheProp] || {}); if (!prevTruthyAnswer(trans)) { promise = $q.when(controllerInstance.uiCanExit(trans)); promise.then((val) => (ids[id] = val !== false)); } return promise; }; const criteria = { exiting: viewState.name }; $scope.$on('$destroy', <any>$transitions.onBefore(criteria, wrappedHook, hookOptions)); } } angular.module('ui.router.state').directive('uiView', <any>uiView); angular.module('ui.router.state').directive('uiView', <any>$ViewDirectiveFill);
the_stack
namespace Reflect { // Metadata Proposal // https://rbuckton.github.io/reflect-metadata/ type HashMap<V> = Record<string, V>; interface BufferLike { [offset: number]: number; length: number; } type IteratorResult<T> = { value: T, done: false } | { value: never, done: true }; interface Iterator<T> { next(value?: any): IteratorResult<T>; throw?(value: any): IteratorResult<T>; return?(value?: T): IteratorResult<T>; } interface Iterable<T> { "@@iterator"(): Iterator<T>; } interface IterableIterator<T> extends Iterator<T> { "@@iterator"(): IterableIterator<T>; } interface Map<K, V> extends Iterable<[K, V]> { size: number; has(key: K): boolean; get(key: K): V; set(key: K, value?: V): this; delete(key: K): boolean; clear(): void; keys(): IterableIterator<K>; values(): IterableIterator<V>; entries(): IterableIterator<[K, V]>; } interface MapConstructor { new (): Map<any, any>; new <K, V>(): Map<K, V>; prototype: Map<any, any>; } interface Set<T> extends Iterable<T> { size: number; has(value: T): boolean; add(value: T): this; delete(value: T): boolean; clear(): void; keys(): IterableIterator<T>; values(): IterableIterator<T>; entries(): IterableIterator<[T, T]>; } interface SetConstructor { new (): Set<any>; new <T>(): Set<T>; prototype: Set<any>; } interface WeakMap<K, V> { clear(): void; delete(key: K): boolean; get(key: K): V; has(key: K): boolean; set(key: K, value?: V): WeakMap<K, V>; } interface WeakMapConstructor { new (): WeakMap<any, any>; new <K, V>(): WeakMap<K, V>; prototype: WeakMap<any, any>; } type MemberDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor?: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void; declare const Symbol: { iterator: symbol, toPrimitive: symbol }; declare const Set: SetConstructor; declare const WeakMap: WeakMapConstructor; declare const Map: MapConstructor; declare const global: any; declare const crypto: Crypto; declare const msCrypto: Crypto; declare const process: any; /** * Applies a set of decorators to a target object. * @param decorators An array of decorators. * @param target The target object. * @returns The result of applying the provided decorators. * @remarks Decorators are applied in reverse order of their positions in the array. * @example * * class Example { } * * // constructor * Example = Reflect.decorate(decoratorsArray, Example); * */ export declare function decorate(decorators: ClassDecorator[], target: Function): Function; /** * Applies a set of decorators to a property of a target object. * @param decorators An array of decorators. * @param target The target object. * @param propertyKey The property key to decorate. * @param attributes A property descriptor. * @remarks Decorators are applied in reverse order. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod() { } * method() { } * } * * // property (on constructor) * Reflect.decorate(decoratorsArray, Example, "staticProperty"); * * // property (on prototype) * Reflect.decorate(decoratorsArray, Example.prototype, "property"); * * // method (on constructor) * Object.defineProperty(Example, "staticMethod", * Reflect.decorate(decoratorsArray, Example, "staticMethod", * Object.getOwnPropertyDescriptor(Example, "staticMethod"))); * * // method (on prototype) * Object.defineProperty(Example.prototype, "method", * Reflect.decorate(decoratorsArray, Example.prototype, "method", * Object.getOwnPropertyDescriptor(Example.prototype, "method"))); * */ export declare function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, attributes?: PropertyDescriptor | null): PropertyDescriptor | undefined; /** * Applies a set of decorators to a property of a target object. * @param decorators An array of decorators. * @param target The target object. * @param propertyKey The property key to decorate. * @param attributes A property descriptor. * @remarks Decorators are applied in reverse order. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod() { } * method() { } * } * * // property (on constructor) * Reflect.decorate(decoratorsArray, Example, "staticProperty"); * * // property (on prototype) * Reflect.decorate(decoratorsArray, Example.prototype, "property"); * * // method (on constructor) * Object.defineProperty(Example, "staticMethod", * Reflect.decorate(decoratorsArray, Example, "staticMethod", * Object.getOwnPropertyDescriptor(Example, "staticMethod"))); * * // method (on prototype) * Object.defineProperty(Example.prototype, "method", * Reflect.decorate(decoratorsArray, Example.prototype, "method", * Object.getOwnPropertyDescriptor(Example.prototype, "method"))); * */ export declare function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, attributes: PropertyDescriptor): PropertyDescriptor; /** * A default metadata decorator factory that can be used on a class, class member, or parameter. * @param metadataKey The key for the metadata entry. * @param metadataValue The value for the metadata entry. * @returns A decorator function. * @remarks * If `metadataKey` is already defined for the target and target key, the * metadataValue for that key will be overwritten. * @example * * // constructor * @Reflect.metadata(key, value) * class Example { * } * * // property (on constructor, TypeScript only) * class Example { * @Reflect.metadata(key, value) * static staticProperty; * } * * // property (on prototype, TypeScript only) * class Example { * @Reflect.metadata(key, value) * property; * } * * // method (on constructor) * class Example { * @Reflect.metadata(key, value) * static staticMethod() { } * } * * // method (on prototype) * class Example { * @Reflect.metadata(key, value) * method() { } * } * */ export declare function metadata(metadataKey: any, metadataValue: any): { (target: Function): void; (target: any, propertyKey: string | symbol): void; }; /** * Define a unique metadata entry on the target. * @param metadataKey A key used to store and retrieve metadata. * @param metadataValue A value that contains attached metadata. * @param target The target object on which to define metadata. * @example * * class Example { * } * * // constructor * Reflect.defineMetadata("custom:annotation", options, Example); * * // decorator factory as metadata-producing annotation. * function MyAnnotation(options): ClassDecorator { * return target => Reflect.defineMetadata("custom:annotation", options, target); * } * */ export declare function defineMetadata(metadataKey: any, metadataValue: any, target: any): void; /** * Define a unique metadata entry on the target. * @param metadataKey A key used to store and retrieve metadata. * @param metadataValue A value that contains attached metadata. * @param target The target object on which to define metadata. * @param propertyKey The property key for the target. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * Reflect.defineMetadata("custom:annotation", Number, Example, "staticProperty"); * * // property (on prototype) * Reflect.defineMetadata("custom:annotation", Number, Example.prototype, "property"); * * // method (on constructor) * Reflect.defineMetadata("custom:annotation", Number, Example, "staticMethod"); * * // method (on prototype) * Reflect.defineMetadata("custom:annotation", Number, Example.prototype, "method"); * * // decorator factory as metadata-producing annotation. * function MyAnnotation(options): PropertyDecorator { * return (target, key) => Reflect.defineMetadata("custom:annotation", options, target, key); * } * */ export declare function defineMetadata(metadataKey: any, metadataValue: any, target: any, propertyKey: string | symbol): void; /** * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. * @example * * class Example { * } * * // constructor * result = Reflect.hasMetadata("custom:annotation", Example); * */ export declare function hasMetadata(metadataKey: any, target: any): boolean; /** * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method"); * */ export declare function hasMetadata(metadataKey: any, target: any, propertyKey: string | symbol): boolean; /** * Gets a value indicating whether the target object has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. * @example * * class Example { * } * * // constructor * result = Reflect.hasOwnMetadata("custom:annotation", Example); * */ export declare function hasOwnMetadata(metadataKey: any, target: any): boolean; /** * Gets a value indicating whether the target object has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method"); * */ export declare function hasOwnMetadata(metadataKey: any, target: any, propertyKey: string | symbol): boolean; /** * Gets the metadata value for the provided metadata key on the target object or its prototype chain. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * } * * // constructor * result = Reflect.getMetadata("custom:annotation", Example); * */ export declare function getMetadata(metadataKey: any, target: any): any; /** * Gets the metadata value for the provided metadata key on the target object or its prototype chain. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "method"); * */ export declare function getMetadata(metadataKey: any, target: any, propertyKey: string | symbol): any; /** * Gets the metadata value for the provided metadata key on the target object. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * } * * // constructor * result = Reflect.getOwnMetadata("custom:annotation", Example); * */ export declare function getOwnMetadata(metadataKey: any, target: any): any; /** * Gets the metadata value for the provided metadata key on the target object. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method"); * */ export declare function getOwnMetadata(metadataKey: any, target: any, propertyKey: string | symbol): any; /** * Gets the metadata keys defined on the target object or its prototype chain. * @param target The target object on which the metadata is defined. * @returns An array of unique metadata keys. * @example * * class Example { * } * * // constructor * result = Reflect.getMetadataKeys(Example); * */ export declare function getMetadataKeys(target: any): any[]; /** * Gets the metadata keys defined on the target object or its prototype chain. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.getMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "method"); * */ export declare function getMetadataKeys(target: any, propertyKey: string | symbol): any[]; /** * Gets the unique metadata keys defined on the target object. * @param target The target object on which the metadata is defined. * @returns An array of unique metadata keys. * @example * * class Example { * } * * // constructor * result = Reflect.getOwnMetadataKeys(Example); * */ export declare function getOwnMetadataKeys(target: any): any[]; /** * Gets the unique metadata keys defined on the target object. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "method"); * */ export declare function getOwnMetadataKeys(target: any, propertyKey: string | symbol): any[]; /** * Deletes the metadata entry from the target object with the provided key. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @returns `true` if the metadata entry was found and deleted; otherwise, false. * @example * * class Example { * } * * // constructor * result = Reflect.deleteMetadata("custom:annotation", Example); * */ export declare function deleteMetadata(metadataKey: any, target: any): boolean; /** * Deletes the metadata entry from the target object with the provided key. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey The property key for the target. * @returns `true` if the metadata entry was found and deleted; otherwise, false. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * static staticMethod(p) { } * method(p) { } * } * * // property (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method"); * */ export declare function deleteMetadata(metadataKey: any, target: any, propertyKey: string | symbol): boolean; (function (this: any, factory: (exporter: <K extends keyof typeof Reflect>(key: K, value: typeof Reflect[K]) => void) => void) { const root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : Function("return this;")(); let exporter = makeExporter(Reflect); if (typeof root.Reflect === "undefined") { root.Reflect = Reflect; } else { exporter = makeExporter(root.Reflect, exporter); } factory(exporter); function makeExporter(target: typeof Reflect, previous?: <K extends keyof typeof Reflect>(key: K, value: typeof Reflect[K]) => void) { return <K extends keyof typeof Reflect>(key: K, value: typeof Reflect[K]) => { if (typeof target[key] !== "function") { Object.defineProperty(target, key, { configurable: true, writable: true, value }); } if (previous) previous(key, value); }; } }) (function (exporter) { const hasOwn = Object.prototype.hasOwnProperty; // feature test for Symbol support const supportsSymbol = typeof Symbol === "function"; const toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; const iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; const supportsCreate = typeof Object.create === "function"; // feature test for Object.create support const supportsProto = { __proto__: [] } instanceof Array; // feature test for __proto__ support const downLevel = !supportsCreate && !supportsProto; const HashMap = { // create an object in dictionary mode (a.k.a. "slow" mode in v8) create: supportsCreate ? <V>() => MakeDictionary(Object.create(null) as HashMap<V>) : supportsProto ? <V>() => MakeDictionary({ __proto__: null as any } as HashMap<V>) : <V>() => MakeDictionary({} as HashMap<V>), has: downLevel ? <V>(map: HashMap<V>, key: string | number | symbol) => hasOwn.call(map, key) : <V>(map: HashMap<V>, key: string | number | symbol) => key in map, get: downLevel ? <V>(map: HashMap<V>, key: string | number | symbol): V | undefined => hasOwn.call(map, key) ? map[key as string | number] : undefined : <V>(map: HashMap<V>, key: string | number | symbol): V | undefined => map[key as string | number], }; // Load global or shim versions of Map, Set, and WeakMap const functionPrototype = Object.getPrototypeOf(Function); const usePolyfill = typeof process === "object" && process.env && process.env["REFLECT_METADATA_USE_MAP_POLYFILL"] === "true"; const _Map: typeof Map = !usePolyfill && typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); const _Set: typeof Set = !usePolyfill && typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); const _WeakMap: typeof WeakMap = !usePolyfill && typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); // [[Metadata]] internal slot // https://rbuckton.github.io/reflect-metadata/#ordinary-object-internal-methods-and-internal-slots const Metadata = new _WeakMap<any, Map<string | symbol | undefined, Map<any, any>>>(); function decorate(decorators: ClassDecorator[], target: Function): Function; function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, attributes?: PropertyDescriptor | null): PropertyDescriptor | undefined; function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, attributes: PropertyDescriptor): PropertyDescriptor; /** * Applies a set of decorators to a property of a target object. * @param decorators An array of decorators. * @param target The target object. * @param propertyKey (Optional) The property key to decorate. * @param attributes (Optional) The property descriptor for the target key. * @remarks Decorators are applied in reverse order. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * Example = Reflect.decorate(decoratorsArray, Example); * * // property (on constructor) * Reflect.decorate(decoratorsArray, Example, "staticProperty"); * * // property (on prototype) * Reflect.decorate(decoratorsArray, Example.prototype, "property"); * * // method (on constructor) * Object.defineProperty(Example, "staticMethod", * Reflect.decorate(decoratorsArray, Example, "staticMethod", * Object.getOwnPropertyDescriptor(Example, "staticMethod"))); * * // method (on prototype) * Object.defineProperty(Example.prototype, "method", * Reflect.decorate(decoratorsArray, Example.prototype, "method", * Object.getOwnPropertyDescriptor(Example.prototype, "method"))); * */ function decorate(decorators: (ClassDecorator | MemberDecorator)[], target: any, propertyKey?: string | symbol, attributes?: PropertyDescriptor | null): PropertyDescriptor | Function | undefined { if (!IsUndefined(propertyKey)) { if (!IsArray(decorators)) throw new TypeError(); if (!IsObject(target)) throw new TypeError(); if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) throw new TypeError(); if (IsNull(attributes)) attributes = undefined; propertyKey = ToPropertyKey(propertyKey); return DecorateProperty(<MemberDecorator[]>decorators, target, propertyKey, attributes); } else { if (!IsArray(decorators)) throw new TypeError(); if (!IsConstructor(target)) throw new TypeError(); return DecorateConstructor(<ClassDecorator[]>decorators, <Function>target); } } exporter("decorate", decorate); // 4.1.2 Reflect.metadata(metadataKey, metadataValue) // https://rbuckton.github.io/reflect-metadata/#reflect.metadata /** * A default metadata decorator factory that can be used on a class, class member, or parameter. * @param metadataKey The key for the metadata entry. * @param metadataValue The value for the metadata entry. * @returns A decorator function. * @remarks * If `metadataKey` is already defined for the target and target key, the * metadataValue for that key will be overwritten. * @example * * // constructor * @Reflect.metadata(key, value) * class Example { * } * * // property (on constructor, TypeScript only) * class Example { * @Reflect.metadata(key, value) * static staticProperty; * } * * // property (on prototype, TypeScript only) * class Example { * @Reflect.metadata(key, value) * property; * } * * // method (on constructor) * class Example { * @Reflect.metadata(key, value) * static staticMethod() { } * } * * // method (on prototype) * class Example { * @Reflect.metadata(key, value) * method() { } * } * */ function metadata(metadataKey: any, metadataValue: any) { function decorator(target: Function): void; function decorator(target: any, propertyKey: string | symbol): void; function decorator(target: any, propertyKey?: string | symbol): void { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) throw new TypeError(); OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } return decorator; } exporter("metadata", metadata); // 4.1.3 Reflect.defineMetadata(metadataKey, metadataValue, target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect.definemetadata function defineMetadata(metadataKey: any, metadataValue: any, target: any): void; function defineMetadata(metadataKey: any, metadataValue: any, target: any, propertyKey: string | symbol): void; /** * Define a unique metadata entry on the target. * @param metadataKey A key used to store and retrieve metadata. * @param metadataValue A value that contains attached metadata. * @param target The target object on which to define metadata. * @param propertyKey (Optional) The property key for the target. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * Reflect.defineMetadata("custom:annotation", options, Example); * * // property (on constructor) * Reflect.defineMetadata("custom:annotation", options, Example, "staticProperty"); * * // property (on prototype) * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "property"); * * // method (on constructor) * Reflect.defineMetadata("custom:annotation", options, Example, "staticMethod"); * * // method (on prototype) * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "method"); * * // decorator factory as metadata-producing annotation. * function MyAnnotation(options): Decorator { * return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key); * } * */ function defineMetadata(metadataKey: any, metadataValue: any, target: any, propertyKey?: string | symbol): void { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } exporter("defineMetadata", defineMetadata); // 4.1.4 Reflect.hasMetadata(metadataKey, target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect.hasmetadata function hasMetadata(metadataKey: any, target: any): boolean; function hasMetadata(metadataKey: any, target: any, propertyKey: string | symbol): boolean; /** * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.hasMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method"); * */ function hasMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): boolean { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryHasMetadata(metadataKey, target, propertyKey); } exporter("hasMetadata", hasMetadata); // 4.1.5 Reflect.hasOwnMetadata(metadataKey, target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect-hasownmetadata function hasOwnMetadata(metadataKey: any, target: any): boolean; function hasOwnMetadata(metadataKey: any, target: any, propertyKey: string | symbol): boolean; /** * Gets a value indicating whether the target object has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.hasOwnMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method"); * */ function hasOwnMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): boolean { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); } exporter("hasOwnMetadata", hasOwnMetadata); // 4.1.6 Reflect.getMetadata(metadataKey, target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect-getmetadata function getMetadata(metadataKey: any, target: any): any; function getMetadata(metadataKey: any, target: any, propertyKey: string | symbol): any; /** * Gets the metadata value for the provided metadata key on the target object or its prototype chain. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "method"); * */ function getMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): any { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryGetMetadata(metadataKey, target, propertyKey); } exporter("getMetadata", getMetadata); // 4.1.7 Reflect.getOwnMetadata(metadataKey, target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect-getownmetadata function getOwnMetadata(metadataKey: any, target: any): any; function getOwnMetadata(metadataKey: any, target: any, propertyKey: string | symbol): any; /** * Gets the metadata value for the provided metadata key on the target object. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getOwnMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method"); * */ function getOwnMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): any { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); } exporter("getOwnMetadata", getOwnMetadata); // 4.1.8 Reflect.getMetadataKeys(target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect-getmetadatakeys function getMetadataKeys(target: any): any[]; function getMetadataKeys(target: any, propertyKey: string | symbol): any[]; /** * Gets the metadata keys defined on the target object or its prototype chain. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getMetadataKeys(Example); * * // property (on constructor) * result = Reflect.getMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "method"); * */ function getMetadataKeys(target: any, propertyKey?: string | symbol): any[] { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryMetadataKeys(target, propertyKey); } exporter("getMetadataKeys", getMetadataKeys); // 4.1.9 Reflect.getOwnMetadataKeys(target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect-getownmetadata function getOwnMetadataKeys(target: any): any[]; function getOwnMetadataKeys(target: any, propertyKey: string | symbol): any[]; /** * Gets the unique metadata keys defined on the target object. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getOwnMetadataKeys(Example); * * // property (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "method"); * */ function getOwnMetadataKeys(target: any, propertyKey?: string | symbol): any[] { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryOwnMetadataKeys(target, propertyKey); } exporter("getOwnMetadataKeys", getOwnMetadataKeys); // 4.1.10 Reflect.deleteMetadata(metadataKey, target [, propertyKey]) // https://rbuckton.github.io/reflect-metadata/#reflect-deletemetadata function deleteMetadata(metadataKey: any, target: any): boolean; function deleteMetadata(metadataKey: any, target: any, propertyKey: string | symbol): boolean; /** * Deletes the metadata entry from the target object with the provided key. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata entry was found and deleted; otherwise, false. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.deleteMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method"); * */ function deleteMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): boolean { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); const metadataMap = GetOrCreateMetadataMap(target, propertyKey, /*Create*/ false); if (IsUndefined(metadataMap)) return false; if (!metadataMap.delete(metadataKey)) return false; if (metadataMap.size > 0) return true; const targetMetadata = Metadata.get(target); targetMetadata.delete(propertyKey); if (targetMetadata.size > 0) return true; Metadata.delete(target); return true; } exporter("deleteMetadata", deleteMetadata); function DecorateConstructor(decorators: ClassDecorator[], target: Function): Function { for (let i = decorators.length - 1; i >= 0; --i) { const decorator = decorators[i]; const decorated = decorator(target); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsConstructor(decorated)) throw new TypeError(); target = <Function>decorated; } } return target; } function DecorateProperty(decorators: MemberDecorator[], target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor | undefined): PropertyDescriptor | undefined { for (let i = decorators.length - 1; i >= 0; --i) { const decorator = decorators[i]; const decorated = decorator(target, propertyKey, descriptor); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsObject(decorated)) throw new TypeError(); descriptor = <PropertyDescriptor>decorated; } } return descriptor; } // 2.1.1 GetOrCreateMetadataMap(O, P, Create) // https://rbuckton.github.io/reflect-metadata/#getorcreatemetadatamap function GetOrCreateMetadataMap(O: any, P: string | symbol | undefined, Create: true): Map<any, any>; function GetOrCreateMetadataMap(O: any, P: string | symbol | undefined, Create: false): Map<any, any> | undefined; function GetOrCreateMetadataMap(O: any, P: string | symbol | undefined, Create: boolean): Map<any, any> | undefined { let targetMetadata = Metadata.get(O); if (IsUndefined(targetMetadata)) { if (!Create) return undefined; targetMetadata = new _Map<string | symbol | undefined, Map<any, any>>(); Metadata.set(O, targetMetadata); } let metadataMap = targetMetadata.get(P); if (IsUndefined(metadataMap)) { if (!Create) return undefined; metadataMap = new _Map<any, any>(); targetMetadata.set(P, metadataMap); } return metadataMap; } // 3.1.1.1 OrdinaryHasMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasmetadata function OrdinaryHasMetadata(MetadataKey: any, O: any, P: string | symbol | undefined): boolean { const hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return true; const parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) return OrdinaryHasMetadata(MetadataKey, parent, P); return false; } // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata function OrdinaryHasOwnMetadata(MetadataKey: any, O: any, P: string | symbol | undefined): boolean { const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return false; return ToBoolean(metadataMap.has(MetadataKey)); } // 3.1.3.1 OrdinaryGetMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetmetadata function OrdinaryGetMetadata(MetadataKey: any, O: any, P: string | symbol | undefined): any { const hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return OrdinaryGetOwnMetadata(MetadataKey, O, P); const parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) return OrdinaryGetMetadata(MetadataKey, parent, P); return undefined; } // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata function OrdinaryGetOwnMetadata(MetadataKey: any, O: any, P: string | symbol | undefined): any { const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return undefined; return metadataMap.get(MetadataKey); } // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata function OrdinaryDefineOwnMetadata(MetadataKey: any, MetadataValue: any, O: any, P: string | symbol | undefined): void { const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ true); metadataMap.set(MetadataKey, MetadataValue); } // 3.1.6.1 OrdinaryMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarymetadatakeys function OrdinaryMetadataKeys(O: any, P: string | symbol | undefined): any[] { const ownKeys = OrdinaryOwnMetadataKeys(O, P); const parent = OrdinaryGetPrototypeOf(O); if (parent === null) return ownKeys; const parentKeys = OrdinaryMetadataKeys(parent, P); if (parentKeys.length <= 0) return ownKeys; if (ownKeys.length <= 0) return parentKeys; const set = new _Set<any>(); const keys: any[] = []; for (const key of ownKeys) { const hasKey = set.has(key); if (!hasKey) { set.add(key); keys.push(key); } } for (const key of parentKeys) { const hasKey = set.has(key); if (!hasKey) { set.add(key); keys.push(key); } } return keys; } // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys function OrdinaryOwnMetadataKeys(O: any, P: string | symbol | undefined): any[] { const keys: any[] = []; const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return keys; const keysObj = metadataMap.keys(); const iterator = GetIterator(keysObj); let k = 0; while (true) { const next = IteratorStep(iterator); if (!next) { keys.length = k; return keys; } const nextValue = IteratorValue(next); try { keys[k] = nextValue; } catch (e) { try { IteratorClose(iterator); } finally { throw e; } } k++; } } // 6 ECMAScript Data Typ0es and Values // https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values function Type(x: any): Tag { if (x === null) return Tag.Null; switch (typeof x) { case "undefined": return Tag.Undefined; case "boolean": return Tag.Boolean; case "string": return Tag.String; case "symbol": return Tag.Symbol; case "number": return Tag.Number; case "object": return x === null ? Tag.Null : Tag.Object; default: return Tag.Object; } } // 6.1 ECMAScript Language Types // https://tc39.github.io/ecma262/#sec-ecmascript-language-types const enum Tag { Undefined, Null, Boolean, String, Symbol, Number, Object } // 6.1.1 The Undefined Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-undefined-type function IsUndefined(x: any): x is undefined { return x === undefined; } // 6.1.2 The Null Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-null-type function IsNull(x: any): x is null { return x === null; } // 6.1.5 The Symbol Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-symbol-type function IsSymbol(x: any): x is symbol { return typeof x === "symbol"; } // 6.1.7 The Object Type // https://tc39.github.io/ecma262/#sec-object-type function IsObject<T>(x: T | undefined | null | boolean | string | symbol | number): x is T { return typeof x === "object" ? x !== null : typeof x === "function"; } // 7.1 Type Conversion // https://tc39.github.io/ecma262/#sec-type-conversion // 7.1.1 ToPrimitive(input [, PreferredType]) // https://tc39.github.io/ecma262/#sec-toprimitive function ToPrimitive(input: any, PreferredType?: Tag): undefined | null | boolean | string | symbol | number { switch (Type(input)) { case Tag.Undefined: return input; case Tag.Null: return input; case Tag.Boolean: return input; case Tag.String: return input; case Tag.Symbol: return input; case Tag.Number: return input; } const hint: "string" | "number" | "default" = PreferredType === Tag.String ? "string" : PreferredType === Tag.Number ? "number" : "default"; const exoticToPrim = GetMethod(input, toPrimitiveSymbol); if (exoticToPrim !== undefined) { const result = exoticToPrim.call(input, hint); if (IsObject(result)) throw new TypeError(); return result; } return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint); } // 7.1.1.1 OrdinaryToPrimitive(O, hint) // https://tc39.github.io/ecma262/#sec-ordinarytoprimitive function OrdinaryToPrimitive(O: any, hint: "string" | "number"): undefined | null | boolean | string | symbol | number { if (hint === "string") { const toString = O.toString; if (IsCallable(toString)) { const result = toString.call(O); if (!IsObject(result)) return result; } const valueOf = O.valueOf; if (IsCallable(valueOf)) { const result = valueOf.call(O); if (!IsObject(result)) return result; } } else { const valueOf = O.valueOf; if (IsCallable(valueOf)) { const result = valueOf.call(O); if (!IsObject(result)) return result; } const toString = O.toString; if (IsCallable(toString)) { const result = toString.call(O); if (!IsObject(result)) return result; } } throw new TypeError(); } // 7.1.2 ToBoolean(argument) // https://tc39.github.io/ecma262/2016/#sec-toboolean function ToBoolean(argument: any): boolean { return !!argument; } // 7.1.12 ToString(argument) // https://tc39.github.io/ecma262/#sec-tostring function ToString(argument: any): string { return "" + argument; } // 7.1.14 ToPropertyKey(argument) // https://tc39.github.io/ecma262/#sec-topropertykey function ToPropertyKey(argument: any): string | symbol { const key = ToPrimitive(argument, Tag.String); if (IsSymbol(key)) return key; return ToString(key); } // 7.2 Testing and Comparison Operations // https://tc39.github.io/ecma262/#sec-testing-and-comparison-operations // 7.2.2 IsArray(argument) // https://tc39.github.io/ecma262/#sec-isarray function IsArray(argument: any): argument is any[] { return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]"; } // 7.2.3 IsCallable(argument) // https://tc39.github.io/ecma262/#sec-iscallable function IsCallable(argument: any): argument is Function { // NOTE: This is an approximation as we cannot check for [[Call]] internal method. return typeof argument === "function"; } // 7.2.4 IsConstructor(argument) // https://tc39.github.io/ecma262/#sec-isconstructor function IsConstructor(argument: any): argument is Function { // NOTE: This is an approximation as we cannot check for [[Construct]] internal method. return typeof argument === "function"; } // 7.2.7 IsPropertyKey(argument) // https://tc39.github.io/ecma262/#sec-ispropertykey function IsPropertyKey(argument: any): argument is string | symbol { switch (Type(argument)) { case Tag.String: return true; case Tag.Symbol: return true; default: return false; } } // 7.3 Operations on Objects // https://tc39.github.io/ecma262/#sec-operations-on-objects // 7.3.9 GetMethod(V, P) // https://tc39.github.io/ecma262/#sec-getmethod function GetMethod(V: any, P: any): Function | undefined { const func = V[P]; if (func === undefined || func === null) return undefined; if (!IsCallable(func)) throw new TypeError(); return func; } // 7.4 Operations on Iterator Objects // https://tc39.github.io/ecma262/#sec-operations-on-iterator-objects function GetIterator<T>(obj: Iterable<T>): Iterator<T> { const method = GetMethod(obj, iteratorSymbol); if (!IsCallable(method)) throw new TypeError(); // from Call const iterator = method.call(obj); if (!IsObject(iterator)) throw new TypeError(); return iterator; } // 7.4.4 IteratorValue(iterResult) // https://tc39.github.io/ecma262/2016/#sec-iteratorvalue function IteratorValue<T>(iterResult: IteratorResult<T>): T { return iterResult.value; } // 7.4.5 IteratorStep(iterator) // https://tc39.github.io/ecma262/#sec-iteratorstep function IteratorStep<T>(iterator: Iterator<T>): IteratorResult<T> | false { const result = iterator.next(); return result.done ? false : result; } // 7.4.6 IteratorClose(iterator, completion) // https://tc39.github.io/ecma262/#sec-iteratorclose function IteratorClose<T>(iterator: Iterator<T>) { const f = iterator["return"]; if (f) f.call(iterator); } // 9.1 Ordinary Object Internal Methods and Internal Slots // https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots // 9.1.1.1 OrdinaryGetPrototypeOf(O) // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof function OrdinaryGetPrototypeOf(O: any): any { const proto = Object.getPrototypeOf(O); if (typeof O !== "function" || O === functionPrototype) return proto; // TypeScript doesn't set __proto__ in ES5, as it's non-standard. // Try to determine the superclass constructor. Compatible implementations // must either set __proto__ on a subclass constructor to the superclass constructor, // or ensure each class has a valid `constructor` property on its prototype that // points back to the constructor. // If this is not the same as Function.[[Prototype]], then this is definately inherited. // This is the case when in ES6 or when using __proto__ in a compatible browser. if (proto !== functionPrototype) return proto; // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. const prototype = O.prototype; const prototypeProto = prototype && Object.getPrototypeOf(prototype); if (prototypeProto == null || prototypeProto === Object.prototype) return proto; // If the constructor was not a function, then we cannot determine the heritage. const constructor = prototypeProto.constructor; if (typeof constructor !== "function") return proto; // If we have some kind of self-reference, then we cannot determine the heritage. if (constructor === O) return proto; // we have a pretty good guess at the heritage. return constructor; } // naive Map shim function CreateMapPolyfill(): MapConstructor { const cacheSentinel = {}; const arraySentinel: any[] = []; class MapIterator<K, V, R extends (K | V | [K, V])> implements IterableIterator<R> { private _keys: K[]; private _values: V[]; private _index = 0; private _selector: (key: K, value: V) => R; constructor(keys: K[], values: V[], selector: (key: K, value: V) => R) { this._keys = keys; this._values = values; this._selector = selector; } "@@iterator"() { return this; } [iteratorSymbol]() { return this; } next(): IteratorResult<R> { const index = this._index; if (index >= 0 && index < this._keys.length) { const result = this._selector(this._keys[index], this._values[index]); if (index + 1 >= this._keys.length) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } else { this._index++; } return { value: result, done: false }; } return { value: <never>undefined, done: true }; } throw(error: any): IteratorResult<R> { if (this._index >= 0) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } throw error; } return(value?: R): IteratorResult<R> { if (this._index >= 0) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } return { value: <never>value, done: true }; } } return class Map<K, V> { private _keys: K[] = []; private _values: (V | undefined)[] = []; private _cacheKey = cacheSentinel; private _cacheIndex = -2; get size() { return this._keys.length; } has(key: K): boolean { return this._find(key, /*insert*/ false) >= 0; } get(key: K): V | undefined { const index = this._find(key, /*insert*/ false); return index >= 0 ? this._values[index] : undefined; } set(key: K, value: V): this { const index = this._find(key, /*insert*/ true); this._values[index] = value; return this; } delete(key: K): boolean { const index = this._find(key, /*insert*/ false); if (index >= 0) { const size = this._keys.length; for (let i = index + 1; i < size; i++) { this._keys[i - 1] = this._keys[i]; this._values[i - 1] = this._values[i]; } this._keys.length--; this._values.length--; if (key === this._cacheKey) { this._cacheKey = cacheSentinel; this._cacheIndex = -2; } return true; } return false; } clear(): void { this._keys.length = 0; this._values.length = 0; this._cacheKey = cacheSentinel; this._cacheIndex = -2; } keys() { return new MapIterator(this._keys, this._values, getKey); } values() { return new MapIterator(this._keys, this._values, getValue); } entries() { return new MapIterator(this._keys, this._values, getEntry); } "@@iterator"() { return this.entries(); } [iteratorSymbol]() { return this.entries(); } private _find(key: K, insert?: boolean): number { if (this._cacheKey !== key) { this._cacheIndex = this._keys.indexOf(this._cacheKey = key); } if (this._cacheIndex < 0 && insert) { this._cacheIndex = this._keys.length; this._keys.push(key); this._values.push(undefined); } return this._cacheIndex; } }; function getKey<K, V>(key: K, _: V) { return key; } function getValue<K, V>(_: K, value: V) { return value; } function getEntry<K, V>(key: K, value: V) { return [key, value] as [K, V]; } } // naive Set shim function CreateSetPolyfill(): SetConstructor { return class Set<T> { private _map = new _Map<any, any>(); get size() { return this._map.size; } has(value: T): boolean { return this._map.has(value); } add(value: T): Set<T> { return this._map.set(value, value), this; } delete(value: T): boolean { return this._map.delete(value); } clear(): void { this._map.clear(); } keys() { return this._map.keys(); } values() { return this._map.values(); } entries() { return this._map.entries(); } "@@iterator"() { return this.keys(); } [iteratorSymbol]() { return this.keys(); } }; } // naive WeakMap shim function CreateWeakMapPolyfill(): WeakMapConstructor { const UUID_SIZE = 16; const keys = HashMap.create<boolean>(); const rootKey = CreateUniqueKey(); return class WeakMap<K, V> { private _key = CreateUniqueKey(); has(target: K): boolean { const table = GetOrCreateWeakMapTable<K>(target, /*create*/ false); return table !== undefined ? HashMap.has(table, this._key) : false; } get(target: K): V { const table = GetOrCreateWeakMapTable<K>(target, /*create*/ false); return table !== undefined ? HashMap.get(table, this._key) : undefined; } set(target: K, value: V): WeakMap<K, V> { const table = GetOrCreateWeakMapTable<K>(target, /*create*/ true); table[this._key] = value; return this; } delete(target: K): boolean { const table = GetOrCreateWeakMapTable<K>(target, /*create*/ false); return table !== undefined ? delete table[this._key] : false; } clear(): void { // NOTE: not a real clear, just makes the previous data unreachable this._key = CreateUniqueKey(); } }; function CreateUniqueKey(): string { let key: string; do key = "@@WeakMap@@" + CreateUUID(); while (HashMap.has(keys, key)); keys[key] = true; return key; } function GetOrCreateWeakMapTable<K>(target: K, create: true): HashMap<any>; function GetOrCreateWeakMapTable<K>(target: K, create: false): HashMap<any> | undefined; function GetOrCreateWeakMapTable<K>(target: K, create: boolean): HashMap<any> | undefined { if (!hasOwn.call(target, rootKey)) { if (!create) return undefined; Object.defineProperty(target, rootKey, { value: HashMap.create<any>() }); } return (<any>target)[rootKey]; } function FillRandomBytes(buffer: BufferLike, size: number): BufferLike { for (let i = 0; i < size; ++i) buffer[i] = Math.random() * 0xff | 0; return buffer; } function GenRandomBytes(size: number): BufferLike { if (typeof Uint8Array === "function") { if (typeof crypto !== "undefined") return crypto.getRandomValues(new Uint8Array(size)) as Uint8Array; if (typeof msCrypto !== "undefined") return msCrypto.getRandomValues(new Uint8Array(size)) as Uint8Array; return FillRandomBytes(new Uint8Array(size), size); } return FillRandomBytes(new Array(size), size); } function CreateUUID() { const data = GenRandomBytes(UUID_SIZE); // mark as random - RFC 4122 § 4.4 data[6] = data[6] & 0x4f | 0x40; data[8] = data[8] & 0xbf | 0x80; let result = ""; for (let offset = 0; offset < UUID_SIZE; ++offset) { const byte = data[offset]; if (offset === 4 || offset === 6 || offset === 8) result += "-"; if (byte < 16) result += "0"; result += byte.toString(16).toLowerCase(); } return result; } } // uses a heuristic used by v8 and chakra to force an object into dictionary mode. function MakeDictionary<T>(obj: T): T { (<any>obj).__ = undefined; delete (<any>obj).__; return obj; } }); }
the_stack
import { call, put, all, fork, select, takeLatest, takeEvery } from 'redux-saga/effects' import { IWidgetFormed } from 'app/containers/Widget/types' import { ActionTypes } from './constants' import { DashboardActions, DashboardActionType } from './actions' import { makeSelectDashboard, makeSelectItems, makeSelectItemRelatedWidget, makeSelectItemInfo, makeSelectFormedViews, makeSelectWidgets } from './selectors' import { makeSelectShareType } from 'share/containers/App/selectors' import { makeSelectGlobalControlPanelFormValues, makeSelectLocalControlPanelFormValues } from 'app/containers/ControlPanel/selectors' import { ControlPanelTypes } from 'app/components/Control/constants' import { ActionTypes as AppActions } from 'share/containers/App/constants' import { dashboardConfigMigrationRecorder, widgetConfigMigrationRecorder } from 'app/utils/migrationRecorders' import { getRequestParams, getRequestBody, getUpdatedPagination, getCurrentControlValues, getInitialPagination } from 'app/containers/Dashboard/util' import { IShareDashboardDetailRaw, IShareWidgetDetailRaw, IShareDashboardItemInfo } from './types' import { IDashboardConfig, IDashboard, IQueryConditions, IDashboardItem } from 'app/containers/Dashboard/types' import { IShareFormedViews } from 'app/containers/View/types' import { IGlobalControlConditions, IGlobalControlConditionsByItem, ILocalControlConditions } from 'app/components/Control/types' import { IWidgetConfig, RenderType } from 'app/containers/Widget/components/Widget' import request, { IDavinciResponse } from 'utils/request' import { errorHandler, getErrorMessage } from 'utils/util' import api from 'utils/api' import { message } from 'antd' import { DownloadTypes } from 'app/containers/App/constants' import { localStorageCRUD, getPasswordUrl } from '../../util' import { operationWidgetProps } from 'app/components/DataDrill/abstract/widgetOperating' export function* getDashboard(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_SHARE_DASHBOARD) { return } const { dashboardGetted, loadDashboardFail } = DashboardActions const { token, reject } = action.payload const shareType = yield select(makeSelectShareType()) const baseUrl = `${api.share}/dashboard/${token}` const requestUrl = getPasswordUrl(shareType, token, baseUrl) try { const result = yield call(request, requestUrl) const { widgets, views, relations, config, ...rest } = result.payload as IShareDashboardDetailRaw const parsedConfig: IDashboardConfig = JSON.parse(config || '{}') const dashboard = { ...rest, config: dashboardConfigMigrationRecorder(parsedConfig) } const formedWidgets = widgets.map((widget) => { const { config, ...rest } = widget const parsedConfig: IWidgetConfig = JSON.parse(config) return { ...rest, config: widgetConfigMigrationRecorder(parsedConfig, { viewId: widget.viewId }) } }) const formedViews = views.reduce( (obj, { id, model, variable, ...rest }) => ({ ...obj, [id]: { ...rest, model: JSON.parse(model), variable: JSON.parse(variable) } }), {} ) yield put(dashboardGetted(dashboard, relations, formedWidgets, formedViews)) const getWidgets: IWidgetFormed = yield select(makeSelectWidgets()) operationWidgetProps.widgetIntoPool(getWidgets) } catch (err) { yield put(loadDashboardFail()) errorHandler(err) reject(err) } } export function* getWidget(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_SHARE_WIDGET) { return } const { widgetGetted } = DashboardActions const { token, resolve, reject } = action.payload const shareType = yield select(makeSelectShareType()) const baseUrl = `${api.share}/widget/${token}` const requestUrl = getPasswordUrl(shareType, token, baseUrl) try { const result = yield call(request, requestUrl) const { widget, views } = result.payload as IShareWidgetDetailRaw const { config, ...rest } = widget const parsedConfig: IWidgetConfig = JSON.parse(config) const formedWidget = { ...rest, config: widgetConfigMigrationRecorder(parsedConfig, { viewId: widget.viewId }) } const formedViews = views.reduce( (obj, { id, model, variable, ...rest }) => ({ ...obj, [id]: { ...rest, model: JSON.parse(model), variable: JSON.parse(variable) } }), {} ) yield put(widgetGetted(formedWidget, formedViews)) const getWidgets: IWidgetFormed = yield select(makeSelectWidgets()) operationWidgetProps.widgetIntoPool(getWidgets) if (resolve) { resolve(formedWidget, formedViews) } } catch (err) { errorHandler(err) reject(err) } } function* getData( renderType: RenderType, itemId: number, queryConditions: Partial<IQueryConditions>, resetPagination?: boolean ) { const { resultsetGetted, getResultsetFail } = DashboardActions const itemInfo: IShareDashboardItemInfo = yield select((state) => makeSelectItemInfo()(state, itemId) ) const relatedWidget: IWidgetFormed = yield select((state) => makeSelectItemRelatedWidget()(state, itemId) ) const requestParams = getRequestParams( relatedWidget, itemInfo.queryConditions, renderType === 'flush', queryConditions ) if (resetPagination) { const initialPagination = getInitialPagination(relatedWidget) if (initialPagination) { const { pageNo, pageSize } = initialPagination requestParams.pagination = { ...requestParams.pagination, pageNo, pageSize } } } try { const result = yield call(request, { method: 'post', url: `${api.share}/data/${relatedWidget.dataToken}`, data: getRequestBody(requestParams) }) result.payload.resultList = result.payload.resultList || [] requestParams.pagination = getUpdatedPagination( requestParams.pagination, result.payload ) yield put( resultsetGetted(renderType, itemId, requestParams, result.payload) ) } catch (err) { yield put(getResultsetFail(itemId, getErrorMessage(err))) } } export function* getResultset(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_SHARE_RESULTSET) { return } const { renderType, itemId, queryConditions } = action.payload yield getData(renderType, itemId, queryConditions) } export function* getBatchDataWithControlValues(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_BATCH_DATA_WITH_CONTROL_VALUES) { return } const { type, itemId, formValues } = action.payload const formedViews: IShareFormedViews = yield select(makeSelectFormedViews()) const currentItems: IDashboardItem[] = yield select(makeSelectItems()) if (type === ControlPanelTypes.Global) { const currentDashboard: IDashboard = yield select(makeSelectDashboard()) const globalControlFormValues = yield select( makeSelectGlobalControlPanelFormValues() ) const globalControlConditionsByItem = getCurrentControlValues( type, currentDashboard.config.filters, formedViews, globalControlFormValues, formValues, currentItems ) const globalControlConditionsByItemEntries: Array<[ string, IGlobalControlConditions ]> = Object.entries( globalControlConditionsByItem as IGlobalControlConditionsByItem ) while (globalControlConditionsByItemEntries.length) { const [itemId, queryConditions] = globalControlConditionsByItemEntries[0] yield fork(getData, 'clear', Number(itemId), queryConditions, true) globalControlConditionsByItemEntries.shift() } } else { const relatedWidget: IWidgetFormed = yield select((state) => makeSelectItemRelatedWidget()(state, itemId) ) const localControlFormValues = yield select((state) => makeSelectLocalControlPanelFormValues()(state, itemId) ) const localControlConditions = getCurrentControlValues( type, relatedWidget.config.controls, formedViews, localControlFormValues, formValues ) yield getData( 'clear', itemId, localControlConditions as ILocalControlConditions, true ) } } export function* getWidgetCsv(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_WIDGET_CSV) { return } const { widgetCsvLoaded, loadWidgetCsvFail } = DashboardActions const { itemId, requestParams, token } = action.payload const { filters, tempFilters, linkageFilters, globalFilters, variables, linkageVariables, globalVariables, ...rest } = requestParams try { const path = yield call(request, { method: 'post', url: `${api.share}/csv/${token}`, data: { ...rest, filters: filters .concat(tempFilters) .concat(linkageFilters) .concat(globalFilters), params: variables.concat(linkageVariables).concat(globalVariables) } }) yield put(widgetCsvLoaded(itemId)) location.href = path.payload // location.href = `data:application/octet-stream,${encodeURIComponent(asyncData)}` } catch (err) { yield put(loadWidgetCsvFail(itemId)) errorHandler(err) } } export function* getSelectOptions(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_SELECT_OPTIONS) { return } const { selectOptionsLoaded, loadSelectOptionsFail } = DashboardActions try { const { controlKey, requestParams, itemId } = action.payload const formedViews: IShareFormedViews = yield select(makeSelectFormedViews()) const requests = Object.entries(requestParams).map(([viewId, params]) => { const { columns, filters, variables, cache, expired } = params const { dataToken } = formedViews[viewId] return call(request, { method: 'post', url: `${api.share}/data/${dataToken}/distinctvalue`, data: { columns: Object.values(columns).filter((c) => !!c), filters, params: variables, cache, expired } }) }) const results: Array<IDavinciResponse<object[]>> = yield all(requests) yield put( selectOptionsLoaded( controlKey, results.reduce((arr, result) => arr.concat(result.payload), []), itemId ) ) } catch (err) { yield put(loadSelectOptionsFail(err)) } } export function* getDownloadList(action: DashboardActionType) { if (action.type !== ActionTypes.LOAD_DOWNLOAD_LIST) { return } const { downloadListLoaded, loadDownloadListFail } = DashboardActions const { shareClinetId, token } = action.payload const shareType = yield select(makeSelectShareType()) const baseUrl = `${api.download}/share/page/${shareClinetId}/${token}` const requestUrl = getPasswordUrl(shareType, token, baseUrl) try { const result = yield call(request, requestUrl) yield put(downloadListLoaded(result.payload)) } catch (err) { yield put(loadDownloadListFail(err)) errorHandler(err) } } export function* downloadFile(action: DashboardActionType) { if (action.type !== ActionTypes.DOWNLOAD_FILE) { return } const { fileDownloaded, downloadFileFail } = DashboardActions const { id, shareClinetId, token } = action.payload try { location.href = `${api.download}/share/record/file/${id}/${shareClinetId}/${token}` yield put(fileDownloaded(id)) } catch (err) { yield put(downloadFileFail(err)) errorHandler(err) } } export function* initiateDownloadTask(action: DashboardActionType) { if (action.type !== ActionTypes.INITIATE_DOWNLOAD_TASK) { return } const { DownloadTaskInitiated, initiateDownloadTaskFail } = DashboardActions const { shareClientId, itemId } = action.payload const currentDashboard: IDashboard = yield select(makeSelectDashboard()) const currentItems: IDashboardItem[] = yield select(makeSelectItems()) const currentDashboardFilters = currentDashboard?.config.filters || [] const formedViews: IShareFormedViews = yield select(makeSelectFormedViews()) const globalControlFormValues = yield select( makeSelectGlobalControlPanelFormValues() ) const globalControlConditionsByItem: IGlobalControlConditionsByItem = getCurrentControlValues( ControlPanelTypes.Global, currentDashboardFilters, formedViews, globalControlFormValues, null, currentItems ) const itemInfo: IShareDashboardItemInfo = yield select((state) => makeSelectItemInfo()(state, itemId) ) const relatedWidget: IWidgetFormed = yield select((state) => makeSelectItemRelatedWidget()(state, itemId) ) const localControlFormValues = yield select((state) => makeSelectLocalControlPanelFormValues()(state, itemId) ) const localControlConditions = getCurrentControlValues( ControlPanelTypes.Local, relatedWidget.config.controls, formedViews, localControlFormValues ) const requestParams = getRequestParams( relatedWidget, itemInfo.queryConditions, false, { ...globalControlConditionsByItem[itemId], ...localControlConditions } ) const { dataToken } = relatedWidget try { yield call(request, { method: 'POST', url: `${api.download}/share/submit/${DownloadTypes.Widget}/${shareClientId}/${dataToken}`, data: [ { id: relatedWidget.id, param: { ...getRequestBody(requestParams), flush: true, pageNo: 0, pageSize: 0 } } ] }) message.success('下载任务创建成功!') yield put(DownloadTaskInitiated(itemId)) } catch (err) { yield put(initiateDownloadTaskFail(err, itemId)) errorHandler(err) } } export default function* rootDashboardSaga() { yield all([ takeLatest(ActionTypes.LOAD_SHARE_DASHBOARD, getDashboard), takeEvery(ActionTypes.LOAD_SHARE_WIDGET, getWidget), takeEvery(ActionTypes.LOAD_SHARE_RESULTSET, getResultset), takeEvery( ActionTypes.LOAD_BATCH_DATA_WITH_CONTROL_VALUES, getBatchDataWithControlValues ), takeLatest(ActionTypes.LOAD_WIDGET_CSV, getWidgetCsv), takeEvery(ActionTypes.LOAD_SELECT_OPTIONS, getSelectOptions), takeLatest(ActionTypes.LOAD_DOWNLOAD_LIST, getDownloadList), takeLatest(ActionTypes.DOWNLOAD_FILE, downloadFile), takeEvery(ActionTypes.INITIATE_DOWNLOAD_TASK, initiateDownloadTask) ]) }
the_stack
/// <reference types="node" /> declare var rpio: Rpio; declare module 'rpio' { export = rpio; } interface Rpio { /** * Initialise the bcm2835 library. This will be called automatically by .open() using the default option values if not called explicitly. * @param options */ init(options: RPIO.Options): void; /** * Open a pin for input or output. Valid modes are: * INPUT: pin is input (read-only). * OUTPUT: pin is output (read-write). * PWM: configure pin for hardware PWM. * * For input pins, option can be used to configure the internal pullup or pulldown resistors using options as described in the .pud() documentation below. * * For output pins, option defines the initial isMotionDetected of the pin, rather than having to issue a separate .write() call. This can be critical for devices which must have a stable value, rather than relying on the initial floating value when a pin is enabled for output but hasn't yet been configured with a value. * @param pin * @param mode * @param options */ open(pin: number, mode: number, options?: number): void; /** * Switch a pin that has already been opened in one mode to a different mode. * This is provided primarily for performance reasons, as it avoids some of the setup work done by .open(). * @param pin * @param mode */ mode(pin: number, mode: number): void; /** * Read the current value of pin, returning either 1 (high) or 0 (low). * @param pin */ read(pin: number): number; /** * Read length bits from pin into buffer as fast as possible. If length isn't specified it defaults to buffer.length. * @param pin * @param buffer * @param length */ readbuf(pin: number, buffer: Buffer, length?: number): void; /** * Set the specified pin either high or low, using either the HIGH/LOW constants, or simply 1 or 0. * @param pin * @param value */ write(pin: number, value: number): void; /** * Write length bits to pin from buffer as fast as possible. If length isn't specified it defaults to buffer.length. * @param pin * @param buffer * @param length */ writebuf(pin: number, buffer: Buffer, length?: number): void; /** * Read the current isMotionDetected of the GPIO pad control for the specified GPIO group. On current models of Raspberry Pi there are three groups with corresponding defines: * PAD_GROUP_0_27: GPIO0 - GPIO27. Use this for the main GPIO header. * PAD_GROUP_28_45: GPIO28 - GPIO45. Use this to configure the P5 header. * PAD_GROUP_46_53: GPIO46 - GPIO53. Internal, you probably won't need this. * * The value returned will be a bit mask of the following defines: * PAD_SLEW_UNLIMITED: 0x10. Slew rate unlimited if set. * PAD_HYSTERESIS: 0x08. Hysteresis is enabled if set. * * The bottom three bits determine the drive current: * PAD_DRIVE_2mA: 0b000 * PAD_DRIVE_4mA: 0b001 * PAD_DRIVE_6mA: 0b010 * PAD_DRIVE_8mA: 0b011 * PAD_DRIVE_10mA: 0b100 * PAD_DRIVE_12mA: 0b101 * PAD_DRIVE_14mA: 0b110 * PAD_DRIVE_16mA: 0b111 * * @note Note that the pad control registers are not available via /dev/gpiomem, so you will need to use .init({gpiomem: false}) and run as root. * @param group */ readpad(group: number): number; /** * Write control settings to the pad control for group. Uses the same defines as above for .readpad(). * @param group * @param control */ writepad(group: number, control: number): void; /** * Configure the pin's internal pullup or pulldown resistors, using the following isMotionDetected constants: * PULL_OFF: disable configured resistors. * PULL_DOWN: enable the pulldown resistor. * PULL_UP: enable the pullup resistor. * * @param pin * @param state */ pud(pin: number, state: number): void; /** * Watch pin for changes and execute the callback cb() on events. cb() takes a single argument, the pin which triggered the callback. * * The optional direction argument can be used to watch for specific events: * POLL_LOW: poll for falling edge transitions to low. * POLL_HIGH: poll for rising edge transitions to high. * POLL_BOTH: poll for both transitions (the default). * * Due to hardware/kernel limitations we can only poll for changes, and the event detection only says that an event occurred, not which one. The poll interval is a 1ms setInterval() and transitions could come in between detecting the event and reading the value. Therefore this interface is only useful for events which transition slower than approximately 1kHz. * * To stop watching for pin changes, call .poll() again, setting the callback to null. * @param pin * @param cb * @param direction */ poll(pin: number, cb: RPIO.CallbackFunction | null, direction?: number): void; /** * Reset pin to INPUT and clear any pullup/pulldown resistors and poll events. * @param pin */ close(pin: number): void; // I²C /** * Assign pins 3 and 5 to i²c use. Until .i2cEnd() is called they won't be available for GPIO use. * * The pin assignments are: * Pin 3: SDA (Serial Data) * Pin 5: SCL (Serial Clock) */ i2cBegin(): void; /** * Configure the slave address. This is between 0 - 0x7f, and it can be helpful to * run the i2cdetect program to figure out where your devices are if you are unsure. * @param address */ i2cSetSlaveAddress(address: number): void; /** * Set the baud rate - directly set the speed in hertz. * @param baudRate */ i2cSetBaudRate(baudRate: number): void; /** * Read from the i²c slave. * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. * @param buffer * @param length */ i2cRead(buffer: Buffer, length?: number): void; /** * Write to the i²c slave. * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. * @param biffer * @param length */ i2cWrite(biffer: Buffer, length?: number): void; /** * Set the baud rate - based on a divisor of the base 250MHz rate. * @param clockDivider */ i2cSetClockDivider(clockDivider: number): void; /** * Turn off the i²c interface and return the pins to GPIO. */ i2cEnd(): void; // PWM /** * Set the PWM refresh rate. * @param clockDivider: power-of-two divisor of the base 19.2MHz rate, with a maximum value of 4096 (4.6875kHz). */ pwmSetClockDivider(clockDivider: number): void; /** * Set the PWM range for a pin. This determines the maximum pulse width. * @param pin * @param range */ pwmSetRange(pin: number, range: number): void; /** * Set the PWM width for a pin. * @param pin * @param data */ pwmSetData(pin: number, data: number): void; // SPI /** * Switch pins 119, 21, 23, 24 and 25 (GPIO7-GPIO11) to SPI mode * * Pin | Function * -----|---------- * 19 | MOSI * 21 | MISO * 23 | SCLK * 24 | CE0 * 25 | CE1 */ spiBegin(): void; /** * Choose which of the chip select / chip enable pins to control. * * Value | Pin * ------|--------------------- * 0 | SPI_CE0 (24 / GPIO8) * 1 | SPI_CE1 (25 / GPIO7) * 2 | Both * * @param chip */ spiChipSelect(cePin: number): void; /** * Commonly chip enable (CE) pins are active low, and this is the default. * If your device's CE pin is active high, use spiSetCSPolarity() to change the polarity. * @param cePin * @param polarity */ spiSetCSPolarity(cePin: number, polarity: number): void; /** * Set the SPI clock speed with. * @param clockDivider: an even divisor of the base 250MHz rate ranging between 0 and 65536. */ spiSetClockDivider(clockDivider: number): void; /** * Transfer data. Data is sent and received in 8-bit chunks via buffers which should be the same size. * @param txBuffer * @param rxBuffer * @param txLength */ spiTransfer(txBuffer: Buffer, rxBuffer: Buffer, txLength: number): void; /** * Send data and do not care about the data coming back. * @param txBuffer * @param txLength */ spiWrite(txBuffer: Buffer, txLength: number): void; /** * Release the pins back to general purpose use. */ spiEnd(): void; // Misc /** * Sleep for n seconds. * @param n: number of seconds to sleep */ sleep(n: number): void; /** * Sleep for n milliseconds. * @param n: number of milliseconds to sleep */ msleep(n: number): void; /** * Sleep for n microseconds. * @param n: number of microseconds to sleep */ usleep(n: number): void; // Constants: HIGH: number; LOW: number; INPUT: number; OUTPUT: number; PWM: number; PULL_OFF: number; PULL_DOWN: number; PULL_UP: number; PAD_GROUP_0_27: number; PAD_GROUP_28_45: number; PAD_GROUP_46_53: number; PAD_SLEW_UNLIMITED: number; PAD_HYSTERESIS: number; PAD_DRIVE_2mA: number; PAD_DRIVE_4mA: number; PAD_DRIVE_6mA: number; PAD_DRIVE_8mA: number; PAD_DRIVE_10mA: number; PAD_DRIVE_12mA: number; PAD_DRIVE_14mA: number; PAD_DRIVE_16mA: number; POLL_LOW: number; POLL_HIGH: number; POLL_BOTH: number; } declare namespace RPIO { interface Options { /** * There are two device nodes for GPIO access. The default is /dev/gpiomem which, when configured with gpio group access, allows users in that group to read/write directly to that device. This removes the need to run as root, but is limited to GPIO functions. * For non-GPIO functions (i²c, PWM, SPI) the /dev/mem device is required for full access to the Broadcom peripheral address range and the program needs to be executed as the root user (e.g. via sudo). If you do not explicitly call .init() when using those functions, the library will do it for you with gpiomem: false. * You may also need to use gpiomem: false if you are running on an older Linux kernel which does not support the gpiomem module. * rpio will throw an exception if you try to use one of the non-GPIO functions after already opening with /dev/gpiomem, as well as checking to see if you have the necessary permissions. * * Valid options: * true: use /dev/gpiomem for non-root but GPIO-only access * false: use /dev/mem for full access but requires root */ gpiomem?: boolean; /** * There are two naming schemes when referring to GPIO pins: * By their physical header location: Pins 1 to 26 (A/B) or Pins 1 to 40 (A+/B+) * Using the Broadcom hardware map: GPIO 0-25 (B rev1), GPIO 2-27 (A/B rev2, A+/B+) * * Confusingly however, the Broadcom GPIO map changes between revisions, so for example P3 maps to GPIO0 on Model B Revision 1 models, but maps to GPIO2 on all later models. * This means the only sane default mapping is the physical layout, so that the same code will work on all models regardless of the underlying GPIO mapping. * If you prefer to use the Broadcom GPIO scheme for whatever reason (e.g. to use the P5 header pins on the Raspberry Pi 1 revision 2.0 model which aren't currently mapped to the physical layout), you can set mapping to gpio to switch to the GPIOxx naming. * * Valid options: * gpio: use the Broadcom GPIOxx naming * physical: use the physical P01-P40 header layou */ mapping?: "gpio" | "physical"; /** * Mock mode is a dry-run environment where everything except pin access is performed. This is useful for testing scripts, and can also be used on systems which do not support GPIO at all. * If rpio is executed on unsupported hardware it will automatically start up in mock mode, and a warn event is emitted. By default the warn event is handled by a simple logger to stdout, but this can be overridden by the user creating their own warn handler. * The user can also explicitly request mock mode, where the argument is the type of hardware they wish to emulate. */ mock?: "raspi-b-r1" | "raspi-a" | "raspi-b" | "raspi-a+" | "raspi-b+" | "raspi-2" | "raspi-3" | "raspi-zero" | "raspi-zero-w"; } interface CallbackFunction { /** * @param pin: The pin which triggered the callback. */ (pin: number): void; } }
the_stack
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of, forkJoin } from 'rxjs'; import * as Rx from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { FullDocNode, DocNode2, Doc2, Link, Change, Db } from './standard-map'; import { MessageService } from './message.service'; import * as d3Sankey from 'd3-sankey'; import { TreeNode, IActionMapping } from 'angular-tree-component'; import { GraphTab } from './GraphTab'; import { GraphFilter } from './GraphFilter'; export interface ICategory { id: string; title: string; active?: boolean; } export type CategoryList = ICategory[]; export class FilterCriteria { constructor( public categoryIds: string[] = null, public categoryOrder: string[] = null) { } } // -- Dag Node -- export interface SNodeExtra { nodeId: number; name: string; data?: any; } export interface SLinkExtra { source: number; target: number; value: number; uom: string; sourceNode: any; targetNode: any; } export type SNode = d3Sankey.SankeyNode<SNodeExtra, SLinkExtra>; export type SLink = d3Sankey.SankeyLink<SNodeExtra, SLinkExtra>; export interface DAG { nodes: SNode[]; links: SLink[]; } // -- Dag Node -- @Injectable({ providedIn: 'root' }) export class GraphService { private docGuids = {}; private docDb: Db = null; private docs = {}; private nextDocGuid = 0; private filterOrder = []; private runningFilters = false; public updateSubject = new Rx.BehaviorSubject(0); public updateViewSubject = new Rx.BehaviorSubject(0); public visualStyle = true; public visualZoom = 1; constructor( private messageService: MessageService, private http: HttpClient) { this.addTab("ISO"); } public runFilters(changedTab: GraphTab, parentChanged: boolean) { if (this.runningFilters) return; // prevent re-entry this.runningFilters = true; var tabs = this.graphTabs; var anyChanged = false; for (var i of this.filterOrder) { var t = tabs[i]; if (!t) continue; if (anyChanged || t.column.autoFilterSrc == changedTab.column || (parentChanged && t == changedTab)) { anyChanged = true; // filter child tree GraphFilter.runFilter(t.column); } } //if (anyChanged) this.updateSubject.next(0); this.runningFilters = false; } getGuid(id: string, type: string, rev: string, createMissing: boolean = true): number { var key = `${type}-${id}-${rev}`; if (key in this.docGuids) return this.docGuids[key]; if (!createMissing) return null; var value = this.nextDocGuid++; this.docGuids[key] = value; return value; } getDbIndex() : Observable<Db> { if (this.docDb) return of(this.docDb); return this.http.get<Db>('assets/output/docs-index.json', {responseType: 'json'}) .pipe( tap( data => { this.docDb = data; }, error => this.handleError("getDbIndex", []) ) ); } getDoc(id: string) : Observable<Doc2> { if (this.docs[id]) return of(this.docs[id]); return this.http.get<Doc2>('assets/output/docs-' + id + '.json', {responseType: 'json'}) .pipe( tap( data => { this.docs[id] = data; }, error => this.handleError("getDoc", []) ) ); } getDocTypes() : Observable<CategoryList> { return this.getDbIndex().pipe( map( data => { return data.docs.map(v => { return { id: v.id, title: v.type }; }); } ) ); } private addToDoc(parent: FullDocNode, input: DocNode2) { var child = new FullDocNode(input); if (parent) { parent.children.push(child); } // Recurse for (var c of input.children) { this.addToDoc(child, c); } return child; } getFullDocByType(id: string) : Observable<FullDocNode> { return this.getDoc(id).pipe( map( data => { return this.addToDoc(null, data); } ) ); } getChangeLog(): Observable<Change[]> { return this.getDbIndex().pipe( map( data => { return data.changelog; } ) ); } // Live state management: maybe move this to a different service. public graphTabs: GraphTab[] = [ ]; public selectedTab: number = 0; public get canAdd(): boolean { return this.graphTabs.length < 3; } public addTab(id: string) { if (!this.canAdd) return; this.getFullDocByType(id) .subscribe(doc => { var newTab = new GraphTab(this, null, doc); newTab.nodes = doc.children; newTab.column.nodes = doc.children; this.graphTabs.push(newTab); this.ensureISOIsInMiddle(); // Coverage calculation is disabled to save time. //if (id != "ISO") //{ // // compare with iso. // newTab.coverage = this.compareDocs(newTab.column, this.graphTabs[1]); //} var selectTab = newTab; if (newTab.isAll) { selectTab = this.graphTabs.find(t => t.isIso); } // The current request is to NOT activate the newly added tab. So only activate index 0 if (this.graphTabs.length != 1) { selectTab = this.graphTabs[this.selectedTab]; // reselect current selection } // even if we dont change tabs, we still have to reactive it to configure filters this.activateTab(selectTab); }); } private ensureISOIsInMiddle() { var isoTab = this.graphTabs.find(t => t.isIso); if (this.graphTabs.length > 1) { this.graphTabs = this.graphTabs.filter(t => t != isoTab); this.graphTabs.splice(1, 0, isoTab); } } public configureFilterStack() { switch (this.selectedTab) { case 0: this.filterOrder = [0, 1, 2]; break; case 1: this.filterOrder = [1, 0, 2]; break; case 2: this.filterOrder = [2, 1, 0]; break; } // setup filters var isoTab = this.graphTabs.find(t => t.isIso); var primary = this.graphTabs[this.filterOrder[0]]; if (!primary) return; // clear auto filter of left tab primary.column.autoFilterSrc = null; primary.column.autoFilterParent = null; primary.column.autoFilterSelf = false; var secondary = this.graphTabs[this.filterOrder[1]]; if (secondary) { if (secondary == isoTab) { // assure iso filters from the primary: "auto filter" isoTab.column.autoFilterSrc = primary.column; isoTab.column.autoFilterParent = primary.column.parent; isoTab.column.autoFilterSelf = false; } else { // auto filter with this tabs connections to iso secondary.column.autoFilterSrc = isoTab.column; secondary.column.autoFilterParent = primary.column.parent; // the primary tab always drives the selection secondary.column.autoFilterSelf = true; } } var third = this.graphTabs[this.filterOrder[2]]; if (third) { // auto filter with this tabs connections to iso third.column.autoFilterSrc = isoTab.column; third.column.autoFilterParent = primary.column.parent; // the primary tab always drives the selection third.column.autoFilterSelf = true; } } public tabChanged() { this.configureFilterStack(); if (this.selectedTab >= 0 && this.selectedTab < this.graphTabs.length) { this.graphTabs[this.selectedTab].parentTabTreeChanged(); } } public removeTab(tab) { this.graphTabs = this.graphTabs.filter(t => t!=tab); this.ensureISOIsInMiddle(); this.activateTab(this.graphTabs[0]); } public activateTab(tab: GraphTab): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { var newIndex = this.graphTabs.indexOf(tab); var finalize = () => { this.selectedTab = newIndex; this.tabChanged(); setTimeout(() => { resolve(true); }, 1000); }; // if the index is the same this.selectedTab = -1; // set it to non-value so change is detected setTimeout(finalize, 1000); // give dom time to stabilize }); } public getNodesWithLinks(children: FullDocNode[], result: FullDocNode[]) { for (var c of children) { if (c.node.links && c.node.links.length > 0) result.push(c); this.getNodesWithLinks(c.children, result); } return result; } public flattenSections(children: FullDocNode[], result: string[]) { for (var c of children) { if (c.getBody()) result.push(c.id); this.flattenSections(c.children, result); } return result; } public flattenLinks(children: FullDocNode[], result: Link[], linkData: any) { for (var c of children) { if (c.shouldBeMapped) { linkData.total++; if (!c.isUnmapped) { linkData.linked++; result = result.concat(c.node.links); } } result = this.flattenLinks(c.children, result, linkData); } return result; } public compareDocs(aTab: GraphTab, bTab: GraphTab): any { var bSections = []; this.flattenSections(bTab.nodes, bSections); var bCopy = bSections.slice(); var linkData = { total: 0, linked: 0 }; var aLinks = this.flattenLinks(aTab.nodes, [], linkData); var found = 0; var checked = 0; for (var a of aLinks) { ++checked; var b = bCopy.find(x => x == a.id) if (b) { bCopy = bCopy.filter(x => x != b); ++found; } } return { coverage: found + "/" + bSections.length, mapped: linkData.linked + "/" + linkData.total, uniqueconnections: found + "/" + checked, uncoveredIds: bCopy //"coverage": (found / bSections.length * 100).toFixed(1) + "% (" + found + "/" + bSections.length + ")", //"mapped": (linkData.linked / linkData.total * 100).toFixed(1) + "% (" + linkData.linked + "/" + linkData.total + ")", //"uniqueconnections": (found / checked * 100).toFixed(1) + "% (" + found + "/" + checked + ")" }; } /** * Handle Http operation that failed. * Let the app continue. * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } /** Log a GraphService message with the MessageService */ private log(message: string) { this.messageService.add(`GraphService: ${message}`); } public get errorStrings(): string[] { return this.graphTabs.reduce((a: string[], v: GraphTab) => { a.concat(v.errors()); return a; }, []); } public get anyErrors(): boolean { for (var t of this.graphTabs) if (t.anyErrors) return true; return false; } }
the_stack
import { jsx } from '@emotion/react' import React from 'react' import * as EP from '../../../core/shared/element-path' import Utils from '../../../utils/utils' import { CanvasPoint } from '../../../core/shared/math-utils' import { EditorDispatch } from '../../editor/action-types' import { DerivedState, EditorState, getMetadata, EditorStore, getOpenUIJSFileKey, TransientCanvasState, TransientFilesState, ResizeOptions, } from '../../editor/store/editor-state' import { ElementPath, NodeModules } from '../../../core/shared/project-file-types' import { CanvasPositions, CSSCursor } from '../canvas-types' import { SelectModeControlContainer } from './select-mode-control-container' import { InsertModeControlContainer } from './insert-mode-control-container' import { HighlightControl } from './highlight-control' import { useEditorState, useRefEditorState } from '../../editor/store/store-hook' import { ElementInstanceMetadataMap, UtopiaJSXComponent, } from '../../../core/shared/element-template' import { MetadataUtils } from '../../../core/model/element-metadata-utils' import { isAspectRatioLockedNew } from '../../aspect-ratio' import { ElementContextMenu } from '../../element-context-menu' import { isLiveMode, EditorModes, isSelectLiteMode } from '../../editor/editor-modes' import { DropTargetHookSpec, ConnectableElement, useDrop } from 'react-dnd' import { FileBrowserItemProps } from '../../filebrowser/fileitem' import { forceNotNull } from '../../../core/shared/optional-utils' import { flatMapArray } from '../../../core/shared/array-utils' import { targetRespectsLayout } from '../../../core/layout/layout-helpers' import { createSelector } from 'reselect' import { PropertyControlsInfo, ResolveFn } from '../../custom-code/code-file' import { useColorTheme } from '../../../uuiui' import { isDragging, isResizing, pickSelectionEnabled, useMaybeHighlightElement, useSelectAndHover, useStartDragStateAfterDragExceedsThreshold, } from './select-mode/select-mode-hooks' import { NO_OP } from '../../../core/shared/utils' import { usePropControlledStateV2 } from '../../inspector/common/inspector-utils' import { ProjectContentTreeRoot } from '../../assets' import { LayoutParentControl } from './layout-parent-control' import { when } from '../../../utils/react-conditionals' import { isFeatureEnabled } from '../../../utils/feature-switches' import { shallowEqual } from '../../../core/shared/equality-utils' import { KeysPressed } from '../../../utils/keyboard' import { usePrevious } from '../../editor/hook-utils' import { LayoutTargetableProp } from '../../../core/layout/layout-helpers-new' import { getDragStateStart } from '../canvas-utils' export const CanvasControlsContainerID = 'new-canvas-controls-container' export type ResizeStatus = 'disabled' | 'noninteractive' | 'enabled' function useLocalSelectedHighlightedViews( transientCanvasState: TransientCanvasState, ): { localSelectedViews: ElementPath[] localHighlightedViews: ElementPath[] setSelectedViewsLocally: (newSelectedViews: Array<ElementPath>) => void } { const [localSelectedViews, setLocalSelectedViews] = usePropControlledStateV2( transientCanvasState.selectedViews, ) const [localHighlightedViews, setLocalHighlightedViews] = usePropControlledStateV2( transientCanvasState.highlightedViews, ) const setSelectedViewsLocally = React.useCallback( (newSelectedViews: Array<ElementPath>) => { setLocalSelectedViews(newSelectedViews) setLocalHighlightedViews([]) }, [setLocalSelectedViews, setLocalHighlightedViews], ) return { localSelectedViews, localHighlightedViews, setSelectedViewsLocally } } export interface ControlProps { selectedViews: Array<ElementPath> highlightedViews: Array<ElementPath> componentMetadata: ElementInstanceMetadataMap projectContents: ProjectContentTreeRoot nodeModules: NodeModules openFile: string | null hiddenInstances: Array<ElementPath> focusedElementPath: ElementPath | null highlightsEnabled: boolean canvasOffset: CanvasPoint scale: number dispatch: EditorDispatch resizeStatus: ResizeStatus elementAspectRatioLocked: boolean imageMultiplier: number | null windowToCanvasPosition: (event: MouseEvent) => CanvasPositions cmdKeyPressed: boolean showAdditionalControls: boolean maybeClearHighlightsOnHoverEnd: () => void transientState: TransientCanvasState resolve: ResolveFn resizeOptions: ResizeOptions } interface NewCanvasControlsProps { windowToCanvasPosition: (event: MouseEvent) => CanvasPositions cursor: CSSCursor } export const NewCanvasControls = React.memo((props: NewCanvasControlsProps) => { const canvasControlProps = useEditorState( (store) => ({ dispatch: store.dispatch, editor: store.editor, derived: store.derived, canvasOffset: store.editor.canvas.roundedCanvasOffset, animationEnabled: (store.editor.canvas.dragState == null || getDragStateStart(store.editor.canvas.dragState, store.editor.canvas.resizeOptions) == null) && store.editor.canvas.animationsEnabled, controls: store.derived.canvas.controls, scale: store.editor.canvas.scale, focusedPanel: store.editor.focusedPanel, transientCanvasState: store.derived.canvas.transientState, }), 'NewCanvasControls', ) const { localSelectedViews, localHighlightedViews, setSelectedViewsLocally, } = useLocalSelectedHighlightedViews(canvasControlProps.transientCanvasState) const canvasScrollAnimation = useEditorState( (store) => store.editor.canvas.scrollAnimation, 'NewCanvasControls scrollAnimation', ) // Somehow this being setup and hooked into the div makes the `onDrop` call // work properly in `editor-canvas.ts`. I blame React DnD for this. const dropSpec: DropTargetHookSpec<FileBrowserItemProps, 'CANVAS', unknown> = { accept: 'filebrowser', canDrop: () => true, } const [_, drop] = useDrop(dropSpec) const forwardedRef = React.useCallback( (node: ConnectableElement) => { return drop(node) }, [drop], ) if (isLiveMode(canvasControlProps.editor.mode) && !canvasControlProps.editor.keysPressed.cmd) { return null } else { return ( <div key='canvas-controls' ref={forwardedRef} className={ canvasControlProps.focusedPanel === 'canvas' ? ' canvas-controls focused ' : ' canvas-controls ' } id='canvas-controls' style={{ pointerEvents: 'initial', position: 'absolute', top: 0, left: 0, transform: 'translate3d(0, 0, 0)', width: `100%`, height: `100%`, zoom: canvasControlProps.scale >= 1 ? `${canvasControlProps.scale * 100}%` : 1, cursor: props.cursor, visibility: canvasScrollAnimation ? 'hidden' : 'initial', }} > <div style={{ position: 'absolute', top: 0, left: 0, width: `${canvasControlProps.scale < 1 ? 100 / canvasControlProps.scale : 100}%`, height: `${canvasControlProps.scale < 1 ? 100 / canvasControlProps.scale : 100}%`, transformOrigin: 'top left', transform: canvasControlProps.scale < 1 ? `scale(${canvasControlProps.scale}) ` : '', }} > <NewCanvasControlsInner windowToCanvasPosition={props.windowToCanvasPosition} localSelectedViews={localSelectedViews} localHighlightedViews={localHighlightedViews} setLocalSelectedViews={setSelectedViewsLocally} {...canvasControlProps} /> </div> <ElementContextMenu contextMenuInstance='context-menu-canvas' /> </div> ) } }) NewCanvasControls.displayName = 'NewCanvasControls' interface NewCanvasControlsInnerProps { editor: EditorState derived: DerivedState dispatch: EditorDispatch canvasOffset: CanvasPoint animationEnabled: boolean windowToCanvasPosition: (event: MouseEvent) => CanvasPositions localSelectedViews: Array<ElementPath> localHighlightedViews: Array<ElementPath> setLocalSelectedViews: (newSelectedViews: ElementPath[]) => void } const NewCanvasControlsInner = (props: NewCanvasControlsInnerProps) => { const colorTheme = useColorTheme() const startDragStateAfterDragExceedsThreshold = useStartDragStateAfterDragExceedsThreshold() const { localSelectedViews, localHighlightedViews, setLocalSelectedViews } = props const cmdKeyPressed = props.editor.keysPressed['cmd'] ?? false const componentMetadata = getMetadata(props.editor) const resizing = isResizing(props.editor) const dragging = isDragging(props.editor) const selectionEnabled = pickSelectionEnabled(props.editor.canvas, props.editor.keysPressed) const draggingEnabled = !isSelectLiteMode(props.editor.mode) const contextMenuEnabled = !isLiveMode(props.editor.mode) const { maybeHighlightOnHover, maybeClearHighlightsOnHoverEnd } = useMaybeHighlightElement() const { onMouseMove, onMouseDown } = useSelectAndHover(cmdKeyPressed, setLocalSelectedViews) const getResizeStatus = () => { const selectedViews = localSelectedViews if (props.editor.canvas.textEditor != null || props.editor.keysPressed['z']) { return 'disabled' } if (cmdKeyPressed) { return 'noninteractive' } const anyIncomprehensibleElementsSelected = selectedViews.some((selectedView) => { const possibleMetadata = MetadataUtils.findElementByElementPath( componentMetadata, selectedView, ) return possibleMetadata == null }) if (anyIncomprehensibleElementsSelected) { return 'disabled' } return 'enabled' } const renderModeControlContainer = () => { const elementAspectRatioLocked = localSelectedViews.every((target) => { const possibleElement = MetadataUtils.findElementByElementPath(componentMetadata, target) if (possibleElement == null) { return false } else { return isAspectRatioLockedNew(possibleElement) } }) const imageMultiplier: number | null = MetadataUtils.getImageMultiplier( componentMetadata, localSelectedViews, ) const resolveFn = props.editor.codeResultCache.curriedResolveFn(props.editor.projectContents) const controlProps: ControlProps = { selectedViews: localSelectedViews, highlightedViews: localHighlightedViews, componentMetadata: componentMetadata, hiddenInstances: props.editor.hiddenInstances, focusedElementPath: props.editor.focusedElementPath, highlightsEnabled: props.editor.canvas.highlightsEnabled, canvasOffset: props.canvasOffset, scale: props.editor.canvas.scale, dispatch: props.dispatch, resizeStatus: getResizeStatus(), elementAspectRatioLocked: elementAspectRatioLocked, imageMultiplier: imageMultiplier, windowToCanvasPosition: props.windowToCanvasPosition, cmdKeyPressed: cmdKeyPressed, showAdditionalControls: props.editor.interfaceDesigner.additionalControls, maybeClearHighlightsOnHoverEnd: maybeClearHighlightsOnHoverEnd, projectContents: props.editor.projectContents, nodeModules: props.editor.nodeModules.files, openFile: props.editor.canvas.openFile?.filename ?? null, transientState: props.derived.canvas.transientState, resolve: resolveFn, resizeOptions: props.editor.canvas.resizeOptions, } const dragState = props.editor.canvas.dragState switch (props.editor.mode.type) { case 'select': case 'select-lite': case 'live': { return ( <SelectModeControlContainer {...controlProps} startDragStateAfterDragExceedsThreshold={startDragStateAfterDragExceedsThreshold} setSelectedViewsLocally={setLocalSelectedViews} keysPressed={props.editor.keysPressed} windowToCanvasPosition={props.windowToCanvasPosition} isDragging={dragging} isResizing={resizing} selectionEnabled={selectionEnabled} draggingEnabled={draggingEnabled} contextMenuEnabled={contextMenuEnabled} maybeHighlightOnHover={maybeHighlightOnHover} maybeClearHighlightsOnHoverEnd={maybeClearHighlightsOnHoverEnd} duplicationState={props.editor.canvas.duplicationState} dragState={ dragState?.type === 'MOVE_DRAG_STATE' || dragState?.type === 'RESIZE_DRAG_STATE' ? dragState : null } showAdditionalControls={props.editor.interfaceDesigner.additionalControls} /> ) } case 'insert': { return ( <InsertModeControlContainer {...controlProps} mode={props.editor.mode} keysPressed={props.editor.keysPressed} windowToCanvasPosition={props.windowToCanvasPosition} dragState={ dragState != null && dragState.type === 'INSERT_DRAG_STATE' ? dragState : null } canvasOffset={props.editor.canvas.realCanvasOffset /* maybe roundedCanvasOffset? */} scale={props.editor.canvas.scale} /> ) } default: { const _exhaustiveCheck: never = props.editor.mode throw new Error(`Unhandled editor mode ${JSON.stringify(props.editor.mode)}`) } } } const renderHighlightControls = () => { return selectionEnabled ? localHighlightedViews.map((path) => { const frame = MetadataUtils.getFrameInCanvasCoords(path, componentMetadata) if (frame == null) { return null } const isFocusableComponent = MetadataUtils.isFocusableComponent(path, componentMetadata) const isFocusedComponent = EP.isFocused(props.editor.focusedElementPath, path) const color = isFocusableComponent || isFocusedComponent ? colorTheme.canvasSelectionIsolatedComponent.value : colorTheme.canvasSelectionPrimaryOutline.value return ( <HighlightControl key={`highlight-control-${EP.toComponentId(path)}`} color={color} frame={frame} scale={props.editor.canvas.scale} canvasOffset={props.canvasOffset} /> ) }) : [] } return ( <div id={CanvasControlsContainerID} data-testid={CanvasControlsContainerID} className='new-canvas-controls-container' style={{ pointerEvents: 'initial', position: 'relative', width: '100%', height: '100%', }} onMouseDown={onMouseDown} onMouseMove={onMouseMove} > {renderModeControlContainer()} {renderHighlightControls()} <LayoutParentControl /> </div> ) }
the_stack
import { NgModule, SecurityContext } from '@angular/core'; import { CommonModule, DatePipe } from '@angular/common'; import { FooterComponent } from '@shared/components/footer.component'; import { LogoComponent } from '@shared/components/logo.component'; import { TbSnackBarComponent, ToastDirective } from '@shared/components/toast.directive'; import { BreadcrumbComponent } from '@shared/components/breadcrumb.component'; import { FlowInjectionToken, NgxFlowModule } from '@flowjs/ngx-flow'; import { NgxFlowchartModule } from 'ngx-flowchart'; import Flow from '@flowjs/flow.js'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatChipsModule } from '@angular/material/chips'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatDialogModule } from '@angular/material/dialog'; import { MatDividerModule } from '@angular/material/divider'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatGridListModule } from '@angular/material/grid-list'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatMenuModule } from '@angular/material/menu'; import { MatPaginatorModule } from '@angular/material/paginator'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatRadioModule } from '@angular/material/radio'; import { MatSelectModule } from '@angular/material/select'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatSliderModule } from '@angular/material/slider'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSortModule } from '@angular/material/sort'; import { MatStepperModule } from '@angular/material/stepper'; import { MatTableModule } from '@angular/material/table'; import { MatTabsModule } from '@angular/material/tabs'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatTooltipModule } from '@angular/material/tooltip'; import { MatListModule } from '@angular/material/list'; import { MatDatetimepickerModule, MatNativeDatetimeModule } from '@mat-datetimepicker/core'; import { NgxDaterangepickerMd } from 'ngx-daterangepicker-material'; import { GridsterModule } from 'angular-gridster2'; import { FlexLayoutModule } from '@angular/flex-layout'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { ShareModule as ShareButtonsModule } from 'ngx-sharebuttons'; import { HotkeyModule } from 'angular2-hotkeys'; import { ColorPickerModule } from 'ngx-color-picker'; import { NgxHmCarouselModule } from 'ngx-hm-carousel'; import { UserMenuComponent } from '@shared/components/user-menu.component'; import { NospacePipe } from '@shared/pipe/nospace.pipe'; import { TranslateModule } from '@ngx-translate/core'; import { TbCheckboxComponent } from '@shared/components/tb-checkbox.component'; import { HelpComponent } from '@shared/components/help.component'; import { TbAnchorComponent } from '@shared/components/tb-anchor.component'; import { MillisecondsToTimeStringPipe } from '@shared/pipe/milliseconds-to-time-string.pipe'; import { TimewindowComponent } from '@shared/components/time/timewindow.component'; import { OverlayModule } from '@angular/cdk/overlay'; import { TimewindowPanelComponent } from '@shared/components/time/timewindow-panel.component'; import { TimeintervalComponent } from '@shared/components/time/timeinterval.component'; import { DatetimePeriodComponent } from '@shared/components/time/datetime-period.component'; import { EnumToArrayPipe } from '@shared/pipe/enum-to-array.pipe'; import { ClipboardModule } from 'ngx-clipboard'; import { ValueInputComponent } from '@shared/components/value-input.component'; import { MarkdownModule, MarkedOptions } from 'ngx-markdown'; import { FullscreenDirective } from '@shared/components/fullscreen.directive'; import { HighlightPipe } from '@shared/pipe/highlight.pipe'; import { DashboardAutocompleteComponent } from '@shared/components/dashboard-autocomplete.component'; import { EntitySubTypeAutocompleteComponent } from '@shared/components/entity/entity-subtype-autocomplete.component'; import { EntitySubTypeSelectComponent } from '@shared/components/entity/entity-subtype-select.component'; import { EntityAutocompleteComponent } from '@shared/components/entity/entity-autocomplete.component'; import { EntityListComponent } from '@shared/components/entity/entity-list.component'; import { EntityTypeSelectComponent } from '@shared/components/entity/entity-type-select.component'; import { EntitySelectComponent } from '@shared/components/entity/entity-select.component'; import { DatetimeComponent } from '@shared/components/time/datetime.component'; import { EntityKeysListComponent } from '@shared/components/entity/entity-keys-list.component'; import { SocialSharePanelComponent } from '@shared/components/socialshare-panel.component'; import { RelationTypeAutocompleteComponent } from '@shared/components/relation/relation-type-autocomplete.component'; import { EntityListSelectComponent } from '@shared/components/entity/entity-list-select.component'; import { JsonObjectEditComponent } from '@shared/components/json-object-edit.component'; import { FooterFabButtonsComponent } from '@shared/components/footer-fab-buttons.component'; import { CircularProgressDirective } from '@shared/components/circular-progress.directive'; import { FabActionsDirective, FabToolbarComponent, FabTriggerDirective } from '@shared/components/fab-toolbar.component'; import { DashboardSelectPanelComponent } from '@shared/components/dashboard-select-panel.component'; import { DashboardSelectComponent } from '@shared/components/dashboard-select.component'; import { WidgetsBundleSelectComponent } from '@shared/components/widgets-bundle-select.component'; import { KeyboardShortcutPipe } from '@shared/pipe/keyboard-shortcut.pipe'; import { TbErrorComponent } from '@shared/components/tb-error.component'; import { EntityTypeListComponent } from '@shared/components/entity/entity-type-list.component'; import { EntitySubTypeListComponent } from '@shared/components/entity/entity-subtype-list.component'; import { TruncatePipe } from '@shared/pipe/truncate.pipe'; import { TbJsonPipe } from '@shared/pipe/tbJson.pipe'; import { ColorPickerDialogComponent } from '@shared/components/dialog/color-picker-dialog.component'; import { MatChipDraggableDirective } from '@shared/components/mat-chip-draggable.directive'; import { ColorInputComponent } from '@shared/components/color-input.component'; import { JsFuncComponent } from '@shared/components/js-func.component'; import { JsonFormComponent } from '@shared/components/json-form/json-form.component'; import { ConfirmDialogComponent } from '@shared/components/dialog/confirm-dialog.component'; import { AlertDialogComponent } from '@shared/components/dialog/alert-dialog.component'; import { TodoDialogComponent } from '@shared/components/dialog/todo-dialog.component'; import { MaterialIconsDialogComponent } from '@shared/components/dialog/material-icons-dialog.component'; import { MaterialIconSelectComponent } from '@shared/components/material-icon-select.component'; import { ImageInputComponent } from '@shared/components/image-input.component'; import { FileInputComponent } from '@shared/components/file-input.component'; import { NodeScriptTestDialogComponent } from '@shared/components/dialog/node-script-test-dialog.component'; import { MessageTypeAutocompleteComponent } from '@shared/components/message-type-autocomplete.component'; import { JsonContentComponent } from '@shared/components/json-content.component'; import { KeyValMapComponent } from '@shared/components/kv-map.component'; import { TbCheatSheetComponent } from '@shared/components/cheatsheet.component'; import { TbHotkeysDirective } from '@shared/components/hotkeys.directive'; import { NavTreeComponent } from '@shared/components/nav-tree.component'; import { LedLightComponent } from '@shared/components/led-light.component'; import { TbJsonToStringDirective } from '@shared/components/directives/tb-json-to-string.directive'; import { JsonObjectEditDialogComponent } from '@shared/components/dialog/json-object-edit-dialog.component'; import { HistorySelectorComponent } from '@shared/components/time/history-selector/history-selector.component'; import { EntityGatewaySelectComponent } from '@shared/components/entity/entity-gateway-select.component'; import { DndModule } from 'ngx-drag-drop'; import { QueueTypeListComponent } from '@shared/components/queue/queue-type-list.component'; import { ContactComponent } from '@shared/components/contact.component'; import { TimezoneSelectComponent } from '@shared/components/time/timezone-select.component'; import { FileSizePipe } from '@shared/pipe/file-size.pipe'; import { WidgetsBundleSearchComponent } from '@shared/components/widgets-bundle-search.component'; import { SelectableColumnsPipe } from '@shared/pipe/selectable-columns.pipe'; import { QuickTimeIntervalComponent } from '@shared/components/time/quick-time-interval.component'; import { OtaPackageAutocompleteComponent } from '@shared/components/ota-package/ota-package-autocomplete.component'; import { MAT_DATE_LOCALE } from '@angular/material/core'; import { CopyButtonComponent } from '@shared/components/button/copy-button.component'; import { TogglePasswordComponent } from '@shared/components/button/toggle-password.component'; import { HelpPopupComponent } from '@shared/components/help-popup.component'; import { TbPopoverComponent, TbPopoverDirective } from '@shared/components/popover.component'; import { TbStringTemplateOutletDirective } from '@shared/components/directives/sring-template-outlet.directive'; import { TbComponentOutletDirective} from '@shared/components/directives/component-outlet.directive'; import { HelpMarkdownComponent } from '@shared/components/help-markdown.component'; import { MarkedOptionsService } from '@shared/components/marked-options.service'; import { TbPopoverService } from '@shared/components/popover.service'; import { HELP_MARKDOWN_COMPONENT_TOKEN, SHARED_MODULE_TOKEN } from '@shared/components/tokens'; import { TbMarkdownComponent } from '@shared/components/markdown.component'; import { ProtobufContentComponent } from '@shared/components/protobuf-content.component'; import { CssComponent } from '@shared/components/css.component'; export function MarkedOptionsFactory(markedOptionsService: MarkedOptionsService) { return markedOptionsService; } @NgModule({ providers: [ DatePipe, MillisecondsToTimeStringPipe, EnumToArrayPipe, HighlightPipe, TruncatePipe, TbJsonPipe, FileSizePipe, { provide: FlowInjectionToken, useValue: Flow }, { provide: MAT_DATE_LOCALE, useValue: 'en-GB' }, { provide: HELP_MARKDOWN_COMPONENT_TOKEN, useValue: HelpMarkdownComponent }, { provide: SHARED_MODULE_TOKEN, useValue: SharedModule }, TbPopoverService ], declarations: [ FooterComponent, LogoComponent, FooterFabButtonsComponent, ToastDirective, FullscreenDirective, CircularProgressDirective, MatChipDraggableDirective, TbHotkeysDirective, TbAnchorComponent, TbPopoverComponent, TbStringTemplateOutletDirective, TbComponentOutletDirective, TbPopoverDirective, TbMarkdownComponent, HelpComponent, HelpMarkdownComponent, HelpPopupComponent, TbCheckboxComponent, TbSnackBarComponent, TbErrorComponent, TbCheatSheetComponent, BreadcrumbComponent, UserMenuComponent, TimewindowComponent, TimewindowPanelComponent, TimeintervalComponent, QuickTimeIntervalComponent, DashboardSelectComponent, DashboardSelectPanelComponent, DatetimePeriodComponent, DatetimeComponent, TimezoneSelectComponent, ValueInputComponent, DashboardAutocompleteComponent, EntitySubTypeAutocompleteComponent, EntitySubTypeSelectComponent, EntitySubTypeListComponent, EntityAutocompleteComponent, EntityListComponent, EntityTypeSelectComponent, EntitySelectComponent, EntityKeysListComponent, EntityListSelectComponent, EntityTypeListComponent, QueueTypeListComponent, RelationTypeAutocompleteComponent, SocialSharePanelComponent, JsonObjectEditComponent, JsonContentComponent, JsFuncComponent, CssComponent, FabTriggerDirective, FabActionsDirective, FabToolbarComponent, WidgetsBundleSelectComponent, ConfirmDialogComponent, AlertDialogComponent, TodoDialogComponent, ColorPickerDialogComponent, MaterialIconsDialogComponent, ColorInputComponent, MaterialIconSelectComponent, NodeScriptTestDialogComponent, JsonFormComponent, ImageInputComponent, FileInputComponent, MessageTypeAutocompleteComponent, KeyValMapComponent, NavTreeComponent, LedLightComponent, NospacePipe, MillisecondsToTimeStringPipe, EnumToArrayPipe, HighlightPipe, TruncatePipe, TbJsonPipe, FileSizePipe, SelectableColumnsPipe, KeyboardShortcutPipe, TbJsonToStringDirective, JsonObjectEditDialogComponent, HistorySelectorComponent, EntityGatewaySelectComponent, ContactComponent, OtaPackageAutocompleteComponent, WidgetsBundleSearchComponent, CopyButtonComponent, TogglePasswordComponent, ProtobufContentComponent ], imports: [ CommonModule, RouterModule, TranslateModule, MatButtonModule, MatCheckboxModule, MatIconModule, MatCardModule, MatProgressBarModule, MatInputModule, MatSnackBarModule, MatSidenavModule, MatToolbarModule, MatMenuModule, MatGridListModule, MatDialogModule, MatSelectModule, MatTooltipModule, MatTableModule, MatPaginatorModule, MatSortModule, MatProgressSpinnerModule, MatDividerModule, MatTabsModule, MatRadioModule, MatSlideToggleModule, MatDatepickerModule, MatNativeDatetimeModule, MatDatetimepickerModule, NgxDaterangepickerMd.forRoot(), MatSliderModule, MatExpansionModule, MatStepperModule, MatAutocompleteModule, MatChipsModule, MatListModule, GridsterModule, ClipboardModule, FlexLayoutModule.withConfig({addFlexToParent: false}), FormsModule, ReactiveFormsModule, OverlayModule, ShareButtonsModule, HotkeyModule, ColorPickerModule, NgxHmCarouselModule, DndModule, NgxFlowModule, NgxFlowchartModule, // ngx-markdown MarkdownModule.forRoot({ sanitize: SecurityContext.NONE, markedOptions: { provide: MarkedOptions, useFactory: MarkedOptionsFactory, deps: [MarkedOptionsService] } }) ], exports: [ FooterComponent, LogoComponent, FooterFabButtonsComponent, ToastDirective, FullscreenDirective, CircularProgressDirective, MatChipDraggableDirective, TbHotkeysDirective, TbAnchorComponent, TbStringTemplateOutletDirective, TbComponentOutletDirective, TbPopoverDirective, TbMarkdownComponent, HelpComponent, HelpMarkdownComponent, HelpPopupComponent, TbCheckboxComponent, TbErrorComponent, TbCheatSheetComponent, BreadcrumbComponent, UserMenuComponent, TimewindowComponent, TimewindowPanelComponent, TimeintervalComponent, QuickTimeIntervalComponent, DashboardSelectComponent, DatetimePeriodComponent, DatetimeComponent, TimezoneSelectComponent, DashboardAutocompleteComponent, EntitySubTypeAutocompleteComponent, EntitySubTypeSelectComponent, EntitySubTypeListComponent, EntityAutocompleteComponent, EntityListComponent, EntityTypeSelectComponent, EntitySelectComponent, EntityKeysListComponent, EntityListSelectComponent, EntityTypeListComponent, QueueTypeListComponent, RelationTypeAutocompleteComponent, SocialSharePanelComponent, JsonObjectEditComponent, JsonContentComponent, JsFuncComponent, CssComponent, FabTriggerDirective, FabActionsDirective, FabToolbarComponent, WidgetsBundleSelectComponent, ValueInputComponent, MatButtonModule, MatCheckboxModule, MatIconModule, MatCardModule, MatProgressBarModule, MatInputModule, MatSnackBarModule, MatSidenavModule, MatToolbarModule, MatMenuModule, MatGridListModule, MatDialogModule, MatSelectModule, MatTooltipModule, MatTableModule, MatPaginatorModule, MatSortModule, MatProgressSpinnerModule, MatDividerModule, MatTabsModule, MatRadioModule, MatSlideToggleModule, MatDatepickerModule, MatNativeDatetimeModule, MatDatetimepickerModule, NgxDaterangepickerMd, MatSliderModule, MatExpansionModule, MatStepperModule, MatAutocompleteModule, MatChipsModule, MatListModule, GridsterModule, ClipboardModule, FlexLayoutModule, FormsModule, ReactiveFormsModule, OverlayModule, ShareButtonsModule, HotkeyModule, ColorPickerModule, NgxHmCarouselModule, DndModule, NgxFlowchartModule, MarkdownModule, ConfirmDialogComponent, AlertDialogComponent, TodoDialogComponent, ColorPickerDialogComponent, MaterialIconsDialogComponent, ColorInputComponent, MaterialIconSelectComponent, NodeScriptTestDialogComponent, JsonFormComponent, ImageInputComponent, FileInputComponent, MessageTypeAutocompleteComponent, KeyValMapComponent, NavTreeComponent, LedLightComponent, NospacePipe, MillisecondsToTimeStringPipe, EnumToArrayPipe, HighlightPipe, TruncatePipe, TbJsonPipe, KeyboardShortcutPipe, FileSizePipe, SelectableColumnsPipe, TranslateModule, JsonObjectEditDialogComponent, HistorySelectorComponent, EntityGatewaySelectComponent, ContactComponent, OtaPackageAutocompleteComponent, WidgetsBundleSearchComponent, CopyButtonComponent, TogglePasswordComponent, ProtobufContentComponent ] }) export class SharedModule { }
the_stack
export as namespace Diff; export type Callback = (err: undefined, value?: Change[]) => void; export interface CallbackOptions { /** * Callback to call with the result instead of returning the result directly. */ callback: Callback; } export interface BaseOptions { /** * `true` to ignore casing difference. * @default false */ ignoreCase?: boolean; } export interface WordsOptions extends BaseOptions { /** * `true` to ignore leading and trailing whitespace. This is the same as `diffWords()`. */ ignoreWhitespace?: boolean; } export interface LinesOptions extends BaseOptions { /** * `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines()`. */ ignoreWhitespace?: boolean; /** * `true` to treat newline characters as separate tokens. This allows for changes to the newline structure * to occur independently of the line content and to be treated as such. In general this is the more * human friendly form of `diffLines()` and `diffLines()` is better suited for patches and other computer * friendly output. */ newlineIsToken?: boolean; } export interface JsonOptions extends LinesOptions { /** * Replacer used to stringify the properties of the passed objects. */ stringifyReplacer?: (key: string, value: any) => any; /** * The value to use when `undefined` values in the passed objects are encountered during stringification. * Will only be used if `stringifyReplacer` option wasn't specified. * @default undefined */ undefinedReplacement?: any; } export interface ArrayOptions<TLeft, TRight> extends BaseOptions { /** * Comparator for custom equality checks. */ comparator?: (left: TLeft, right: TRight) => boolean; } export interface PatchOptions extends LinesOptions { /** * Describes how many lines of context should be included. * @default 4 */ context?: number; } export interface ApplyPatchOptions { /** * Number of lines that are allowed to differ before rejecting a patch. * @default 0 */ fuzzFactor?: number; /** * Callback used to compare to given lines to determine if they should be considered equal when patching. * Should return `false` if the lines should be rejected. * * @default strict equality */ compareLine?: ( lineNumber: number, line: string, operation: '-' | ' ', patchContent: string ) => boolean; } export interface ApplyPatchesOptions extends ApplyPatchOptions { loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void; patched(index: ParsedDiff, content: string, callback: (err: any) => void): void; complete(err: any): void; } export interface Change { count?: number; /** * Text content. */ value: string; /** * `true` if the value was inserted into the new string. */ added?: boolean; /** * `true` if the value was removed from the old string. */ removed?: boolean; } export interface ArrayChange<T> { value: T[]; count?: number; added?: boolean; removed?: boolean; } export interface ParsedDiff { index?: string; oldFileName?: string; newFileName?: string; oldHeader?: string; newHeader?: string; hunks: Hunk[]; } export interface Hunk { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: string[]; linedelimiters: string[]; } export interface BestPath { newPos: number; componenets: Change[]; } export class Diff { diff( oldString: string, newString: string, options?: Callback | (ArrayOptions<any, any> & Partial<CallbackOptions>) ): Change[]; pushComponent(components: Change[], added: boolean, removed: boolean): void; extractCommon( basePath: BestPath, newString: string, oldString: string, diagonalPath: number ): number; equals(left: any, right: any): boolean; removeEmpty(array: any[]): any[]; castInput(value: any): any; join(chars: string[]): string; tokenize(value: string): any; // return types are string or string[] } /** * Diffs two blocks of text, comparing character by character. * * @returns A list of change objects. */ export function diffChars(oldStr: string, newStr: string, options?: BaseOptions): Change[]; export function diffChars( oldStr: string, newStr: string, options: Callback | (BaseOptions & CallbackOptions) ): void; /** * Diffs two blocks of text, comparing word by word, ignoring whitespace. * * @returns A list of change objects. */ export function diffWords(oldStr: string, newStr: string, options?: WordsOptions): Change[]; export function diffWords( oldStr: string, newStr: string, options: Callback | (WordsOptions & CallbackOptions) ): void; /** * Diffs two blocks of text, comparing word by word, treating whitespace as significant. * * @returns A list of change objects. */ export function diffWordsWithSpace( oldStr: string, newStr: string, options?: WordsOptions ): Change[]; export function diffWordsWithSpace( oldStr: string, newStr: string, options: Callback | (WordsOptions & CallbackOptions) ): void; /** * Diffs two blocks of text, comparing line by line. * * @returns A list of change objects. */ export function diffLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; export function diffLines( oldStr: string, newStr: string, options: Callback | (LinesOptions & CallbackOptions) ): void; /** * Diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. * * @returns A list of change objects. */ export function diffTrimmedLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; export function diffTrimmedLines( oldStr: string, newStr: string, options: Callback | (LinesOptions & CallbackOptions) ): void; /** * Diffs two blocks of text, comparing sentence by sentence. * * @returns A list of change objects. */ export function diffSentences(oldStr: string, newStr: string, options?: BaseOptions): Change[]; export function diffSentences( oldStr: string, newStr: string, options: Callback | (BaseOptions & CallbackOptions) ): void; /** * Diffs two blocks of text, comparing CSS tokens. * * @returns A list of change objects. */ export function diffCss(oldStr: string, newStr: string, options?: BaseOptions): Change[]; export function diffCss( oldStr: string, newStr: string, options: Callback | (BaseOptions & CallbackOptions) ): void; /** * Diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter * in this comparison. * * @returns A list of change objects. */ export function diffJson( oldObj: string | object, newObj: string | object, options?: JsonOptions ): Change[]; export function diffJson( oldObj: string | object, newObj: string | object, options: Callback | (JsonOptions & CallbackOptions) ): void; /** * Diffs two arrays, comparing each item for strict equality (`===`). * * @returns A list of change objects. */ export function diffArrays<TOld, TNew>( oldArr: TOld[], newArr: TNew[], options?: ArrayOptions<TOld, TNew> ): Array<ArrayChange<TOld | TNew>>; /** * Creates a unified diff patch. * * @param oldFileName String to be output in the filename section of the patch for the removals. * @param newFileName String to be output in the filename section of the patch for the additions. * @param oldStr Original string value. * @param newStr New string value. * @param oldHeader Additional information to include in the old file header. * @param newHeader Additional information to include in the new file header. */ export function createTwoFilesPatch( oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader?: string, newHeader?: string, options?: PatchOptions ): string; /** * Creates a unified diff patch. * Just like `createTwoFilesPatch()`, but with `oldFileName` being equal to `newFileName`. * * @param fileName String to be output in the filename section. * @param oldStr Original string value. * @param newStr New string value. * @param oldHeader Additional information to include in the old file header. * @param newHeader Additional information to include in the new file header. */ export function createPatch( fileName: string, oldStr: string, newStr: string, oldHeader?: string, newHeader?: string, options?: PatchOptions ): string; /** * This method is similar to `createTwoFilesPatch()`, but returns a data structure suitable for further processing. * Parameters are the same as `createTwoFilesPatch()`. * * @param oldFileName String to be output in the `oldFileName` hunk property. * @param newFileName String to be output in the `newFileName` hunk property. * @param oldStr Original string value. * @param newStr New string value. * @param oldHeader Additional information to include in the `oldHeader` hunk property. * @param newHeader Additional information to include in the `newHeader` hunk property. * @returns An object with an array of hunk objects. */ export function structuredPatch( oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader?: string, newHeader?: string, options?: PatchOptions ): ParsedDiff; /** * Applies a unified diff patch. * * @param patch May be a string diff or the output from the `parsePatch()` or `structuredPatch()` methods. * @returns A string containing new version of provided data. */ export function applyPatch( source: string, patch: string | ParsedDiff | [ParsedDiff], options?: ApplyPatchOptions ): string; /** * Applies one or more patches. * This method will iterate over the contents of the patch and apply to data provided through callbacks. * * The general flow for each patch index is: * * 1. `options.loadFile(index, callback)` is called. The caller should then load the contents of the file * and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. * 2. `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be * the return value from `applyPatch()`. When it's ready, the caller should call `callback(err)` callback. * Passing an `err` will terminate further patch execution. * 3. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. */ export function applyPatches(patch: string | ParsedDiff[], options: ApplyPatchesOptions): void; /** * Parses a patch into structured data. * * @returns A JSON object representation of the a patch, suitable for use with the `applyPatch()` method. */ export function parsePatch(diffStr: string, options?: { strict?: boolean }): ParsedDiff[]; /** * Converts a list of changes to a serialized XML format. */ export function convertChangesToXML(changes: Change[]): string; /** * Converts a list of changes to [DMP](http://code.google.com/p/google-diff-match-patch/wiki/API) format. */ export function convertChangesToDMP(changes: Change[]): Array<[1 | 0 | -1, string]>; export function merge(mine: string, theirs: string, base: string): ParsedDiff; export function canonicalize(obj: any, stack: any[], replacementStack: any[]): any;
the_stack
import {writeFileSync} from 'node:fs'; import {join} from 'node:path'; import got from 'got'; import {ESLint} from 'eslint'; // protoco.json typing interface GeneratedProtocol { enums: Array<{enumType: string; enumIdentifiers: EnumIdentifier[]}>; requests: OBSRequest[]; events: OBSEvent[]; } interface EnumIdentifier { description: string; enumIdentifier: string; rpcVersion: string; deprecated: boolean; initialVersion: string; enumValue: number | string; } interface OBSRequest { description: string; requestType: string; complexity: number; rpcVersion: string; deprecated: boolean; initialVersion: string; category: string; requestFields: OBSRequestField[]; responseFields: OBSResponseField[]; } interface OBSRequestField { valueName: string; valueType: string; valueDescription: string; valueRestrictions: null | string; valueOptional: boolean; valueOptionalBehavior: null | string; } interface OBSResponseField { valueName: string; valueType: string; valueDescription: string; } function isObsRequestField(val: OBSRequestField | OBSResponseField): val is OBSRequestField { return 'valueOptional' in val; } interface OBSEvent { description: string; eventType: string; eventSubscription: string; complexity: number; rpcVersion: string; deprecated: boolean; initialVersion: string; category: string; dataFields: OBSEventField[]; } interface OBSEventField { valueName: string; valueType: string; valueDescription: string; } const OUTPUT_FILE = join(process.cwd(), 'src/types.ts'); const headers = { // eslint-disable-next-line @typescript-eslint/naming-convention Authorization: process.env.GH_TOKEN ? `token ${process.env.GH_TOKEN}` : undefined, }; /* Uncomment once released const {body: release} = await got('https://api.github.com/repos/obsproject/obs-websocket/releases/latest', { headers, responseType: 'json' }); const commit = release.tag_name; */ const commit = 'master'; const {body: protocol} = await got<GeneratedProtocol>(`https://raw.githubusercontent.com/obsproject/obs-websocket/${commit}/docs/generated/protocol.json`, { headers, responseType: 'json', }); // fix oopsie in protocol.json protocol.requests.forEach(req => { if (req.requestType === 'GetSourceScreenshot' && req.description.startsWith('Saves')) { req.requestType = 'SaveSourceScreenshot'; } }); const ENUMS: Record<string, EnumIdentifier[]> = {}; protocol.enums.forEach(({enumType, enumIdentifiers}) => { ENUMS[enumType] = enumIdentifiers; }); const source = `/** * This file is autogenerated by scripts/generate-obs-typings.js * To update this with latest changes do npm run generate:obs-types */ import {JsonArray, JsonObject, JsonValue} from 'type-fest'; ${generateEnum('WebSocketOpCode', ENUMS.WebSocketOpCode)} /* eslint-disable no-bitwise, @typescript-eslint/prefer-literal-enum-member */ ${generateEnum('EventSubscription', ENUMS.EventSubscription)} /* eslint-enable no-bitwise, @typescript-eslint/prefer-literal-enum-member */ ${generateEnum('RequestBatchExecutionType', ENUMS.RequestBatchExecutionType)} // WebSocket Message Types export type IncomingMessage<Type = keyof IncomingMessageTypes> = Type extends keyof IncomingMessageTypes ? { op: Type; d: IncomingMessageTypes[Type]; } : never; export type OutgoingMessage<Type = keyof OutgoingMessageTypes> = Type extends keyof OutgoingMessageTypes ? { op: Type; d: OutgoingMessageTypes[Type]; } : never; export interface IncomingMessageTypes { /** * Message sent from the server immediately on client connection. Contains authentication information if auth is required. Also contains RPC version for version negotiation. */ [WebSocketOpCode.Hello]: { /** * Version number of obs-websocket */ obsWebSocketVersion: string; /** * Version number which gets incremented on each breaking change to the obs-websocket protocol. * It's usage in this context is to provide the current rpc version that the server would like to use. */ rpcVersion: number; /** * Authentication challenge when password is required */ authentication?: { challenge: string; salt: string; }; }; /** * The identify request was received and validated, and the connection is now ready for normal operation. */ [WebSocketOpCode.Identified]: { /** * If rpc version negotiation succeeds, the server determines the RPC version to be used and gives it to the client */ negotiatedRpcVersion: number; }; /** * An event coming from OBS has occured. Eg scene switched, source muted. */ [WebSocketOpCode.Event]: EventMessage; /** * obs-websocket is responding to a request coming from a client */ [WebSocketOpCode.RequestResponse]: ResponseMessage; } export interface OutgoingMessageTypes { /** * Response to Hello message, should contain authentication string if authentication is required, along with PubSub subscriptions and other session parameters. */ [WebSocketOpCode.Identify]: { /** * Version number that the client would like the obs-websocket server to use */ rpcVersion: number; /** * Authentication challenge response */ authentication?: string; * Bitmask of \`EventSubscription\` items to subscribe to events and event categories at will. By default, all event categories are subscribed, except for events marked as high volume. High volume events must be explicitly subscribed to. */ eventSubscriptions?: number; }; /** * Sent at any time after initial identification to update the provided session parameters. */ [WebSocketOpCode.Reidentify]: { * Bitmask of \`EventSubscription\` items to subscribe to events and event categories at will. By default, all event categories are subscribed, except for events marked as high volume. High volume events must be explicitly subscribed to. */ eventSubscriptions?: number; }; /** * Client is making a request to obs-websocket. Eg get current scene, create source. */ [WebSocketOpCode.Request]: RequestMessage; } type EventMessage<T = keyof OBSEventTypes> = T extends keyof OBSEventTypes ? { eventType: T; /** * The original intent required to be subscribed to in order to receive the event. */ eventIntent: number; eventData: OBSEventTypes[T]; } : never; export type RequestMessage<T = keyof OBSRequestTypes> = T extends keyof OBSRequestTypes ? { requestType: T; requestId: string; requestData: OBSRequestTypes[T]; } : never; export type ResponseMessage<T = keyof OBSResponseTypes> = T extends keyof OBSResponseTypes ? { requestType: T; requestId: string; requestStatus: {result: true; code: number} | {result: false; code: number; comment: string}; responseData: OBSResponseTypes[T]; } : never; // Events export interface OBSEventTypes { ${generateObsEventTypes(protocol.events)} } // Requests and Responses export interface OBSRequestTypes { ${generateObsRequestTypes(protocol.requests)} } export interface OBSResponseTypes { ${generateObsResponseTypes(protocol.requests)} } `; /* typescript provides worse autocomplete results and errors with these // Overrides to improve typescript for requests without data and to provide documentation declare module './base' { interface BaseOBSWebSocket { ${generateObsRequestOverrides(protocol.requests)} ${generateObsListenerOverrides(protocol.events)} } } */ const linter = new ESLint({fix: true}); const linted = await linter.lintText(source, { filePath: OUTPUT_FILE, }); if (linted[0].messages.length > 0) { const formatter = await linter.loadFormatter('stylish'); process.stderr.write(formatter.format(linted)); process.exitCode = 1; } writeFileSync(OUTPUT_FILE, linted[0].output ?? source); // Utility funcs function formatJsDoc(jsdoc: string[]) { return [ '/**', ...jsdoc.map(s => ` * ${s}`), ' */', ].join('\n'); } function generateEnum(type: string, identifiers: EnumIdentifier[]): string { return [ `export enum ${type} {`, ...identifiers.map(value => { const jsdoc: string[] = [ ...value.description.split('\n'), '', `Initial OBS Version: ${value.initialVersion}`, ]; if (value.deprecated) { jsdoc.push('', '@deprecated'); } return [ formatJsDoc(jsdoc), `${value.enumIdentifier} = ${value.enumValue},`, ].join('\n'); }), '}', ].join('\n'); } function generateObsEventTypes(events: OBSEvent[]): string { return events.map(ev => { if (ev.dataFields.length === 0) { return `${ev.eventType}: undefined;`; } return `${ev.eventType}: ${stringifyTypes(unflattenAndResolveTypes(ev.dataFields))};`; }).join('\n'); } function generateObsRequestTypes(requests: OBSRequest[]): string { return requests.map(req => { if (req.requestFields.length === 0) { return `${req.requestType}: never;`; } return `${req.requestType}: ${stringifyTypes(unflattenAndResolveTypes(req.requestFields))};`; }).join('\n'); } function generateObsResponseTypes(requests: OBSRequest[]): string { return requests.map(req => { if (req.responseFields.length === 0) { return `\t${req.requestType}: undefined;`; } return `${req.requestType}: ${stringifyTypes(unflattenAndResolveTypes(req.responseFields))};`; }).join('\n'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars function generateObsListenerOverrides(events: OBSEvent[]): string { return events.map(ev => { const jsdoc: string[] = [ ...ev.description.split('\n'), '', `@category ${ev.category}`, `@initialVersion ${ev.initialVersion}`, `@rpcVersion ${ev.rpcVersion}`, `@complexity ${ev.complexity}`, ]; if (ev.deprecated) { jsdoc.push('@deprecated'); } return [ formatJsDoc(jsdoc), `on(event: '${ev.eventType}', listener: (data: OBSEventTypes['${ev.eventType}']) => void): this;`, ].join('\n'); }).join('\n'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars function generateObsRequestOverrides(requests: OBSRequest[]): string { return requests.map(req => { const jsdoc: string[] = [ ...req.description.split('\n'), '', `@category ${req.category}`, `@initialVersion ${req.initialVersion}`, `@rpcVersion ${req.rpcVersion}`, `@complexity ${req.complexity}`, ]; if (req.deprecated) { jsdoc.push('@deprecated'); } const requestData = req.requestFields.length > 0 ? `requestData: OBSRequestTypes['${req.requestType}']` : 'requestData?: never'; return [ formatJsDoc(jsdoc), `call(requestType: '${req.requestType}', ${requestData}): Promise<OBSResponseTypes['${req.requestType}']>;`, ].join('\n'); }).join('\n'); } type Tree = Record<string, AnyType>; interface BaseType { optional?: boolean; jsdoc?: string; } interface PrimitiveType extends BaseType { type: 'string' | 'number' | 'boolean'; } interface JsonValueType extends BaseType { type: 'jsonvalue'; properties: Tree; } interface ObjectType extends BaseType { type: 'object'; properties: Tree; } interface ArrayType extends BaseType { type: 'array'; items: PrimitiveType | ObjectType; } type AnyType = PrimitiveType | JsonValueType | ObjectType | ArrayType; function unflattenAndResolveTypes(inputItems: Array<OBSRequestField | OBSResponseField>): ObjectType { const root: ObjectType = { type: 'object', properties: {}, }; const items = inputItems.slice(0); // Sort items by depth (number of dots in their key). // This ensures that we build our tree starting from the roots and ending at the leaves. items.sort((a, b) => { const DOTS_REGEX = /\./g; const aDots = a.valueName.match(DOTS_REGEX); const bDots = b.valueName.match(DOTS_REGEX); return (aDots?.length ?? 0) - (bDots?.length ?? 0); }); // Build the tree, one item at a time. items.forEach(item => { // Split the name of this item into parts, splitting it at each dot character. const parts = item.valueName.split('.'); const lastPart = parts.pop()!; let currentNode: AnyType = root; parts.forEach((nodeName, i) => { if (nodeName === '*') { if (currentNode.type !== 'array' || currentNode.items.type !== 'object') { throw new Error(`Unexpected object already exists for * key currentNode: ${JSON.stringify(currentNode)} item: ${JSON.stringify(item)} `); } currentNode = currentNode.items; } if (currentNode.type !== 'object') { throw new Error(`Unexpected current object type currentNode: ${JSON.stringify(currentNode)} item: ${JSON.stringify(item)} nodeName: ${nodeName} `); } if (!(nodeName in currentNode.properties)) { if (parts[i + 1] === '*') { currentNode.properties[nodeName] = { type: 'array', items: { type: 'object', properties: {}, }, }; } else { currentNode.properties[nodeName] = { type: 'object', properties: {}, }; } } currentNode = currentNode.properties[nodeName]; }); if (lastPart === '*') { // Expecting this doesn't happen as there's Array<Subtype> type throw new Error(`Need to add last * handler currentNode: ${JSON.stringify(currentNode)} item: ${JSON.stringify(item)} `); } if (currentNode.type !== 'object') { throw new Error(`Current node isn't an object currentNode: ${JSON.stringify(currentNode)} item: ${JSON.stringify(item)} `); } currentNode.properties[lastPart] = resolveType(item); }); return root; } function resolveType(field: OBSRequestField | OBSResponseField): AnyType { const type = getBaseType(field.valueType); type.jsdoc = field.valueDescription; if (isObsRequestField(field)) { // eslint-disable-next-line @typescript-eslint/naming-convention const {valueRestrictions, valueOptional, valueOptionalBehavior} = field; type.optional = valueOptional; if (valueRestrictions) { type.jsdoc += `\n@restrictions ${valueRestrictions}`; } if (valueOptionalBehavior) { type.jsdoc += `\n@defaultValue ${valueOptionalBehavior}`; } } return type; } function getBaseType(inType: string): AnyType { const ARRAY_PREFIX = 'Array<'; if (inType.startsWith(ARRAY_PREFIX)) { const subType = inType.substring(ARRAY_PREFIX.length, inType.lastIndexOf('>')); return { type: 'array', items: getBaseType(subType) as ArrayType['items'], }; } switch (inType) { case 'Boolean': return { type: 'boolean', }; case 'String': return { type: 'string', }; case 'Number': return { type: 'number', }; case 'Object': return { type: 'object', properties: {}, }; case 'Any': return { type: 'jsonvalue', properties: {}, }; default: throw new Error(`Unknown type: ${inType}`); } } function stringifyTypes(inputTypes: AnyType): string { switch (inputTypes.type) { case 'object': return stringifyObject(inputTypes); case 'array': { const subtype = stringifyTypes(inputTypes.items); if (subtype === 'JsonObject') { return 'JsonArray'; } return `Array<${subtype}>`; } case 'jsonvalue': return 'JsonValue'; default: return inputTypes.type; } } function stringifyObject(inputTypes: ObjectType): string { if (Object.keys(inputTypes.properties).length === 0) { return 'JsonObject'; } const properties: string[] = []; Object.entries(inputTypes.properties).forEach(([key, typeDef]) => { const separator = typeDef.optional ? '?:' : ':'; const type = stringifyTypes(typeDef); if (typeDef.jsdoc) { properties.push(formatJsDoc(typeDef.jsdoc.split('\n'))); } properties.push(`${key}${separator} ${type};`); }); return [ '{', ...properties, '}', ].join('\n'); }
the_stack
import PCR = require( 'puppeteer-chromium-resolver'); const { ObjectId }= require('bson'); import { UserPlatform, Template, Task, Article, Platform, Environment, IUserPlatform, Cookie, IPlatform, ITask, IAritcle, } from "@/models"; import constants from '../constants' import config from './config' import logger from '../logger' import type { Page, Serializable } from 'puppeteer-core'; import type {Types} from 'mongoose' import axios from 'axios'; export default class BaseSpider { taskId: Types.ObjectId; platformId: Types.ObjectId; task: ITask; platform: IPlatform; article: IAritcle; userPlatform: IUserPlatform; browser: any; pcr: ReturnType<typeof PCR>; page: Page; status: { loggedIn: boolean; completedEditor: boolean; published: boolean; }; footerContent: { richText: string; }; urls: any; loginSel: any; publishNavigationChange: any; editorSel: any; constructor(taskId, platformId) { // 任务ID this.taskId = taskId; // 平台ID this.platformId = platformId; } async init() { // 任务 this.task = await Task.findOne({ _id: ObjectId(this.taskId) }) as ITask; if (!this.task) { throw new Error(`task (ID: ${this.taskId}) cannot be found`); } // 文章 this.article = await Article.findOne({ _id: this.task.articleId }) as IAritcle; if (!this.article) { throw new Error(`article (ID: ${this.task.articleId.toString()}) cannot be found`); } // 平台 this.userPlatform = await UserPlatform.findOne({ platform: this.task.platformId, user: this.task.user }) .populate({path: 'platform'}).exec() as IUserPlatform; if (!this.userPlatform) { throw new Error(`platform (ID: ${this.task.platformId.toString()}) cannot be found`); } this.platform = this.userPlatform.platform as IPlatform; // PCR this.pcr = await PCR({ revision: '', detectionPath: '', folderName: '.chromium-browser-snapshots', hosts: ['https://storage.googleapis.com', 'https://npm.taobao.org/mirrors'], retry: 3, silent: false, }); // 是否开启chrome浏览器调试 const enableChromeDebugEnv = await Environment.findOne({ name: constants.environment.ENABLE_CHROME_DEBUG, user: this.task.user }); const enableChromeDebug = enableChromeDebugEnv!.value; // 浏览器 this.browser = await this.pcr.puppeteer.launch({ executablePath: this.pcr.executablePath, //设置超时时间 timeout: 120000, //如果是访问https页面 此属性会忽略https错误 ignoreHTTPSErrors: true, // 打开开发者工具, 当此值为true时, headless总为false devtools: false, // 关闭headless模式, 不会打开浏览器 headless: enableChromeDebug !== "Y", args: ["--no-sandbox", '--start-maximized'], defaultViewport: null, }); // 页面 this.page = await this.browser.newPage(); // 状态 this.status = { loggedIn: false, completedEditor: false, published: false, }; // 配置 const platformConfig = config[this.platform.name]; if (!platformConfig) { throw new Error(`config (platform: ${this.platform.name}) cannot be found`); } Object.assign(this, platformConfig); // 脚注内容 this.footerContent = { richText: `<br><b>本篇文章由一文多发平台<a href="https://github.com/crawlab-team/artipub" target="_blank">ArtiPub</a>自动发布</b>`, }; } /** * 返回拼接头尾部模版后,实际发到平台的最终内容 * @returns */ getFinalContent(): string { return ''; } /** * 登陆网站 */ async login() { logger.info(`logging in... navigating to ${this.urls.login}`); await this.page.goto(this.urls.login); let errNum = 0; while (errNum < 10) { try { await this.page.waitForTimeout(1000); const elUsername = await this.page.$(this.loginSel.username); const elPassword = await this.page.$(this.loginSel.password); const elSubmit = await this.page.$(this.loginSel.submit); await elUsername!.type(this.userPlatform.username); await elPassword!.type(this.userPlatform.password); await elSubmit!.click(); await this.page.waitForTimeout(3000); break; } catch (e) { errNum++; } } // 查看是否登陆成功 this.status.loggedIn = errNum !== 10; if (this.status.loggedIn) { logger.info('Logged in'); } } /** * 设置Cookie */ async setCookies() { const cookies = await Cookie.find({ domain: BaseSpider.getCookieDomainCondition(this.platform.name), }); for (let i = 0; i < cookies.length; i++) { const c = cookies[i]; await this.page.setCookie({ name: c.name, value: c.value, domain: c.domain, }); } } /** * 获取可给axios 使用的cookie */ static async getCookiesForAxios(platformName, userId: Types.ObjectId) { const cookies = await Cookie.find({ domain: BaseSpider.getCookieDomainCondition(platformName), user: userId, }); let cookieStr = ''; for (let i = 0; i < cookies.length; i++) { const c = cookies[i]; cookieStr += `${c.name}=${c.value};`; } return cookieStr; } /** * 域查询条件 */ static getCookieDomainCondition(platformName) { return { $regex: platformName }; } /** * 导航至写作页面 */ async goToEditor() { logger.info(`navigating to ${this.urls.editor}`); await Promise.all([ this.page.goto(this.urls.editor), this.page.waitForNavigation({ waitUntil: ['load', 'domcontentloaded', 'networkidle2'] }) ]); await this.afterGoToEditor(); } /** * 导航至写作页面后续操作 */ async afterGoToEditor() { // 导航至写作页面的后续处理 // 掘金等网站会先弹出Markdown页面,需要特殊处理 } /** * 输入文章标题 */ async inputTitle(article, editorSel, task: {title: string}) { const el = document.querySelector(editorSel.title); el.focus(); el.select(); document.execCommand('delete', false); document.execCommand('insertText', false, task.title || article.title); } /** * 输入文章内容 */ async inputContent(realContent: string, editorSel: { content: string; }) { const el = document.querySelector(editorSel.content) as HTMLPreElement; el.focus(); try { //@ts-ignore 不知道为什么识别不了select HTMLPreElement.prototype.select = function () { let range = document.createRange(); range.selectNodeContents(this); let sel = window.getSelection(); sel!.removeAllRanges(); sel!.addRange(range); } //@ts-ignore el.select(); } catch (e) { // do nothing } document.execCommand('delete', false); document.execCommand('insertText', false, realContent); } /** * 输入文章脚注 */ async inputFooter(article, editorSel) { const footerContent = `\n\n> 本篇文章由一文多发平台[ArtiPub](https://github.com/crawlab-team/artipub)自动发布`; const el = document.querySelector(editorSel.content); el.focus(); document.execCommand('insertText', false, footerContent); } /** * 输入编辑器 */ async inputEditor() { logger.info(`input editor title`); // 输入标题 await this.page.evaluate( this.inputTitle, this.article as any, this.editorSel, this.task as any ); // 输入内容 logger.info(`input editor content`); await this.page.evaluate(this.inputContent, this.article as any, this.editorSel); await this.page.waitForTimeout(3000); // 输入脚注 await this.page.evaluate(this.inputFooter, this.article as any, this.editorSel); await this.page.waitForTimeout(3000); // 后续处理 await this.afterInputEditor(); } /** * 输入编辑器后续操作 */ async afterInputEditor() { // 输入编辑器内容的后续处理 // 标签、分类输入放在这里 } /** * 发布文章 */ async publish() { logger.info(`publishing article`); //发布后地址会变更用waitForNavigation,不会变更用固定时间,尽量减少等待时间 await Promise.all([ //@ts-ignore this.page.$eval(this.editorSel.publish, submit => submit.click()), this.publishNavigationChange ? this.page.waitForNavigation() : this.page.waitForTimeout(1500) ]); // 后续处理 await this.afterPublish(); } /** * 发布文章后续操作 */ async afterPublish() { // 提交文章的后续处理 // 保存文章url等逻辑放在这里 } /** * 运行爬虫 */ async run() { // 初始化 await this.init(); if (this.task.authType === constants.authType.LOGIN) { // 登陆 await this.login(); } else { // 使用Cookie await this.setCookies(); } // 导航至编辑器 await this.goToEditor(); // 输入编辑器内容 await this.inputEditor(); // 发布文章 await this.publish(); // 关闭浏览器 // await this.browser.close(); } /** * 获取文章统计数据 */ async fetchStats() { // to be inherited } /** * 获取文章统计数据后续操作 */ async afterFetchStats() { // 统计文章总阅读、点赞、评论数 const tasks = await Task.find({ articleId: this.article._id }); let readNum = 0; let likeNum = 0; let commentNum = 0; for (let i = 0; i < tasks.length; i++) { const task = tasks[i]; readNum += task.readNum || 0; likeNum += task.likeNum || 0; commentNum += task.commentNum || 0; } this.article.readNum = readNum; this.article.likeNum = likeNum; this.article.commentNum = commentNum; await this.article.save(); } /** * 运行获取文章统计数据 */ async runFetchStats() { // 初始化 await this.init(); // 获取文章数据 await this.fetchStats(); // 后续操作 await this.afterFetchStats(); // 关闭浏览器 const pages = await this.browser.pages(); await Promise.all(pages.map(page => page.close())); await this.browser.close(); } /** * 检查Cookie是否能正常登陆 */ static async checkCookieStatus(platform: IPlatform, userId: Types.ObjectId) { // platform let userPlatform = (await UserPlatform.findOne({ platform: platform._id, user: userId, })) as IUserPlatform; if (!userPlatform) { userPlatform = new UserPlatform({platform: platform._id, user: userId}) } //百家号不支持 cookie,页面埋了token,只携带cookie 还是未登陆态,页面请求后会将token失效 if (platform.name === constants.platform.BAIJIAHAO) { userPlatform.loggedIn = false; await userPlatform.save(); return; } const cookie = await BaseSpider.getCookiesForAxios(platform.name, userId); if (!cookie) { userPlatform.loggedIn = false; await userPlatform.save(); return; } let url = platform.url if (platform.name === constants.platform.CSDN) { url = "https://me.csdn.net/api/user/getUserPrivacy" } if (platform.name === constants.platform.ALIYUN) { url = "https://developer.aliyun.com/developer/api/my/user/getUser" } axios.get(url, { headers: { 'Cookie': cookie, }, timeout: 5000, }) .then(async res => { logger.info(url); let text = res.data; if (platform.name === constants.platform.TOUTIAO) { userPlatform.loggedIn = !text.includes('login-button'); } else if (platform.name === constants.platform.CSDN) { text = text.message userPlatform.loggedIn = text.includes('成功'); } else if (platform.name === constants.platform.JIANSHU) { userPlatform.loggedIn = text.includes('我的主页'); } else if ([constants.platform.CNBLOGS, constants.platform.B_51CTO].includes(platform.name)) { userPlatform.loggedIn = text.includes('我的博客'); } else if (platform.name === constants.platform.OSCHINA) { userPlatform.loggedIn = text.includes('g_user_name'); } else if (platform.name === constants.platform.V2EX) { userPlatform.loggedIn = text.includes('登出'); } else if (platform.name === constants.platform.ALIYUN) { userPlatform.loggedIn = text.data != null } else { userPlatform.loggedIn = !text.includes('登录'); } logger.info(userPlatform.loggedIn); await userPlatform.save(); }) .catch(error => { logger.error(`${url} 登录态校验异常`); logger.error(error); }); } }
the_stack
import { defaultTheme, PredictionTypes } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { RangeTypes } from "@responsible-ai/mlchartlib"; import _ from "lodash"; import { Pivot, PivotItem, Stack, StackItem, loadTheme, MessageBar, MessageBarType, Text } from "office-ui-fabric-react"; import React from "react"; import { EmptyHeader } from "./Controls/EmptyHeader"; import { FairnessTab } from "./Controls/FairnessTab"; import { FeatureTab } from "./Controls/FeatureTab"; import { IntroTab } from "./Controls/IntroTab"; import { ModelComparisonChart } from "./Controls/ModelComparisonChart"; import { PerformanceTab } from "./Controls/PerformanceTab"; import { FairnessWizardStyles } from "./FairnessWizard.styles"; import { IFairnessProps } from "./IFairnessProps"; import { IFairnessOption, fairnessOptions, defaultFairnessMetricPrioritization } from "./util/FairnessMetrics"; import { IBinnedResponse } from "./util/IBinnedResponse"; import { IFairnessContext, IRunTimeFairnessContext } from "./util/IFairnessContext"; import { MetricsCache } from "./util/MetricsCache"; import { performanceOptions, IPerformanceOption, defaultPerformanceMetricPrioritization } from "./util/PerformanceMetrics"; import { WizardBuilder } from "./util/WizardBuilder"; import { WizardReport } from "./WizardReport"; export interface IPerformancePickerPropsV2 { performanceOptions: IPerformanceOption[]; selectedPerformanceKey: string; onPerformanceChange: (newKey: string) => void; } export interface IFairnessPickerPropsV2 { fairnessOptions: IFairnessOption[]; selectedFairnessKey: string; onFairnessChange: (newKey: string) => void; } export interface IErrorPickerProps { errorBarsEnabled: boolean; onErrorChange: (newKey: boolean) => void; } export interface IFeatureBinPickerPropsV2 { featureBins: IBinnedResponse[]; selectedBinIndex: number; onBinChange: (index: number) => void; } export interface IWizardStateV2 { showIntro: boolean; activeTabKey: string; selectedModelId?: number; dashboardContext: IFairnessContext; performanceMetrics: IPerformanceOption[]; fairnessMetrics: IFairnessOption[]; selectedPerformanceKey: string | undefined; selectedFairnessKey: string | undefined; errorBarsEnabled: boolean; featureBins: IBinnedResponse[]; selectedBinIndex: number; metricCache: MetricsCache; } const introTabKey = "introTab"; const featureBinTabKey = "featureBinTab"; const performanceTabKey = "performanceTab"; const fairnessTabKey = "fairnessTab"; const reportTabKey = "reportTab"; const flights = { skipFairness: false }; export class FairnessWizard extends React.PureComponent< IFairnessProps, IWizardStateV2 > { public constructor(props: IFairnessProps) { super(props); if (this.props.locale) { localization.setLanguage(this.props.locale); } let performanceMetrics: IPerformanceOption[]; let fairnessMetrics: IFairnessOption[]; let selectedPerformanceKey: string | undefined; let selectedFairnessKey: string | undefined; loadTheme(props.theme || defaultTheme); // handle the case of precomputed metrics separately. As it becomes more defined, can integrate with existing code path. if (this.props.precomputedMetrics && this.props.precomputedFeatureBins) { // we must assume that the same performance metrics are provided across models and bins performanceMetrics = WizardBuilder.buildPerformanceListForPrecomputedMetrics(this.props); fairnessMetrics = WizardBuilder.buildFairnessListForPrecomputedMetrics( this.props ); const readonlyFeatureBins = this.props.precomputedFeatureBins.map( (initialBin, index) => { return { array: initialBin.binLabels, featureIndex: index, hasError: false, labelArray: initialBin.binLabels, rangeType: RangeTypes.Categorical }; } ); selectedPerformanceKey = this.selectDefaultMetric( performanceMetrics, defaultPerformanceMetricPrioritization ); selectedFairnessKey = this.selectDefaultMetric( fairnessMetrics, defaultFairnessMetricPrioritization ); this.state = { activeTabKey: featureBinTabKey, dashboardContext: WizardBuilder.buildPrecomputedFairnessContext( this.props ), errorBarsEnabled: this.props.errorBarsEnabled ?? false, fairnessMetrics, featureBins: readonlyFeatureBins, metricCache: new MetricsCache( 0, 0, undefined, props.precomputedMetrics ), performanceMetrics, selectedBinIndex: 0, selectedFairnessKey, selectedModelId: this.props.predictedY.length === 1 ? 0 : undefined, selectedPerformanceKey, showIntro: true }; return; } const fairnessContext = WizardBuilder.buildInitialFairnessContext( this.props ); const featureBins = WizardBuilder.buildFeatureBins(fairnessContext); if (featureBins.length > 0) { fairnessContext.binVector = WizardBuilder.generateBinVectorForBin( featureBins[0], fairnessContext.dataset ); fairnessContext.groupNames = featureBins[0].labelArray; } performanceMetrics = this.getPerformanceMetrics(fairnessContext); performanceMetrics = performanceMetrics.filter((metric) => !!metric); selectedPerformanceKey = this.selectDefaultMetric( performanceMetrics, defaultPerformanceMetricPrioritization ); fairnessMetrics = this.getFairnessMetrics(fairnessContext); fairnessMetrics = fairnessMetrics.filter((metric) => !!metric); selectedFairnessKey = this.selectDefaultMetric( fairnessMetrics, defaultFairnessMetricPrioritization ); this.state = { activeTabKey: introTabKey, dashboardContext: fairnessContext, errorBarsEnabled: this.props.errorBarsEnabled ?? false, fairnessMetrics, featureBins, metricCache: new MetricsCache( featureBins.length, this.props.predictedY.length, this.props.requestMetrics ), performanceMetrics, selectedBinIndex: 0, selectedFairnessKey, selectedModelId: this.props.predictedY.length === 1 ? 0 : undefined, selectedPerformanceKey, showIntro: true }; } public componentDidUpdate(prev: IFairnessProps): void { if (prev.theme !== this.props.theme) { loadTheme(this.props.theme || defaultTheme); } if (this.props.locale && prev.locale !== this.props.locale) { localization.setLanguage(this.props.locale); } } public render(): React.ReactNode { const styles = FairnessWizardStyles(); if (!this.state.selectedPerformanceKey) { return ( <MessageBar messageBarType={MessageBarType.warning}> <Text> {localization.Fairness.ValidationErrors.missingPerformanceMetric} </Text> </MessageBar> ); } if (!this.state.selectedFairnessKey) { return ( <MessageBar messageBarType={MessageBarType.warning}> <Text> {localization.Fairness.ValidationErrors.missingFairnessMetric} </Text> </MessageBar> ); } const performancePickerProps = { onPerformanceChange: this.setPerformanceKey, performanceOptions: this.state.performanceMetrics, selectedPerformanceKey: this.state.selectedPerformanceKey }; const fairnessPickerProps = { fairnessOptions: this.state.fairnessMetrics, onFairnessChange: this.setFairnessKey, selectedFairnessKey: this.state.selectedFairnessKey }; const errorPickerProps = { errorBarsEnabled: this.state.errorBarsEnabled, onErrorChange: this.setErrorBarsEnabled }; const featureBinPickerProps = { featureBins: this.state.featureBins, onBinChange: this.setBinIndex, selectedBinIndex: this.state.selectedBinIndex }; if (this.state.featureBins.length === 0) { return ( <Stack className={styles.frame}> <EmptyHeader /> </Stack> ); } return ( <Stack className={styles.frame}> <EmptyHeader /> {this.state.activeTabKey === introTabKey && ( <StackItem grow={2}> <IntroTab onNext={this.setTab.bind(this, featureBinTabKey)} /> </StackItem> )} {(this.state.activeTabKey === featureBinTabKey || this.state.activeTabKey === performanceTabKey || this.state.activeTabKey === fairnessTabKey) && ( <Stack.Item grow={2}> <Pivot className={styles.pivot} styles={{ itemContainer: { height: "100%" } }} selectedKey={this.state.activeTabKey} onLinkClick={this.handleTabClick} > <PivotItem headerText={localization.Fairness.sensitiveFeatures} itemKey={featureBinTabKey} style={{ height: "100%", paddingLeft: "8px" }} > <FeatureTab dashboardContext={this.state.dashboardContext} selectedFeatureChange={this.setBinIndex} selectedFeatureIndex={this.state.selectedBinIndex} featureBins={this.state.featureBins.filter((x) => !!x)} onNext={this.setTab.bind(this, performanceTabKey)} saveBin={this.saveBin} /> </PivotItem> <PivotItem headerText={localization.Fairness.performanceMetric} itemKey={performanceTabKey} style={{ height: "100%", paddingLeft: "8px" }} > <PerformanceTab dashboardContext={this.state.dashboardContext} performancePickerProps={performancePickerProps} onNext={this.setTab.bind( this, flights.skipFairness ? reportTabKey : fairnessTabKey )} onPrevious={this.setTab.bind(this, featureBinTabKey)} /> </PivotItem> {flights.skipFairness === false && ( <PivotItem headerText={localization.Fairness.fairnessMetric} itemKey={fairnessTabKey} style={{ height: "100%", paddingLeft: "8px" }} > <FairnessTab dashboardContext={this.state.dashboardContext} fairnessPickerProps={fairnessPickerProps} onNext={this.setTab.bind(this, reportTabKey)} onPrevious={this.setTab.bind(this, performanceTabKey)} /> </PivotItem> )} </Pivot> </Stack.Item> )} {this.state.activeTabKey === reportTabKey && this.state.selectedModelId !== undefined && ( <WizardReport showIntro={this.state.showIntro} dashboardContext={this.state.dashboardContext} metricsCache={this.state.metricCache} modelCount={this.props.predictedY.length} performancePickerProps={performancePickerProps} onChartClick={this.onSelectModel} fairnessPickerProps={fairnessPickerProps} errorPickerProps={errorPickerProps} featureBinPickerProps={featureBinPickerProps} selectedModelIndex={this.state.selectedModelId} onHideIntro={this.hideIntro} onEditConfigs={this.setTab.bind(this, featureBinTabKey)} /> )} {this.state.activeTabKey === reportTabKey && this.state.selectedModelId === undefined && ( <ModelComparisonChart showIntro={this.state.showIntro} dashboardContext={this.state.dashboardContext} metricsCache={this.state.metricCache} onChartClick={this.onSelectModel} modelCount={this.props.predictedY.length} performancePickerProps={performancePickerProps} fairnessPickerProps={fairnessPickerProps} errorPickerProps={errorPickerProps} featureBinPickerProps={featureBinPickerProps} onHideIntro={this.hideIntro} onEditConfigs={this.setTab.bind(this, featureBinTabKey)} /> )} </Stack> ); } private getPerformanceMetrics( fairnessContext: IRunTimeFairnessContext ): IPerformanceOption[] { if ( fairnessContext.modelMetadata.PredictionType === PredictionTypes.BinaryClassification ) { return this.props.supportedBinaryClassificationPerformanceKeys.map( (key) => performanceOptions[key] ); } if ( fairnessContext.modelMetadata.PredictionType === PredictionTypes.Regression ) { return this.props.supportedRegressionPerformanceKeys.map( (key) => performanceOptions[key] ); } return this.props.supportedProbabilityPerformanceKeys.map( (key) => performanceOptions[key] ); } private getFairnessMetrics( fairnessContext: IRunTimeFairnessContext ): IFairnessOption[] { return Object.values(fairnessOptions).filter((fairnessOption) => { return fairnessOption.supportedTasks.has( fairnessContext.modelMetadata.PredictionType ); }); } private readonly hideIntro = (): void => { this.setState({ showIntro: false }); }; private readonly setTab = (key: string): void => { this.setState({ activeTabKey: key }); }; private readonly onSelectModel = (data: any): void => { if (!data) { this.setState({ selectedModelId: undefined }); return; } if (data.points && data.points[0]) { this.setState({ selectedModelId: data.points[0].customdata.modelId }); } }; private readonly setPerformanceKey = (key: string): void => { const value: Partial<IWizardStateV2> = { selectedPerformanceKey: key }; if (flights.skipFairness) { value.selectedFairnessKey = key; } this.setState(value as IWizardStateV2); }; private readonly setFairnessKey = (key: string): void => { this.setState({ selectedFairnessKey: key }); }; private readonly setErrorBarsEnabled = (key: boolean): void => { this.setState({ errorBarsEnabled: key }); }; private readonly setBinIndex = (index: number): void => { if (this.props.precomputedMetrics) { const newContext = _.cloneDeep(this.state.dashboardContext); newContext.binVector = this.props.precomputedFeatureBins[index].binVector; newContext.groupNames = this.props.precomputedFeatureBins[index].binLabels; this.setState({ dashboardContext: newContext, selectedBinIndex: index }); } else { this.binningSet(this.state.featureBins[index]); } }; private readonly handleTabClick = (item?: PivotItem): void => { if (item?.props?.itemKey) { this.setState({ activeTabKey: item.props.itemKey }); } }; private readonly binningSet = (value: IBinnedResponse): void => { if (!value || value.hasError || value.array.length === 0) { return; } const newContext = _.cloneDeep(this.state.dashboardContext); newContext.binVector = WizardBuilder.generateBinVectorForBin( value, this.state.dashboardContext.dataset ); newContext.groupNames = value.labelArray; this.setState({ dashboardContext: newContext, selectedBinIndex: value.featureIndex }); }; private readonly saveBin = (bin: IBinnedResponse): void => { const newBin = [...this.state.featureBins]; newBin[bin.featureIndex] = bin; this.setState({ featureBins: newBin }); this.state.metricCache.clearCache(bin.featureIndex); this.binningSet(bin); }; private selectDefaultMetric( metrics: { [key: string]: any }, prioritization: string[] ): string | undefined { const keys = new Set(Object.values(metrics).map((metric) => metric.key)); for (const metricKey of prioritization) { if (keys.has(metricKey)) { return metricKey; } } // if none of the prioritized default metrics are available return first item return Object.values(metrics)[0]?.key; } }
the_stack
import { Mesh } from "../../Meshes/mesh"; import { Scene } from "../../scene"; import { Nullable } from "../../types"; import { Vector3, Quaternion, Matrix, TmpVectors } from "../../Maths/math.vector"; import { Observable, Observer } from "../../Misc/observable"; import { BaseSixDofDragBehavior } from "./baseSixDofDragBehavior"; import { TransformNode } from "../../Meshes/transformNode"; import { Space } from "../../Maths/math.axis"; /** * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray */ export class SixDofDragBehavior extends BaseSixDofDragBehavior { private _sceneRenderObserver: Nullable<Observer<Scene>> = null; private _virtualTransformNode: TransformNode; protected _targetPosition = new Vector3(0, 0, 0); protected _targetOrientation = new Quaternion(); protected _targetScaling = new Vector3(1, 1, 1); protected _startingPosition = new Vector3(0, 0, 0); protected _startingOrientation = new Quaternion(); protected _startingScaling = new Vector3(1, 1, 1); /** * Fires when position is updated */ public onPositionChangedObservable = new Observable<{ position: Vector3 }>(); /** * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) */ public dragDeltaRatio = 0.2; /** * If the object should rotate to face the drag origin */ public rotateDraggedObject = true; /** * If `rotateDraggedObject` is set to `true`, this parameter determines if we are only rotating around the y axis (yaw) */ public rotateAroundYOnly = false; /** * Should the behavior rotate 1:1 with the motion controller, when one is used. */ public rotateWithMotionController = true; /** * The name of the behavior */ public get name(): string { return "SixDofDrag"; } /** * Use this flag to update the target but not move the owner node towards the target */ public disableMovement: boolean = false; /** * Should the object rotate towards the camera when we start dragging it */ public faceCameraOnDragStart = false; /** * Attaches the six DoF drag behavior * @param ownerNode The mesh that will be dragged around once attached */ public attach(ownerNode: Mesh): void { super.attach(ownerNode); ownerNode.isNearGrabbable = true; // Node that will save the owner's transform this._virtualTransformNode = new TransformNode("virtual_sixDof", BaseSixDofDragBehavior._virtualScene); this._virtualTransformNode.rotationQuaternion = Quaternion.Identity(); // On every frame move towards target scaling to avoid jitter caused by vr controllers this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(() => { if (this.currentDraggingPointerIds.length === 1 && this._moving && !this.disableMovement) { // 1 pointer only drags mesh var oldParent = ownerNode.parent; ownerNode.setParent(null); ownerNode.position.addInPlace(this._targetPosition.subtract(ownerNode.position).scale(this.dragDeltaRatio)); this.onPositionChangedObservable.notifyObservers({ position: ownerNode.absolutePosition }); // Only rotate the mesh if it's parent has uniform scaling if (!oldParent || ((oldParent as Mesh).scaling && !(oldParent as Mesh).scaling.isNonUniformWithinEpsilon(0.001))) { Quaternion.SlerpToRef(ownerNode.rotationQuaternion!, this._targetOrientation, this.dragDeltaRatio, ownerNode.rotationQuaternion!); } ownerNode.setParent(oldParent); } }); } private _getPositionOffsetAround(transformationLocalOrigin: Vector3, scaling: number, rotation: Quaternion): Vector3 { const translationMatrix = TmpVectors.Matrix[0]; // T const translationMatrixInv = TmpVectors.Matrix[1]; // T' const rotationMatrix = TmpVectors.Matrix[2]; // R const scaleMatrix = TmpVectors.Matrix[3]; // S const finalMatrix = TmpVectors.Matrix[4]; // T' x R x S x T Matrix.TranslationToRef(transformationLocalOrigin.x, transformationLocalOrigin.y, transformationLocalOrigin.z, translationMatrix); // T Matrix.TranslationToRef(-transformationLocalOrigin.x, -transformationLocalOrigin.y, -transformationLocalOrigin.z, translationMatrixInv); // T' Matrix.FromQuaternionToRef(rotation, rotationMatrix); // R Matrix.ScalingToRef(scaling, scaling, scaling, scaleMatrix); translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R finalMatrix.multiplyToRef(scaleMatrix, finalMatrix); // T' x R x S finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x S x T return finalMatrix.getTranslation(); } private _onePointerPositionUpdated(worldDeltaPosition: Vector3, worldDeltaRotation: Quaternion) { let pointerDelta = TmpVectors.Vector3[0]; pointerDelta.setAll(0); if (this._dragging === this._dragType.DRAG) { if (this.rotateDraggedObject) { if (this.rotateAroundYOnly) { // Convert change in rotation to only y axis rotation Quaternion.RotationYawPitchRollToRef(worldDeltaRotation.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]); } else { TmpVectors.Quaternion[0].copyFrom(worldDeltaRotation); } TmpVectors.Quaternion[0].multiplyToRef(this._startingOrientation, this._targetOrientation); } } else if (this._dragging === this._dragType.NEAR_DRAG || (this._dragging === this._dragType.DRAG_WITH_CONTROLLER && this.rotateWithMotionController)) { worldDeltaRotation.multiplyToRef(this._startingOrientation, this._targetOrientation); } this._targetPosition.copyFrom(this._startingPosition).addInPlace(worldDeltaPosition); } private _twoPointersPositionUpdated() { const startingPosition0 = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition; const startingPosition1 = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition; const startingCenter = TmpVectors.Vector3[0]; startingPosition0.addToRef(startingPosition1, startingCenter); startingCenter.scaleInPlace(0.5); const startingVector = TmpVectors.Vector3[1]; startingPosition1.subtractToRef(startingPosition0, startingVector); const currentPosition0 = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition; const currentPosition1 = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition; const currentCenter = TmpVectors.Vector3[2]; currentPosition0.addToRef(currentPosition1, currentCenter); currentCenter.scaleInPlace(0.5); const currentVector = TmpVectors.Vector3[3]; currentPosition1.subtractToRef(currentPosition0, currentVector); const scaling = currentVector.length() / startingVector.length(); const translation = currentCenter.subtract(startingCenter); const rotationQuaternion = Quaternion.FromEulerAngles( 0, Vector3.GetAngleBetweenVectorsOnPlane(startingVector.normalize(), currentVector.normalize(), Vector3.UpReadOnly), 0 ); const oldParent = this._ownerNode.parent; this._ownerNode.setParent(null); const positionOffset = this._getPositionOffsetAround(startingCenter.subtract(this._virtualTransformNode.getAbsolutePivotPoint()), scaling, rotationQuaternion); this._virtualTransformNode.rotationQuaternion!.multiplyToRef(rotationQuaternion, this._ownerNode.rotationQuaternion!); this._virtualTransformNode.scaling.scaleToRef(scaling, this._ownerNode.scaling); this._virtualTransformNode.position.addToRef(translation.addInPlace(positionOffset), this._ownerNode.position); this.onPositionChangedObservable.notifyObservers({ position: this._ownerNode.position }); this._ownerNode.setParent(oldParent); } protected _targetDragStart() { const pointerCount = this.currentDraggingPointerIds.length; const oldParent = this._ownerNode.parent; if (!this._ownerNode.rotationQuaternion) { this._ownerNode.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._ownerNode.rotation.y, this._ownerNode.rotation.x, this._ownerNode.rotation.z); } const worldPivot = this._ownerNode.getAbsolutePivotPoint(); this._ownerNode.setParent(null); if (pointerCount === 1) { this._targetPosition.copyFrom(this._ownerNode.position); this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion); this._targetScaling.copyFrom(this._ownerNode.scaling); if (this.faceCameraOnDragStart && this._scene.activeCamera) { const toCamera = TmpVectors.Vector3[0]; this._scene.activeCamera.position.subtractToRef(worldPivot, toCamera); toCamera.normalize(); const quat = TmpVectors.Quaternion[0]; if (this._scene.useRightHandedSystem) { Quaternion.FromLookDirectionRHToRef(toCamera, new Vector3(0, 1, 0), quat); } else { Quaternion.FromLookDirectionLHToRef(toCamera, new Vector3(0, 1, 0), quat); } quat.normalize(); Quaternion.RotationYawPitchRollToRef(quat.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]); this._targetOrientation.copyFrom(TmpVectors.Quaternion[0]); } this._startingPosition.copyFrom(this._targetPosition); this._startingOrientation.copyFrom(this._targetOrientation); this._startingScaling.copyFrom(this._targetScaling); } else if (pointerCount === 2) { this._virtualTransformNode.setPivotPoint(new Vector3(0, 0, 0), Space.LOCAL); this._virtualTransformNode.position.copyFrom(this._ownerNode.position); this._virtualTransformNode.scaling.copyFrom(this._ownerNode.scaling); this._virtualTransformNode.rotationQuaternion!.copyFrom(this._ownerNode.rotationQuaternion); this._virtualTransformNode.setPivotPoint(worldPivot, Space.WORLD); this._resetVirtualMeshesPosition(); } this._ownerNode.setParent(oldParent); } protected _targetDrag(worldDeltaPosition: Vector3, worldDeltaRotation: Quaternion, pointerId: number) { if (this.currentDraggingPointerIds.length === 1) { this._onePointerPositionUpdated(worldDeltaPosition, worldDeltaRotation); } else if (this.currentDraggingPointerIds.length === 2) { this._twoPointersPositionUpdated(); } } protected _targetDragEnd() { if (this.currentDraggingPointerIds.length === 1) { // We still have 1 active pointer, we must simulate a dragstart with a reseted position/orientation this._resetVirtualMeshesPosition(); const previousFaceCameraFlag = this.faceCameraOnDragStart; this.faceCameraOnDragStart = false; this._targetDragStart(); this.faceCameraOnDragStart = previousFaceCameraFlag; } } /** * Detaches the behavior from the mesh */ public detach(): void { super.detach(); if (this._ownerNode) { (this._ownerNode as Mesh).isNearGrabbable = false; this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); } if (this._virtualTransformNode) { this._virtualTransformNode.dispose(); } } }
the_stack
import { bold, BufReader, BufWriter, delay, joinPath, yellow, } from "../deps.ts"; import { DeferredStack } from "../utils/deferred.ts"; import { getSocketName, readUInt32BE } from "../utils/utils.ts"; import { PacketWriter } from "./packet.ts"; import { Message, type Notice, parseBackendKeyMessage, parseCommandCompleteMessage, parseNoticeMessage, parseRowDataMessage, parseRowDescriptionMessage, } from "./message.ts"; import { type Query, QueryArrayResult, QueryObjectResult, type QueryResult, ResultType, } from "../query/query.ts"; import { type ClientConfiguration } from "./connection_params.ts"; import * as scram from "./scram.ts"; import { ConnectionError, ConnectionParamsError, PostgresError, } from "../client/error.ts"; import { AUTHENTICATION_TYPE, ERROR_MESSAGE, INCOMING_AUTHENTICATION_MESSAGES, INCOMING_QUERY_MESSAGES, INCOMING_TLS_MESSAGES, } from "./message_code.ts"; import { hashMd5Password } from "./auth.ts"; // Work around unstable limitation type ConnectOptions = | { hostname: string; port: number; transport: "tcp" } | { path: string; transport: "unix" }; function assertSuccessfulStartup(msg: Message) { switch (msg.type) { case ERROR_MESSAGE: throw new PostgresError(parseNoticeMessage(msg)); } } function assertSuccessfulAuthentication(auth_message: Message) { if (auth_message.type === ERROR_MESSAGE) { throw new PostgresError(parseNoticeMessage(auth_message)); } if ( auth_message.type !== INCOMING_AUTHENTICATION_MESSAGES.AUTHENTICATION ) { throw new Error(`Unexpected auth response: ${auth_message.type}.`); } const responseCode = auth_message.reader.readInt32(); if (responseCode !== 0) { throw new Error(`Unexpected auth response code: ${responseCode}.`); } } function logNotice(notice: Notice) { console.error(`${bold(yellow(notice.severity))}: ${notice.message}`); } const decoder = new TextDecoder(); const encoder = new TextEncoder(); // TODO // - Refactor properties to not be lazily initialized // or to handle their undefined value export class Connection { #bufReader!: BufReader; #bufWriter!: BufWriter; #conn!: Deno.Conn; connected = false; #connection_params: ClientConfiguration; #message_header = new Uint8Array(5); #onDisconnection: () => Promise<void>; #packetWriter = new PacketWriter(); #pid?: number; #queryLock: DeferredStack<undefined> = new DeferredStack( 1, [undefined], ); // TODO // Find out what the secret key is for #secretKey?: number; #tls?: boolean; #transport?: "tcp" | "socket"; get pid() { return this.#pid; } /** Indicates if the connection is carried over TLS */ get tls() { return this.#tls; } /** Indicates the connection protocol used */ get transport() { return this.#transport; } constructor( connection_params: ClientConfiguration, disconnection_callback: () => Promise<void>, ) { this.#connection_params = connection_params; this.#onDisconnection = disconnection_callback; } /** * Read single message sent by backend */ async #readMessage(): Promise<Message> { // Clear buffer before reading the message type this.#message_header.fill(0); await this.#bufReader.readFull(this.#message_header); const type = decoder.decode(this.#message_header.slice(0, 1)); // TODO // Investigate if the ascii terminator is the best way to check for a broken // session if (type === "\x00") { // This error means that the database terminated the session without notifying // the library // TODO // This will be removed once we move to async handling of messages by the frontend // However, unnotified disconnection will remain a possibility, that will likely // be handled in another place throw new ConnectionError("The session was terminated unexpectedly"); } const length = readUInt32BE(this.#message_header, 1) - 4; const body = new Uint8Array(length); await this.#bufReader.readFull(body); return new Message(type, length, body); } async #serverAcceptsTLS(): Promise<boolean> { const writer = this.#packetWriter; writer.clear(); writer .addInt32(8) .addInt32(80877103) .join(); await this.#bufWriter.write(writer.flush()); await this.#bufWriter.flush(); const response = new Uint8Array(1); await this.#conn.read(response); switch (String.fromCharCode(response[0])) { case INCOMING_TLS_MESSAGES.ACCEPTS_TLS: return true; case INCOMING_TLS_MESSAGES.NO_ACCEPTS_TLS: return false; default: throw new Error( `Could not check if server accepts SSL connections, server responded with: ${response}`, ); } } /** https://www.postgresql.org/docs/14/protocol-flow.html#id-1.10.5.7.3 */ async #sendStartupMessage(): Promise<Message> { const writer = this.#packetWriter; writer.clear(); // protocol version - 3.0, written as writer.addInt16(3).addInt16(0); // explicitly set utf-8 encoding writer.addCString("client_encoding").addCString("'utf-8'"); // TODO: recognize other parameters writer.addCString("user").addCString(this.#connection_params.user); writer.addCString("database").addCString(this.#connection_params.database); writer.addCString("application_name").addCString( this.#connection_params.applicationName, ); const connection_options = Object.entries(this.#connection_params.options); if (connection_options.length > 0) { // The database expects options in the --key=value writer.addCString("options").addCString( connection_options.map(([key, value]) => `--${key}=${value}`).join(" "), ); } // terminator after all parameters were writter writer.addCString(""); const bodyBuffer = writer.flush(); const bodyLength = bodyBuffer.length + 4; writer.clear(); const finalBuffer = writer .addInt32(bodyLength) .add(bodyBuffer) .join(); await this.#bufWriter.write(finalBuffer); await this.#bufWriter.flush(); return await this.#readMessage(); } async #openConnection(options: ConnectOptions) { // @ts-ignore This will throw in runtime if the options passed to it are socket related and deno is running // on stable this.#conn = await Deno.connect(options); this.#bufWriter = new BufWriter(this.#conn); this.#bufReader = new BufReader(this.#conn); } async #openSocketConnection(path: string, port: number) { if (Deno.build.os === "windows") { throw new Error( "Socket connection is only available on UNIX systems", ); } const socket = await Deno.stat(path); if (socket.isFile) { await this.#openConnection({ path, transport: "unix" }); } else { const socket_guess = joinPath(path, getSocketName(port)); try { await this.#openConnection({ path: socket_guess, transport: "unix", }); } catch (e) { if (e instanceof Deno.errors.NotFound) { throw new ConnectionError( `Could not open socket in path "${socket_guess}"`, ); } throw e; } } } async #openTlsConnection( connection: Deno.Conn, options: { hostname: string; caCerts: string[] }, ) { this.#conn = await Deno.startTls(connection, options); this.#bufWriter = new BufWriter(this.#conn); this.#bufReader = new BufReader(this.#conn); } #resetConnectionMetadata() { this.connected = false; this.#packetWriter = new PacketWriter(); this.#pid = undefined; this.#queryLock = new DeferredStack( 1, [undefined], ); this.#secretKey = undefined; this.#tls = undefined; this.#transport = undefined; } #closeConnection() { try { this.#conn.close(); } catch (_e) { // Swallow if the connection had errored or been closed beforehand } finally { this.#resetConnectionMetadata(); } } async #startup() { this.#closeConnection(); const { hostname, host_type, port, tls: { enabled: tls_enabled, enforce: tls_enforced, caCertificates, }, } = this.#connection_params; if (host_type === "socket") { await this.#openSocketConnection(hostname, port); this.#tls = undefined; this.#transport = "socket"; } else { // A BufWriter needs to be available in order to check if the server accepts TLS connections await this.#openConnection({ hostname, port, transport: "tcp" }); this.#tls = false; this.#transport = "tcp"; if (tls_enabled) { // If TLS is disabled, we don't even try to connect. const accepts_tls = await this.#serverAcceptsTLS() .catch((e) => { // Make sure to close the connection if the TLS validation throws this.#closeConnection(); throw e; }); // https://www.postgresql.org/docs/14/protocol-flow.html#id-1.10.5.7.11 if (accepts_tls) { try { await this.#openTlsConnection(this.#conn, { hostname, caCerts: caCertificates, }); this.#tls = true; } catch (e) { if (!tls_enforced) { console.error( bold(yellow("TLS connection failed with message: ")) + e.message + "\n" + bold("Defaulting to non-encrypted connection"), ); await this.#openConnection({ hostname, port, transport: "tcp" }); this.#tls = false; } else { throw e; } } } else if (tls_enforced) { // Make sure to close the connection before erroring this.#closeConnection(); throw new Error( "The server isn't accepting TLS connections. Change the client configuration so TLS configuration isn't required to connect", ); } } } try { let startup_response; try { startup_response = await this.#sendStartupMessage(); } catch (e) { // Make sure to close the connection before erroring or reseting this.#closeConnection(); if (e instanceof Deno.errors.InvalidData && tls_enabled) { if (tls_enforced) { throw new Error( "The certificate used to secure the TLS connection is invalid.", ); } else { console.error( bold(yellow("TLS connection failed with message: ")) + e.message + "\n" + bold("Defaulting to non-encrypted connection"), ); await this.#openConnection({ hostname, port, transport: "tcp" }); this.#tls = false; this.#transport = "tcp"; startup_response = await this.#sendStartupMessage(); } } else { throw e; } } assertSuccessfulStartup(startup_response); await this.#authenticate(startup_response); // Handle connection status // Process connection initialization messages until connection returns ready let message = await this.#readMessage(); while (message.type !== INCOMING_AUTHENTICATION_MESSAGES.READY) { switch (message.type) { // Connection error (wrong database or user) case ERROR_MESSAGE: await this.#processErrorUnsafe(message, false); break; case INCOMING_AUTHENTICATION_MESSAGES.BACKEND_KEY: { const { pid, secret_key } = parseBackendKeyMessage(message); this.#pid = pid; this.#secretKey = secret_key; break; } case INCOMING_AUTHENTICATION_MESSAGES.PARAMETER_STATUS: break; default: throw new Error(`Unknown response for startup: ${message.type}`); } message = await this.#readMessage(); } this.connected = true; } catch (e) { this.#closeConnection(); throw e; } } /** * Calling startup on a connection twice will create a new session and overwrite the previous one * * @param is_reconnection This indicates whether the startup should behave as if there was * a connection previously established, or if it should attempt to create a connection first * * https://www.postgresql.org/docs/14/protocol-flow.html#id-1.10.5.7.3 */ async startup(is_reconnection: boolean) { if (is_reconnection && this.#connection_params.connection.attempts === 0) { throw new Error( "The client has been disconnected from the database. Enable reconnection in the client to attempt reconnection after failure", ); } let reconnection_attempts = 0; const max_reconnections = this.#connection_params.connection.attempts; let error: Error | undefined; // If no connection has been established and the reconnection attempts are // set to zero, attempt to connect at least once if (!is_reconnection && this.#connection_params.connection.attempts === 0) { try { await this.#startup(); } catch (e) { error = e; } } else { let interval = typeof this.#connection_params.connection.interval === "number" ? this.#connection_params.connection.interval : 0; while (reconnection_attempts < max_reconnections) { // Don't wait for the interval on the first connection if (reconnection_attempts > 0) { if ( typeof this.#connection_params.connection.interval === "function" ) { interval = this.#connection_params.connection.interval(interval); } if (interval > 0) { await delay(interval); } } try { await this.#startup(); break; } catch (e) { // TODO // Eventually distinguish between connection errors and normal errors reconnection_attempts++; if (reconnection_attempts === max_reconnections) { error = e; } } } } if (error) { await this.end(); throw error; } } /** * Will attempt to authenticate with the database using the provided * password credentials */ async #authenticate(authentication_request: Message) { const authentication_type = authentication_request.reader.readInt32(); let authentication_result: Message; switch (authentication_type) { case AUTHENTICATION_TYPE.NO_AUTHENTICATION: authentication_result = authentication_request; break; case AUTHENTICATION_TYPE.CLEAR_TEXT: authentication_result = await this.#authenticateWithClearPassword(); break; case AUTHENTICATION_TYPE.MD5: { const salt = authentication_request.reader.readBytes(4); authentication_result = await this.#authenticateWithMd5(salt); break; } case AUTHENTICATION_TYPE.SCM: throw new Error( "Database server expected SCM authentication, which is not supported at the moment", ); case AUTHENTICATION_TYPE.GSS_STARTUP: throw new Error( "Database server expected GSS authentication, which is not supported at the moment", ); case AUTHENTICATION_TYPE.GSS_CONTINUE: throw new Error( "Database server expected GSS authentication, which is not supported at the moment", ); case AUTHENTICATION_TYPE.SSPI: throw new Error( "Database server expected SSPI authentication, which is not supported at the moment", ); case AUTHENTICATION_TYPE.SASL_STARTUP: authentication_result = await this.#authenticateWithSasl(); break; default: throw new Error(`Unknown auth message code ${authentication_type}`); } await assertSuccessfulAuthentication(authentication_result); } async #authenticateWithClearPassword(): Promise<Message> { this.#packetWriter.clear(); const password = this.#connection_params.password || ""; const buffer = this.#packetWriter.addCString(password).flush(0x70); await this.#bufWriter.write(buffer); await this.#bufWriter.flush(); return this.#readMessage(); } async #authenticateWithMd5(salt: Uint8Array): Promise<Message> { this.#packetWriter.clear(); if (!this.#connection_params.password) { throw new ConnectionParamsError( "Attempting MD5 authentication with unset password", ); } const password = await hashMd5Password( this.#connection_params.password, this.#connection_params.user, salt, ); const buffer = this.#packetWriter.addCString(password).flush(0x70); await this.#bufWriter.write(buffer); await this.#bufWriter.flush(); return this.#readMessage(); } /** * https://www.postgresql.org/docs/14/sasl-authentication.html */ async #authenticateWithSasl(): Promise<Message> { if (!this.#connection_params.password) { throw new ConnectionParamsError( "Attempting SASL auth with unset password", ); } const client = new scram.Client( this.#connection_params.user, this.#connection_params.password, ); const utf8 = new TextDecoder("utf-8"); // SASLInitialResponse const clientFirstMessage = client.composeChallenge(); this.#packetWriter.clear(); this.#packetWriter.addCString("SCRAM-SHA-256"); this.#packetWriter.addInt32(clientFirstMessage.length); this.#packetWriter.addString(clientFirstMessage); this.#bufWriter.write(this.#packetWriter.flush(0x70)); this.#bufWriter.flush(); const maybe_sasl_continue = await this.#readMessage(); switch (maybe_sasl_continue.type) { case INCOMING_AUTHENTICATION_MESSAGES.AUTHENTICATION: { const authentication_type = maybe_sasl_continue.reader.readInt32(); if (authentication_type !== AUTHENTICATION_TYPE.SASL_CONTINUE) { throw new Error( `Unexpected authentication type in SASL negotiation: ${authentication_type}`, ); } break; } case ERROR_MESSAGE: throw new PostgresError(parseNoticeMessage(maybe_sasl_continue)); default: throw new Error( `Unexpected message in SASL negotiation: ${maybe_sasl_continue.type}`, ); } const sasl_continue = utf8.decode( maybe_sasl_continue.reader.readAllBytes(), ); await client.receiveChallenge(sasl_continue); this.#packetWriter.clear(); this.#packetWriter.addString(await client.composeResponse()); this.#bufWriter.write(this.#packetWriter.flush(0x70)); this.#bufWriter.flush(); const maybe_sasl_final = await this.#readMessage(); switch (maybe_sasl_final.type) { case INCOMING_AUTHENTICATION_MESSAGES.AUTHENTICATION: { const authentication_type = maybe_sasl_final.reader.readInt32(); if (authentication_type !== AUTHENTICATION_TYPE.SASL_FINAL) { throw new Error( `Unexpected authentication type in SASL finalization: ${authentication_type}`, ); } break; } case ERROR_MESSAGE: throw new PostgresError(parseNoticeMessage(maybe_sasl_final)); default: throw new Error( `Unexpected message in SASL finalization: ${maybe_sasl_continue.type}`, ); } const sasl_final = utf8.decode( maybe_sasl_final.reader.readAllBytes(), ); await client.receiveResponse(sasl_final); // Return authentication result return this.#readMessage(); } async #simpleQuery( query: Query<ResultType.ARRAY>, ): Promise<QueryArrayResult>; async #simpleQuery( query: Query<ResultType.OBJECT>, ): Promise<QueryObjectResult>; async #simpleQuery( query: Query<ResultType>, ): Promise<QueryResult> { this.#packetWriter.clear(); const buffer = this.#packetWriter.addCString(query.text).flush(0x51); await this.#bufWriter.write(buffer); await this.#bufWriter.flush(); let result; if (query.result_type === ResultType.ARRAY) { result = new QueryArrayResult(query); } else { result = new QueryObjectResult(query); } let error: Error | undefined; let current_message = await this.#readMessage(); // Process messages until ready signal is sent // Delay error handling until after the ready signal is sent while (current_message.type !== INCOMING_QUERY_MESSAGES.READY) { switch (current_message.type) { case ERROR_MESSAGE: error = new PostgresError(parseNoticeMessage(current_message)); break; case INCOMING_QUERY_MESSAGES.COMMAND_COMPLETE: { result.handleCommandComplete( parseCommandCompleteMessage(current_message), ); break; } case INCOMING_QUERY_MESSAGES.DATA_ROW: { const row_data = parseRowDataMessage(current_message); try { result.insertRow(row_data); } catch (e) { error = e; } break; } case INCOMING_QUERY_MESSAGES.EMPTY_QUERY: break; case INCOMING_QUERY_MESSAGES.NOTICE_WARNING: { const notice = parseNoticeMessage(current_message); logNotice(notice); result.warnings.push(notice); break; } case INCOMING_QUERY_MESSAGES.PARAMETER_STATUS: break; case INCOMING_QUERY_MESSAGES.READY: break; case INCOMING_QUERY_MESSAGES.ROW_DESCRIPTION: { result.loadColumnDescriptions( parseRowDescriptionMessage(current_message), ); break; } default: throw new Error( `Unexpected simple query message: ${current_message.type}`, ); } current_message = await this.#readMessage(); } if (error) throw error; return result; } async #appendQueryToMessage<T extends ResultType>(query: Query<T>) { this.#packetWriter.clear(); const buffer = this.#packetWriter .addCString("") // TODO: handle named queries (config.name) .addCString(query.text) .addInt16(0) .flush(0x50); await this.#bufWriter.write(buffer); } async #appendArgumentsToMessage<T extends ResultType>( query: Query<T>, ) { this.#packetWriter.clear(); const hasBinaryArgs = query.args.some((arg) => arg instanceof Uint8Array); // bind statement this.#packetWriter.clear(); this.#packetWriter .addCString("") // TODO: unnamed portal .addCString(""); // TODO: unnamed prepared statement if (hasBinaryArgs) { this.#packetWriter.addInt16(query.args.length); query.args.forEach((arg) => { this.#packetWriter.addInt16(arg instanceof Uint8Array ? 1 : 0); }); } else { this.#packetWriter.addInt16(0); } this.#packetWriter.addInt16(query.args.length); query.args.forEach((arg) => { if (arg === null || typeof arg === "undefined") { this.#packetWriter.addInt32(-1); } else if (arg instanceof Uint8Array) { this.#packetWriter.addInt32(arg.length); this.#packetWriter.add(arg); } else { const byteLength = encoder.encode(arg).length; this.#packetWriter.addInt32(byteLength); this.#packetWriter.addString(arg); } }); this.#packetWriter.addInt16(0); const buffer = this.#packetWriter.flush(0x42); await this.#bufWriter.write(buffer); } /** * This function appends the query type (in this case prepared statement) * to the message */ async #appendDescribeToMessage() { this.#packetWriter.clear(); const buffer = this.#packetWriter.addCString("P").flush(0x44); await this.#bufWriter.write(buffer); } async #appendExecuteToMessage() { this.#packetWriter.clear(); const buffer = this.#packetWriter .addCString("") // unnamed portal .addInt32(0) .flush(0x45); await this.#bufWriter.write(buffer); } async #appendSyncToMessage() { this.#packetWriter.clear(); const buffer = this.#packetWriter.flush(0x53); await this.#bufWriter.write(buffer); } // TODO // Rename process function to a more meaningful name and move out of class async #processErrorUnsafe( msg: Message, recoverable = true, ) { const error = new PostgresError(parseNoticeMessage(msg)); if (recoverable) { let maybe_ready_message = await this.#readMessage(); while (maybe_ready_message.type !== INCOMING_QUERY_MESSAGES.READY) { maybe_ready_message = await this.#readMessage(); } } throw error; } /** * https://www.postgresql.org/docs/14/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY */ async #preparedQuery<T extends ResultType>( query: Query<T>, ): Promise<QueryResult> { // The parse messages declares the statement, query arguments and the cursor used in the transaction // The database will respond with a parse response await this.#appendQueryToMessage(query); await this.#appendArgumentsToMessage(query); // The describe message will specify the query type and the cursor in which the current query will be running // The database will respond with a bind response await this.#appendDescribeToMessage(); // The execute response contains the portal in which the query will be run and how many rows should it return await this.#appendExecuteToMessage(); await this.#appendSyncToMessage(); // send all messages to backend await this.#bufWriter.flush(); let result; if (query.result_type === ResultType.ARRAY) { result = new QueryArrayResult(query); } else { result = new QueryObjectResult(query); } let error: Error | undefined; let current_message = await this.#readMessage(); while (current_message.type !== INCOMING_QUERY_MESSAGES.READY) { switch (current_message.type) { case ERROR_MESSAGE: { error = new PostgresError(parseNoticeMessage(current_message)); break; } case INCOMING_QUERY_MESSAGES.BIND_COMPLETE: break; case INCOMING_QUERY_MESSAGES.COMMAND_COMPLETE: { result.handleCommandComplete( parseCommandCompleteMessage(current_message), ); break; } case INCOMING_QUERY_MESSAGES.DATA_ROW: { const row_data = parseRowDataMessage(current_message); try { result.insertRow(row_data); } catch (e) { error = e; } break; } case INCOMING_QUERY_MESSAGES.NO_DATA: break; case INCOMING_QUERY_MESSAGES.NOTICE_WARNING: { const notice = parseNoticeMessage(current_message); logNotice(notice); result.warnings.push(notice); break; } case INCOMING_QUERY_MESSAGES.PARAMETER_STATUS: break; case INCOMING_QUERY_MESSAGES.PARSE_COMPLETE: // TODO: add to already parsed queries if // query has name, so it's not parsed again break; case INCOMING_QUERY_MESSAGES.ROW_DESCRIPTION: { result.loadColumnDescriptions( parseRowDescriptionMessage(current_message), ); break; } default: throw new Error( `Unexpected prepared query message: ${current_message.type}`, ); } current_message = await this.#readMessage(); } if (error) throw error; return result; } async query( query: Query<ResultType.ARRAY>, ): Promise<QueryArrayResult>; async query( query: Query<ResultType.OBJECT>, ): Promise<QueryObjectResult>; async query( query: Query<ResultType>, ): Promise<QueryResult> { if (!this.connected) { await this.startup(true); } await this.#queryLock.pop(); try { if (query.args.length === 0) { return await this.#simpleQuery(query); } else { return await this.#preparedQuery(query); } } catch (e) { if (e instanceof ConnectionError) { await this.end(); } throw e; } finally { this.#queryLock.push(undefined); } } async end(): Promise<void> { if (this.connected) { const terminationMessage = new Uint8Array([0x58, 0x00, 0x00, 0x00, 0x04]); await this.#bufWriter.write(terminationMessage); try { await this.#bufWriter.flush(); } catch (_e) { // This steps can fail if the underlying connection was closed ungracefully } finally { this.#closeConnection(); this.#onDisconnection(); } } } }
the_stack
import { UxModalService, UxModalServiceResult } from './ux-modal-service'; import { customElement, bindable, useView } from 'aurelia-templating'; import { inject } from 'aurelia-dependency-injection'; import { StyleEngine, UxComponent } from '@aurelia-ux/core'; import { UxModalTheme } from './ux-modal-theme'; import { TaskQueue } from 'aurelia-framework'; import { PLATFORM, DOM } from 'aurelia-pal'; import { getLogger } from 'aurelia-logging'; import { UxModalPosition, UxModalKeybord, UxDefaultModalConfiguration } from './ux-modal-configuration'; const log = getLogger('ux-modal'); @inject(Element, StyleEngine, UxModalService, TaskQueue, UxDefaultModalConfiguration) @customElement('ux-modal') @useView(PLATFORM.moduleName('./ux-modal.html')) export class UxModal implements UxComponent { @bindable public position: UxModalPosition = 'center'; @bindable public host: 'body' | HTMLElement | false | string = 'body'; @bindable public modalBreakpoint: number = 768; @bindable public theme: UxModalTheme; @bindable public overlayDismiss: boolean = true; @bindable public outsideDismiss: boolean = true; @bindable public lock: boolean = true; @bindable public keyboard: UxModalKeybord = ['Escape']; @bindable public restoreFocus?: (lastActiveElement: HTMLElement) => void= (lastActiveElement: HTMLElement) => { lastActiveElement.focus(); } @bindable public openingCallback?: (contentWrapperElement?: HTMLElement, overlayElement?: HTMLElement) => void; // Aria attributes @bindable public role: 'dialog' | 'alertdialog' = 'dialog'; @bindable public ariaLabelledby: string = ''; @bindable public ariaDescribedby: string = ''; public lastActiveElement?: HTMLElement; private handlingEvent: boolean = false; public viewportType: 'mobile' | 'desktop' = 'desktop'; // Will be populated by `ref="...."` in template private overlayElement: HTMLElement; private contentWrapperElement: HTMLElement; public contentElement: HTMLElement; private showed: boolean = false; private showing: boolean = false; private hiding: boolean = false; private bindingContext: any; constructor( public element: HTMLElement, private styleEngine: StyleEngine, private modalService: UxModalService, private taskQueue: TaskQueue, private defaultConfig: UxDefaultModalConfiguration) { if (this.defaultConfig.modalBreakpoint !== undefined) { this.modalBreakpoint = this.defaultConfig.modalBreakpoint; } if (this.defaultConfig.host !== undefined) { this.host = this.defaultConfig.host; } if (this.defaultConfig.overlayDismiss !== undefined) { this.overlayDismiss = this.defaultConfig.overlayDismiss; } if (this.defaultConfig.outsideDismiss !== undefined) { this.outsideDismiss = this.defaultConfig.outsideDismiss; } if (this.defaultConfig.lock !== undefined) { this.lock = this.defaultConfig.lock; } if (this.defaultConfig.position !== undefined) { this.position = this.defaultConfig.position; } if (this.defaultConfig.keyboard !== undefined) { this.keyboard = this.defaultConfig.keyboard; } if (this.defaultConfig.theme !== undefined) { this.theme = this.defaultConfig.theme; } } public bind(bindingContext: any) { this.bindingContext = bindingContext; this.themeChanged(this.theme); this.setViewportType(); window.addEventListener('resize', this); this.positionChanged(); this.modalBreakpointChanged(); this.hostChanged(); this.overlayDismissChanged(); this.outsideDismissChanged(); this.lockChanged(); this.keyboardChanged(); } public positionChanged() { if (!this.position && this.defaultConfig.position) { this.position = this.defaultConfig.position; } } public modalBreakpointChanged() { if (typeof this.modalBreakpoint !== 'number' && this.defaultConfig.modalBreakpoint) { this.modalBreakpoint = this.defaultConfig.modalBreakpoint; } } public hostChanged() { if (this.host === false || this.host === 'body' || this.host instanceof HTMLElement) { return; } if (this.defaultConfig.host !== undefined) { this.host = this.defaultConfig.host; return; } if (this.host === '') { this.host = 'body'; } } public overlayDismissChanged() { if (!this.overlayDismiss && this.defaultConfig.overlayDismiss) { this.overlayDismiss = this.defaultConfig.overlayDismiss; } } public outsideDismissChanged() { if (!this.outsideDismiss && this.defaultConfig.outsideDismiss) { this.outsideDismiss = this.defaultConfig.outsideDismiss; } } public lockChanged() { if (!this.lock && this.defaultConfig.lock !== undefined) { this.lock = this.defaultConfig.lock; } this.setZindex(); } public keyboardChanged() { if (!this.keyboard && this.defaultConfig.keyboard) { this.keyboard = this.defaultConfig.keyboard; } } public attached() { if (this.host) { this.moveToHost(); } this.show(); } public detached() { if (this.host) { this.removeFromHost(); } } private show() { if (this.showing && this.showed) { return; } if (document.activeElement instanceof HTMLElement) { this.lastActiveElement = document.activeElement; } if (this.openingCallback) { this.openingCallback.call(this, this.contentWrapperElement, this.overlayElement); } this.showing = true; this.modalService.addLayer(this, this.bindingContext); this.setZindex(); // We rely on `queueTask()` here to make sure the // element is completely ready with all CSS set // before to set `showed = true` which will start // the CSS transition to bring the modal to the // screen this.taskQueue.queueTask(() => { this.showed = true; const duration = this.getAnimationDuration(); setTimeout(() => { this.showing = false; }, duration); }); } private async hide() { if (this.hiding || !this.showed) {return;} this.hiding = true; const duration = this.getAnimationDuration(); this.showed = false; return new Promise((resolve) => { setTimeout(() => { this.modalService.removeLayer(this); this.hiding = false; if (this.lastActiveElement && typeof this.restoreFocus === 'function') { this.restoreFocus(this.lastActiveElement); } resolve(); }, duration); }); } private setZindex() { if (this.overlayElement) { this.overlayElement.style.zIndex = `${this.modalService.zIndex}`; } this.contentWrapperElement.style.zIndex = `${this.modalService.zIndex}`; } private moveToHost() { const host = this.getHost(); if (!host) { return; } host.appendChild(this.element); } private removeFromHost() { // TODO: make sure we dont' need to bring back the element to its original position // before to remove it. Seems ok to keep it like this, but we decided to keep // an eye on it. See GH comment (18.04.2020 : https://github.com/aurelia/ux/pull/246#discussion_r410664303) const host = this.getHost(); if (!host) { return; } try { host.removeChild(this.element); } catch (e) { // if error, it's because the child is already removed } } private getHost(): Element | null { if (this.host === 'body') { return document.body; } else if (this.host instanceof HTMLElement) { return this.host; } else if (typeof this.host === 'string') { return document.querySelector(this.host); } return null; } public unbind() { window.removeEventListener('resize', this); } public handleEvent() { if (this.handlingEvent) { return; } this.handlingEvent = true; if (PLATFORM.global.requestAnimationFrame) { PLATFORM.global.requestAnimationFrame(() => { this.setViewportType(); this.handlingEvent = false; }); } else { setTimeout(() => { this.setViewportType(); this.handlingEvent = false; }, 100); } this.setViewportType(); } public themeChanged(newValue: any) { if (newValue != null && newValue.themeKey == null) { newValue.themeKey = 'modal'; } this.styleEngine.applyTheme(newValue, this.element); } public setViewportType() { this.viewportType = window.innerWidth < this.modalBreakpoint ? 'mobile' : 'desktop'; } public overlayClick(event: Event): any { for (const element of (event as any).composedPath() ) { if (element === this.contentElement) { return true; // this allow normal behvior when clicking on elements inside the modal } } if (!this.overlayDismiss) { event.stopPropagation(); return; } this.dismiss(); } public async dismiss(event?: Event) { if (event) { event.stopPropagation(); } if (this.showing) { return; } const result: UxModalServiceResult = { wasCancelled: true, output: undefined }; if (!await this.prepareClosing(result)) { return; } await this.hide(); const dismissEvent = DOM.createCustomEvent('dismiss', {bubbles: true}); this.element.dispatchEvent(dismissEvent); } public async ok(output?: any, event?: Event) { if (event) { event.stopPropagation(); } const result: UxModalServiceResult = { wasCancelled: false, output }; if (!await this.prepareClosing(result)) { return; } await this.hide(); const okEvent = DOM.createCustomEvent('ok', {bubbles: true, detail: result.output}); this.element.dispatchEvent(okEvent); } private async prepareClosing(result: UxModalServiceResult): Promise<boolean> { const layer = this.modalService.getLayer(this); if (layer) { if (!await this.modalService.callCanDeactivate(layer, result)) { return false; } try { await this.modalService.callDetached(layer); await this.modalService.callDeactivate(layer, result); } catch (error) { log.error(error); } } return true; } public stop(event: Event) { event.stopPropagation(); } private getAnimationDuration() { // In order to allow precise animation we allow different duration // value for animating the overlay and the drawer. In most cases it will // be the same value but we can imagine a fast overlay and slower modal // apearence for exemple // Because the duration is used to determine when we can safely assume the // modal appeared/disappeard, we only keep the maximum value. const overlayElementDuration: string = this.overlayElement ? window.getComputedStyle(this.overlayElement).transitionDuration || '0' : '0'; const contentDuration: string = window.getComputedStyle(this.contentElement).transitionDuration || '0'; // overlayElementDuration and contentDuration are string like '0.25s' return Math.max(parseFloat(overlayElementDuration), parseFloat(contentDuration)) * 1000; } }
the_stack
'use strict'; import * as dom5 from 'dom5'; import * as url from 'url'; import * as estree from 'estree'; import * as docs from './ast-utils/docs'; import {FileLoader} from './loader/file-loader'; import {importParse, ParsedImport, LocNode} from './ast-utils/import-parse'; import {jsParse} from './ast-utils/js-parse'; import {Resolver} from './loader/resolver'; import {NoopResolver} from './loader/noop-resolver'; import {StringResolver} from './loader/string-resolver'; import {FSResolver} from './loader/fs-resolver'; import {XHRResolver} from './loader/xhr-resolver'; import {ErrorSwallowingFSResolver} from './loader/error-swallowing-fs-resolver'; import {Descriptor, ElementDescriptor, FeatureDescriptor, BehaviorDescriptor} from './ast-utils/descriptors'; function reduceMetadata(m1:DocumentDescriptor, m2:DocumentDescriptor): DocumentDescriptor { return { elements: m1.elements.concat(m2.elements), features: m1.features.concat(m2.features), behaviors: m1.behaviors.concat(m2.behaviors), }; } var EMPTY_METADATA: DocumentDescriptor = {elements: [], features: [], behaviors: []}; /** * Package of a parsed JS script */ interface ParsedJS { ast: estree.Program; scriptElement: dom5.Node; } /** * The metadata for all features and elements defined in one document */ interface DocumentDescriptor { /** * The elements from the document. */ elements: ElementDescriptor[]; /** * The features from the document */ features: FeatureDescriptor[]; /** * The behaviors from the document */ behaviors: BehaviorDescriptor[]; href?: string; imports?: DocumentDescriptor[]; parsedScript?: estree.Program; html?: ParsedImport; } /** * The metadata of an entire HTML document, in promises. */ interface AnalyzedDocument { /** * The url of the document. */ href: string; /** * The parsed representation of the doc. Use the `ast` property to get * the full `parse5` ast. */ htmlLoaded: Promise<ParsedImport>; /** * Resolves to the list of this Document's transitive import dependencies. */ depsLoaded: Promise<string[]>; /** * The direct dependencies of the document. */ depHrefs: string[]; /** * Resolves to the list of this Document's import dependencies */ metadataLoaded: Promise<DocumentDescriptor>; } /** * Options for `Analyzer.analzye` */ interface LoadOptions { /** * Whether `annotate()` should be skipped. */ noAnnotations?: boolean; /** * Content to resolve `href` to instead of loading from the file system. */ content?: string; /** * Whether the generated descriptors should be cleaned of redundant data. */ clean?: boolean; /** * `xhr` to use XMLHttpRequest. * `fs` to use the local filesystem. * `permissive` to use the local filesystem and return empty files when a * path can't be found. * Default is `fs` in node and `xhr` in the browser. */ resolver?: string; /** * A predicate function that indicates which files should be ignored by * the loader. By default all files not located under the dirname * of `href` will be ignored. */ filter?: (path:string)=> boolean; /** * If resolver is 'xhr': * Type of object to be returned by the XHR. Defaults to 'text', * accepts 'document', 'arraybuffer', and 'json'. * responseType: string; */ responseType?: string; /** * If resolver is 'xhr': * If true, we'll set the `withCredentials` property on any XHRs made. * This is relevant for whether cross-domain requests include cookies. */ withCredentials?: boolean; } /** * An Error extended with location metadata. */ interface LocError extends Error{ location: {line: number; column: number}; ownerDocument: string; } /** * A database of Polymer metadata defined in HTML */ export class Analyzer { loader: FileLoader; /** * A list of all elements the `Analyzer` has metadata for. */ elements: ElementDescriptor[] = []; /** * A view into `elements`, keyed by tag name. */ elementsByTagName: {[tagName: string]: ElementDescriptor} = {}; /** * A list of API features added to `Polymer.Base` encountered by the * analyzer. */ features: FeatureDescriptor[] = []; /** * The behaviors collected by the analysis pass. */ behaviors: BehaviorDescriptor[] = []; /** * The behaviors collected by the analysis pass by name. */ behaviorsByName: {[name:string]: BehaviorDescriptor} = {}; /** * A map, keyed by absolute path, of Document metadata. */ html: {[path: string]: AnalyzedDocument} = {}; /** * A map, keyed by path, of HTML document ASTs. */ parsedDocuments: {[path:string]: dom5.Node} = {}; /** * A map, keyed by path, of JS script ASTs. * * If the path is an HTML file with multiple scripts, * the entry will be an array of scripts. */ parsedScripts: {[path:string]: ParsedJS[]} = {}; /** * A map, keyed by path, of document content. */ _content: {[path:string]: string} = {}; /** * @param {boolean} attachAST If true, attach a parse5 compliant AST * @param {FileLoader=} loader An optional `FileLoader` used to load external * resources */ constructor(attachAST:boolean, loader:FileLoader) { this.loader = loader; } /** * Shorthand for transitively loading and processing all imports beginning at * `href`. * * In order to properly filter paths, `href` _must_ be an absolute URI. * * @param {string} href The root import to begin loading from. * @param {LoadOptions=} options Any additional options for the load. * @return {Promise<Analyzer>} A promise that will resolve once `href` and its * dependencies have been loaded and analyzed. */ static analyze = function analyze(href:string, options?:LoadOptions) { options = options || {}; options.filter = options.filter || _defaultFilter(href); var loader = new FileLoader(); var resolver = options.resolver; if (resolver === undefined) { if (typeof window === 'undefined') { resolver = 'fs'; } else { resolver = 'xhr'; } } let primaryResolver: Resolver; if (resolver === 'fs') { primaryResolver = new FSResolver(options); } else if (resolver === 'xhr') { primaryResolver = new XHRResolver(options); } else if (resolver === 'permissive') { primaryResolver = new ErrorSwallowingFSResolver(options); } else { throw new Error("Resolver must be one of 'fs', 'xhr', or 'permissive'"); } loader.addResolver(primaryResolver); if (options.content) { loader.addResolver(new StringResolver({url: href, content: options.content})); } loader.addResolver(new NoopResolver({test: options.filter})); var analyzer = new Analyzer(false, loader); return analyzer.metadataTree(href).then((root) => { if (!options.noAnnotations) { analyzer.annotate(); } if (options.clean) { analyzer.clean(); } return Promise.resolve(analyzer); }); }; load(href: string):Promise<AnalyzedDocument> { return this.loader.request(href).then((content) => { return new Promise<AnalyzedDocument>((resolve, reject) => { setTimeout(() => { this._content[href] = content; resolve(this._parseHTML(content, href)); }, 0); }).catch(function(err){ console.error("Error processing document at " + href); throw err; }); }); }; /** * Returns an `AnalyzedDocument` representing the provided document * @private * @param {string} htmlImport Raw text of an HTML document * @param {string} href The document's URL. * @return {AnalyzedDocument} An `AnalyzedDocument` */ _parseHTML(htmlImport: string, href: string):AnalyzedDocument { if (href in this.html) { return this.html[href]; } var depsLoaded: Promise<Object>[] = []; var depHrefs: string[] = []; var metadataLoaded = Promise.resolve(EMPTY_METADATA); var parsed: ParsedImport; try { parsed = importParse(htmlImport, href); } catch (err) { console.error('Error parsing!'); throw err; } var htmlLoaded = Promise.resolve(parsed); if (parsed.script) { metadataLoaded = this._processScripts(parsed.script, href); } var commentText = parsed.comment.map(function(comment){ return dom5.getTextContent(comment); }); var pseudoElements = docs.parsePseudoElements(commentText); for (const element of pseudoElements) { element.contentHref = href; this.elements.push(element); if (element.is) { this.elementsByTagName[element.is] = element; } } metadataLoaded = metadataLoaded.then(function(metadata){ var metadataEntry: DocumentDescriptor = { elements: pseudoElements, features: [], behaviors: [] }; return [metadata, metadataEntry].reduce(reduceMetadata); }); depsLoaded.push(metadataLoaded); if (this.loader) { var baseUri = href; if (parsed.base.length > 1) { console.error("Only one base tag per document!"); throw "Multiple base tags in " + href; } else if (parsed.base.length == 1) { var baseHref = dom5.getAttribute(parsed.base[0], "href"); if (baseHref) { baseHref = baseHref + "/"; baseUri = url.resolve(baseUri, baseHref); } } for (const link of parsed.import) { var linkurl = dom5.getAttribute(link, 'href'); if (linkurl) { var resolvedUrl = url.resolve(baseUri, linkurl); depHrefs.push(resolvedUrl); depsLoaded.push(this._dependenciesLoadedFor(resolvedUrl, href)); } } for (const styleElement of parsed.style) { if (polymerExternalStyle(styleElement)) { var styleHref = dom5.getAttribute(styleElement, 'href'); if (href) { styleHref = url.resolve(baseUri, styleHref); depsLoaded.push(this.loader.request(styleHref).then((content) => { this._content[styleHref] = content; return {}; })); } } } } const depsStrLoaded = Promise.all(depsLoaded) .then(function() {return depHrefs;}) .catch(function(err) {throw err;}); this.parsedDocuments[href] = parsed.ast; this.html[href] = { href: href, htmlLoaded: htmlLoaded, metadataLoaded: metadataLoaded, depHrefs: depHrefs, depsLoaded: depsStrLoaded }; return this.html[href]; }; _processScripts(scripts: LocNode[], href: string) { var scriptPromises: Promise<DocumentDescriptor>[] = []; scripts.forEach((script) => { scriptPromises.push(this._processScript(script, href)); }); return Promise.all(scriptPromises).then(function(metadataList) { // TODO(ajo) remove this cast. var list: DocumentDescriptor[] = <any>metadataList; return list.reduce(reduceMetadata, EMPTY_METADATA); }); }; _processScript(script: LocNode, href: string):Promise<DocumentDescriptor> { const src = dom5.getAttribute(script, 'src'); var parsedJs: DocumentDescriptor; if (!src) { try { parsedJs = jsParse((script.childNodes.length) ? script.childNodes[0].value : ''); } catch (err) { // Figure out the correct line number for the error. var line = 0; var col = 0; if (script.__ownerDocument && script.__ownerDocument == href) { line = script.__locationDetail.line - 1; col = script.__locationDetail.column - 1; } line += err.lineNumber; col += err.column; var message = "Error parsing script in " + href + " at " + line + ":" + col; message += "\n" + err.stack; var fixedErr = <LocError>(new Error(message)); fixedErr.location = {line: line, column: col}; fixedErr.ownerDocument = script.__ownerDocument; return Promise.reject<DocumentDescriptor>(fixedErr); } if (parsedJs.elements) { parsedJs.elements.forEach((element) => { element.scriptElement = script; element.contentHref = href; this.elements.push(element); if (element.is in this.elementsByTagName) { console.warn('Ignoring duplicate element definition: ' + element.is); } else if (element.is) { this.elementsByTagName[element.is] = element; } }); } if (parsedJs.features) { parsedJs.features.forEach(function(feature){ feature.contentHref = href; feature.scriptElement = script; }); this.features = this.features.concat(parsedJs.features); } if (parsedJs.behaviors) { parsedJs.behaviors.forEach((behavior) => { behavior.contentHref = href; this.behaviorsByName[behavior.is] = behavior; this.behaviorsByName[behavior.symbol] = behavior; }); this.behaviors = this.behaviors.concat(parsedJs.behaviors); } if (!Object.hasOwnProperty.call(this.parsedScripts, href)) { this.parsedScripts[href] = []; } var scriptElement : LocNode; if (script.__ownerDocument && script.__ownerDocument == href) { scriptElement = script; } this.parsedScripts[href].push({ ast: parsedJs.parsedScript, scriptElement: scriptElement }); return Promise.resolve(parsedJs); } if (this.loader) { var resolvedSrc = url.resolve(href, src); return this.loader.request(resolvedSrc).then((content) => { this._content[resolvedSrc] = content; var scriptText = dom5.constructors.text(content); dom5.append(script, scriptText); dom5.removeAttribute(script, 'src'); script.__hydrolysisInlined = src; return this._processScript(script, resolvedSrc); }).catch(function(err) {throw err;}); } else { return Promise.resolve(EMPTY_METADATA); } }; _dependenciesLoadedFor(href: string, root: string) { var found: {[href: string]: boolean} = {}; if (root !== undefined) { found[root] = true; } return this._getDependencies(href, found).then((deps) => { var depPromises = deps.map((depHref) =>{ return this.load(depHref).then((htmlMonomer) => { return htmlMonomer.metadataLoaded; }); }); return Promise.all(depPromises); }); }; /** * List all the html dependencies for the document at `href`. * @param {string} href The href to get dependencies for. * @param {Object.<string,boolean>=} found An object keyed by URL of the * already resolved dependencies. * @param {boolean=} transitive Whether to load transitive * dependencies. Defaults to true. * @return {Array.<string>} A list of all the html dependencies. */ _getDependencies(href:string, found?:{[url:string]: boolean}, transitive?:boolean):Promise<string[]> { if (found === undefined) { found = {}; found[href] = true; } if (transitive === undefined) { transitive = true; } var deps: string[] = []; return this.load(href).then((htmlMonomer) => { var transitiveDeps: Promise<string[]>[] = []; htmlMonomer.depHrefs.forEach((depHref) => { if (found[depHref]) { return; } deps.push(depHref); found[depHref] = true; if (transitive) { transitiveDeps.push(this._getDependencies(depHref, found)); } }); return Promise.all(transitiveDeps); }).then(function(transitiveDeps) { var alldeps = transitiveDeps.reduce(function(a, b) { return a.concat(b); }, []).concat(deps); return alldeps; }); }; /** * Returns the elements defined in the folder containing `href`. * @param {string} href path to search. */ elementsForFolder(href: string): ElementDescriptor[] { return this.elements.filter(function(element){ return matchesDocumentFolder(element, href); }); }; /** * Returns the behaviors defined in the folder containing `href`. * @param {string} href path to search. * @return {Array.<BehaviorDescriptor>} */ behaviorsForFolder(href:string):BehaviorDescriptor[] { return this.behaviors.filter(function(behavior){ return matchesDocumentFolder(behavior, href); }); }; /** * Returns a promise that resolves to a POJO representation of the import * tree, in a format that maintains the ordering of the HTML imports spec. * @param {string} href the import to get metadata for. * @return {Promise} */ metadataTree(href:string) { return this.load(href).then((monomer) =>{ var loadedHrefs: {[href: string]: boolean} = {}; loadedHrefs[href] = true; return this._metadataTree(monomer, loadedHrefs); }); }; async _metadataTree(htmlMonomer:AnalyzedDocument, loadedHrefs: {[href: string]: boolean}) { if (loadedHrefs === undefined) { loadedHrefs = {}; } let metadata = await htmlMonomer.metadataLoaded; metadata = { elements: metadata.elements, features: metadata.features, behaviors: [], href: htmlMonomer.href }; const hrefs = await htmlMonomer.depsLoaded var depMetadata: Promise<DocumentDescriptor>[] = []; for (const href of hrefs) { let metadataPromise: Promise<DocumentDescriptor>; if (!loadedHrefs[href]) { loadedHrefs[href] = true; metadataPromise = this._metadataTree(this.html[href], loadedHrefs); await metadataPromise; } else { metadataPromise = Promise.resolve({}); } depMetadata.push(metadataPromise); } return Promise.all(depMetadata).then(function(importMetadata) { // TODO(ajo): remove this when tsc stops having issues. metadata.imports = <any>importMetadata; return htmlMonomer.htmlLoaded.then(function(parsedHtml) { metadata.html = parsedHtml; if (metadata.elements) { metadata.elements.forEach(function(element) { attachDomModule(parsedHtml, element); }); } return metadata; }); }); }; _inlineStyles(ast:dom5.Node, href: string) { var cssLinks = dom5.queryAll(ast, polymerExternalStyle); cssLinks.forEach((link) => { var linkHref = dom5.getAttribute(link, 'href'); var uri = url.resolve(href, linkHref); var content = this._content[uri]; var style = dom5.constructors.element('style'); dom5.setTextContent(style, '\n' + content + '\n'); dom5.replace(link, style); }); return cssLinks.length > 0; }; _inlineScripts(ast: dom5.Node, href: string) { var scripts = dom5.queryAll(ast, externalScript); scripts.forEach((script) => { var scriptHref = dom5.getAttribute(script, 'src'); var uri = url.resolve(href, scriptHref); var content = this._content[uri]; var inlined = dom5.constructors.element('script'); dom5.setTextContent(inlined, '\n' + content + '\n'); dom5.replace(script, inlined); }); return scripts.length > 0; }; _inlineImports(ast:dom5.Node, href:string, loaded:{[href:string]:boolean}) { var imports = dom5.queryAll(ast, isHtmlImportNode); imports.forEach((htmlImport) => { var importHref = dom5.getAttribute(htmlImport, 'href'); var uri = url.resolve(href, importHref); if (loaded[uri]) { dom5.remove(htmlImport); return; } var content = this.getLoadedAst(uri, loaded); dom5.replace(htmlImport, content); }); return imports.length > 0; }; /** * Returns a promise resolving to a form of the AST with all links replaced * with the document they link to. .css and .script files become &lt;style&gt; and * &lt;script&gt;, respectively. * * The elements in the loaded document are unmodified from their original * documents. * * @param {string} href The document to load. * @param {Object.<string,boolean>=} loaded An object keyed by already loaded documents. * @return {Promise.<DocumentAST>} */ getLoadedAst(href:string, loaded:{[href:string]:boolean}) { if (!loaded) { loaded = {}; } loaded[href] = true; var parsedDocument = this.parsedDocuments[href]; var analyzedDocument = this.html[href]; var astCopy = dom5.parse(dom5.serialize(parsedDocument)); // Whenever we inline something, reset inlined to true to know that anoather // inlining pass is needed; this._inlineStyles(astCopy, href); this._inlineScripts(astCopy, href); this._inlineImports(astCopy, href, loaded); return astCopy; }; /** * Calls `dom5.nodeWalkAll` on each document that `Anayzler` has laoded. */ nodeWalkDocuments(predicate:dom5.Predicate) { var results: dom5.Node[] = []; for (var href in this.parsedDocuments) { var newNodes = dom5.nodeWalkAll(this.parsedDocuments[href], predicate); results = results.concat(newNodes); } return results; }; /** * Calls `dom5.nodeWalkAll` on each document that `Anayzler` has laoded. * * TODO: make nodeWalkAll & nodeWalkAllDocuments distict, or delete one. */ nodeWalkAllDocuments(predicate:dom5.Predicate) { var results: dom5.Node[] = []; for (var href in this.parsedDocuments) { var newNodes = dom5.nodeWalkAll(this.parsedDocuments[href], predicate); results = results.concat(newNodes); } return results; }; /** Annotates all loaded metadata with its documentation. */ annotate() { if (this.features.length > 0) { var featureEl = docs.featureElement(this.features); this.elements.unshift(featureEl); if (featureEl.is) { this.elementsByTagName[featureEl.is] = featureEl; } } var behaviorsByName = this.behaviorsByName; var elementHelper = (descriptor: ElementDescriptor) => { docs.annotateElement(descriptor, behaviorsByName); }; this.elements.forEach(elementHelper); this.behaviors.forEach(elementHelper); // Same shape. this.behaviors.forEach((behavior) =>{ if (behavior.is !== behavior.symbol && behavior.symbol) { this.behaviorsByName[behavior.symbol] = undefined; } }); }; /** Removes redundant properties from the collected descriptors. */ clean() { this.elements.forEach(docs.cleanElement); }; }; /** * @private * @param {string} href * @return {function(string): boolean} */ function _defaultFilter(href:string) { // Everything up to the last `/` or `\`. var base = href.match(/^(.*?)[^\/\\]*$/)[1]; return function(uri:string) { return uri.indexOf(base) !== 0; }; } function matchesDocumentFolder(descriptor: ElementDescriptor, href: string) { if (!descriptor.contentHref) { return false; } var descriptorDoc = url.parse(descriptor.contentHref); if (!descriptorDoc || !descriptorDoc.pathname) { return false; } var searchDoc = url.parse(href); if (!searchDoc || !searchDoc.pathname) { return false; } var searchPath = searchDoc.pathname; var lastSlash = searchPath.lastIndexOf("/"); if (lastSlash > 0) { searchPath = searchPath.slice(0, lastSlash); } return descriptorDoc.pathname.indexOf(searchPath) === 0; } // TODO(ajo): Refactor out of vulcanize into dom5. var polymerExternalStyle = dom5.predicates.AND( dom5.predicates.hasTagName('link'), dom5.predicates.hasAttrValue('rel', 'import'), dom5.predicates.hasAttrValue('type', 'css') ); var externalScript = dom5.predicates.AND( dom5.predicates.hasTagName('script'), dom5.predicates.hasAttr('src') ); var isHtmlImportNode = dom5.predicates.AND( dom5.predicates.hasTagName('link'), dom5.predicates.hasAttrValue('rel', 'import'), dom5.predicates.NOT( dom5.predicates.hasAttrValue('type', 'css') ) ); function attachDomModule(parsedImport: ParsedImport, element: ElementDescriptor) { var domModules = parsedImport['dom-module']; for (const domModule of domModules) { if (dom5.getAttribute(domModule, 'id') === element.is) { element.domModule = domModule; return; } } }
the_stack
import { HttpStatus, INestApplication } from '@nestjs/common'; import { expect } from 'chai'; import request from 'supertest'; import { getAddress } from 'ethers/lib/utils'; import moment from 'moment'; import { DatabaseService } from '@energyweb/origin-backend-utils'; import { TestUser, bootstrapTestInstance, deviceManager } from './issuer-api'; import { CERTIFICATION_REQUESTS_TABLE_NAME } from '../src/pods/certification-request/certification-request.entity'; import { CERTIFICATES_TABLE_NAME } from '../src/pods/certificate/certificate.entity'; import { CertificationRequestDTO } from '../src/pods/certification-request'; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const certificationRequestTestData = { to: deviceManager.address, energy: '1000000', fromTime: moment().subtract(2, 'month').unix(), toTime: moment().subtract(1, 'month').unix(), deviceId: 'ABC-123', files: ['test.pdf', 'test2.pdf'] }; describe('Certification Request tests', () => { let app: INestApplication; let databaseService: DatabaseService; before(async () => { ({ databaseService, app } = await bootstrapTestInstance()); await app.init(); await databaseService.truncate(CERTIFICATION_REQUESTS_TABLE_NAME); await databaseService.truncate(CERTIFICATES_TABLE_NAME); }); afterEach(async () => { await databaseService.truncate(CERTIFICATION_REQUESTS_TABLE_NAME); await databaseService.truncate(CERTIFICATES_TABLE_NAME); }); after(async () => { await databaseService.cleanUp(); await app.close(); }); it('should return 400 BadRequest if "to" address is invalid', async () => { await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send({ ...certificationRequestTestData, to: 'invalid one' }) .expect(HttpStatus.BAD_REQUEST); }); [ certificationRequestTestData, { ...certificationRequestTestData, to: '0x0089d53f703f7e0843953d48133f74ce247184c2' }, { ...certificationRequestTestData, to: '0x7CB57B5A97EABE94205C07890BE4C1AD31E486A8' } ].forEach((certReqData) => { it(`should create a certification request + entry in the DB: ${certReqData.to}`, async () => { const { body: { deviceId, fromTime, toTime, created, owner, approved, revoked, files, energy } } = await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send(certReqData) .expect(HttpStatus.CREATED); expect(deviceId).to.equal(certReqData.deviceId); expect(fromTime).to.equal(certReqData.fromTime); expect(toTime).to.equal(certReqData.toTime); expect(created).to.be.null; expect(owner).to.equal(getAddress(certReqData.to)); expect(approved).to.be.false; expect(revoked).to.be.false; expect(JSON.stringify(files)).to.equal(JSON.stringify(certReqData.files)); expect(energy).to.equal(certReqData.energy); const { body: requests } = await request(app.getHttpServer()) .get(`/certification-request`) .set({ 'test-user': TestUser.OrganizationDeviceManager }) .expect(HttpStatus.OK); const cr = requests.find( (req: CertificationRequestDTO) => req.owner === getAddress(certReqData.to) ); expect(cr).to.be.not.empty; }); }); it('should not be able to request certification request twice for the same time period', async () => { await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send(certificationRequestTestData) .expect(HttpStatus.CREATED); await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send(certificationRequestTestData) .expect(HttpStatus.CONFLICT); }); it('should approve a certification request and a new certificate should be created', async () => { const { body: { id: certificationRequestId } } = await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send(certificationRequestTestData); // need to wait for item to be picked up from the queue and deployed await sleep(3000); const { body: { success } } = await request(app.getHttpServer()) .put(`/certification-request/${certificationRequestId}/approve`) .set({ 'test-user': TestUser.Issuer }) .expect(HttpStatus.OK); expect(success).to.be.true; const { body: { issuedCertificateId: newCertificateId } } = await request(app.getHttpServer()) .get(`/certification-request/${certificationRequestId}`) .set({ 'test-user': TestUser.OrganizationDeviceManager }) .expect(HttpStatus.OK); expect(newCertificateId).to.be.above(0); await sleep(3000); const { body: certificate } = await request(app.getHttpServer()) .get(`/certificate/${newCertificateId}`) .set({ 'test-user': TestUser.OrganizationDeviceManager }) .expect(HttpStatus.OK); expect(certificate.id).to.be.above(0); expect(certificate.deviceId).to.equal(certificationRequestTestData.deviceId); expect(certificate.generationStartTime).to.equal(certificationRequestTestData.fromTime); expect(certificate.generationEndTime).to.equal(certificationRequestTestData.toTime); expect(certificate.creationTime).to.be.above(1); expect(certificate.creationTransactionHash); expect(certificate.issuedPrivately).to.be.false; expect(certificate.isOwned).to.be.true; }); it('should revoke a certification request', async () => { const { body: { id: certificationRequestId } } = await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send(certificationRequestTestData) .expect(HttpStatus.CREATED); // need to wait for item to be picked up from the queue and deployed await sleep(3000); await request(app.getHttpServer()) .put(`/certification-request/${certificationRequestId}/revoke`) .set({ 'test-user': TestUser.Issuer }) .expect(HttpStatus.OK) .expect((res) => { expect(res.body.success).to.be.true; }); }); it('should fail to revoke a revoked certification request', async () => { let certificationRequestId; await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send(certificationRequestTestData) .expect((res) => { certificationRequestId = res.body.id; }); // need to wait for item to be picked up from the queue and deployed await sleep(3000); await request(app.getHttpServer()) .put(`/certification-request/${certificationRequestId}/revoke`) .set({ 'test-user': TestUser.Issuer }) .expect(HttpStatus.OK) .expect((res) => { expect(res.body.success).to.be.true; }); await request(app.getHttpServer()) .put(`/certification-request/${certificationRequestId}/revoke`) .set({ 'test-user': TestUser.Issuer }) .expect(HttpStatus.BAD_REQUEST); }); it('should create a private certification request', async () => { await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send({ ...certificationRequestTestData, isPrivate: true }) .expect(HttpStatus.CREATED) .expect((res) => { expect(res.body.isPrivate).to.be.true; }); }); // TO-DO: Check why this test fails. It doesn't fail when it is run with it.only(... xit('should approve a private certification request', async () => { const { body: { id: certificationRequestId, isPrivate } } = await request(app.getHttpServer()) .post('/certification-request') .set({ 'test-user': TestUser.OrganizationDeviceManager }) .send({ ...certificationRequestTestData, isPrivate: true }) .expect(HttpStatus.CREATED); // need to wait for item to be picked up from the queue and deployed await sleep(3000); expect(isPrivate).to.be.true; const { body: { success } } = await request(app.getHttpServer()) .put(`/certification-request/${certificationRequestId}/approve`) .set({ 'test-user': TestUser.Issuer }) .expect(HttpStatus.OK); expect(success).to.be.true; await sleep(10000); const { body: { issuedCertificateId: newCertificateId } } = await request(app.getHttpServer()) .get(`/certification-request/${certificationRequestId}`) .set({ 'test-user': TestUser.OrganizationDeviceManager }) .expect(HttpStatus.OK); const { body: certificate } = await request(app.getHttpServer()) .get(`/certificate/${newCertificateId}`) .set({ 'test-user': TestUser.OrganizationDeviceManager }) .expect(HttpStatus.OK); expect(certificate.issuedPrivately).to.be.true; expect(certificate.energy.privateVolume).to.equal(certificationRequestTestData.energy); }); });
the_stack
import { Component, OnInit } from '@angular/core'; import {MessageService, SelectItem, MenuItem, LazyLoadEvent} from 'primeng/api'; import {BrowserService} from './service/browser.service'; import Browser from './service/browser'; import MyBrowser from './service/mybrowser'; @Component({ selector: 'jhi-table', templateUrl: './tabledemo.component.html', styles: [` .new-version { background-color: #1CA979 !important; color: #ffffff !important; } .ui-grid-row div { padding: 4px 10px } .ui-grid-row div label { font-weight: bold; } /* Column Priorities */ @media only all { th.ui-p-6, td.ui-p-6, th.ui-p-5, td.ui-p-5, th.ui-p-4, td.ui-p-4, th.ui-p-3, td.ui-p-3, th.ui-p-2, td.ui-p-2, th.ui-p-1, td.ui-p-1 { display: none; } } /* Show priority 1 at 320px (20em x 16px) */ @media screen and (min-width: 20em) { th.ui-p-1, td.ui-p-1 { display: table-cell; } } /* Show priority 2 at 480px (30em x 16px) */ @media screen and (min-width: 30em) { th.ui-p-2, td.ui-p-2 { display: table-cell; } } /* Show priority 3 at 640px (40em x 16px) */ @media screen and (min-width: 40em) { th.ui-p-3, td.ui-p-3 { display: table-cell; } } /* Show priority 4 at 800px (50em x 16px) */ @media screen and (min-width: 50em) { th.ui-p-4, td.ui-p-4 { display: table-cell; } } /* Show priority 5 at 960px (60em x 16px) */ @media screen and (min-width: 60em) { th.ui-p-5, td.ui-p-5 { display: table-cell; } } /* Show priority 6 at 1,120px (70em x 16px) */ @media screen and (min-width: 70em) { th.ui-p-6, td.ui-p-6 { display: table-cell; } } `]}) export class TableDemoComponent implements OnInit { activeIndex = 0; browser: Browser; basicBrowsers: Browser[]; browsers: Browser[]; selectedBrowser: Browser; selectedBrowsers: Browser[]; displayDialog: boolean; stacked: boolean; newBrowser: boolean; totalRecords: number; engines: SelectItem[]; grades: SelectItem[]; expandedRows: any[]; cols: any[]; columnOptions: SelectItem[]; tableItems: MenuItem[]; selectedColumns: any[]; sortField: string; frozenBrowsers: Browser[]; frozenCols: any[]; scrollableCols: any[]; ratingFilter: number; loading: boolean; constructor(private browserService: BrowserService, private messageService: MessageService) { this.browser = new MyBrowser(); this.basicBrowsers = []; this.browsers = []; this.selectedBrowser = new MyBrowser(); this.selectedBrowsers = []; this.displayDialog = false; this.stacked = false; this.newBrowser = false; this.totalRecords = 100; this.engines = []; this.grades = []; this.expandedRows = []; this.cols = []; this.columnOptions = []; this.tableItems = []; this.selectedColumns = []; this.sortField = ''; this.frozenBrowsers = []; this.frozenCols = []; this.scrollableCols = []; this.ratingFilter = 0; this.loading = false; } ngOnInit(): void { this.browserService.getBrowsers().subscribe((browsers: any) => this.browsers = browsers.data); this.browserService.getBrowsers().subscribe((browsers: any) => this.basicBrowsers = browsers.data.slice(0, 10)); this.cols = [ {field: 'engine', header: 'Engine'}, {field: 'browser', header: 'Browser'}, {field: 'platform', header: 'Platform'}, {field: 'grade', header: 'Grade'} ]; this.columnOptions = []; for (const col of this.cols) { this.columnOptions.push({label: col.header, value: col}); } this.engines = []; this.engines.push({label: 'All engines', value: null}); this.engines.push({label: 'Trident', value: 'Trident'}); this.engines.push({label: 'Gecko', value: 'Gecko'}); this.engines.push({label: 'Webkit', value: 'Webkit'}); this.grades = []; this.grades.push({label: 'A', value: 'A'}); this.grades.push({label: 'B', value: 'B'}); this.grades.push({label: 'C', value: 'C'}); this.tableItems = [ { label: 'View', icon: 'pi pi-search', command: () => this.selectBrowser(this.selectedBrowser) }, { label: 'Delete', icon: 'pi pi-times', command: () => this.delete() } ]; this.selectedColumns = this.cols; this.frozenCols = [ { field: 'engine', header: 'Engine' }, { field: 'browser', header: 'Browser' } ]; this.frozenBrowsers = [ { "engine": "Trident", "browser": "Internet Explorer 4.0", "platform": "Win 95+", "version": 4, "code":"ie", "grade":"X" }, { "engine": "Gecko", "browser": "Firefox 1.5", "platform": "Win 98+ / OSX.2+", "version": 1.8, "code":"firefox", "grade":"A" } ]; this.scrollableCols = [ { field: 'engine', header: 'Engine' }, { field: 'browser', header: 'Browser' }, {field: 'platform', header: 'Platform'}, ]; } onRowClick(event: any): void { this.messageService.add({severity: 'info', summary: 'Browser clicked', detail: event.data.engine + ' - ' + event.data.browser}); } onRowDblClick(event: any): void { this.messageService.add({severity: 'info', summary: 'Browser double clicked', detail: event.data.engine + ' - ' + event.data.browser}); } onRowSelect(event: any): void { this.messageService.add({severity: 'info', summary: 'Type of selection:', detail: event.type}); this.messageService.add({severity: 'info', summary: 'Browser Selected', detail: event.data.engine + ' - ' + event.data.browser}); } onRowUnselect(event: any): void { this.messageService.add({severity: 'info', summary: 'Type of selection:', detail: event.type}); this.messageService.add({severity: 'info', summary: 'Browser Unselected', detail: event.data.engine + ' - ' + event.data.browser}); } onHeaderCheckboxToggle(event: any): void { this.messageService.add({severity: 'info', summary: 'Header checkbox toggled:', detail: event.checked}); } onContextMenuSelect(event: any): void { this.messageService.add({severity: 'info', summary: 'Selected data', detail: event.data.engine + ' - ' + event.data.browser}); } onColResize(event: any): void { this.messageService.add({severity: 'info', summary: 'Resized column header' + event.element, detail: 'Change of column width' + event.delta + 'px'}); } onColReorder(event: any): void { this.messageService.add({severity: 'info', summary: 'Index of dragged column', detail: event.dragIndex}); this.messageService.add({severity: 'info', summary: 'Index of dropped column', detail: event.dropIndex}); this.messageService.add({severity: 'info', summary: 'Columns array after reorder', detail: event.columns}); } onEditInit(event: any): void { this.messageService.add({severity: 'info', summary: 'Column is ', detail: event.column}); this.messageService.add({severity: 'info', summary: 'Row data', detail: event.data.engine + ' - ' + event.data.browser}); } onEdit(event: any): void { this.messageService.add({severity: 'info', summary: 'Row index', detail: event.index}); this.messageService.add({severity: 'info', summary: 'Column is ', detail: event.column}); this.messageService.add({severity: 'info', summary: 'Row data', detail: event.data.engine + ' - ' + event.data.browser}); } onEditComplete(event: any): void { this.messageService.add({severity: 'info', summary: 'Row index', detail: event.index}); this.messageService.add({severity: 'info', summary: 'Column is ', detail: event.column}); this.messageService.add({severity: 'info', summary: 'Row data', detail: event.data.engine + ' - ' + event.data.browser}); } onEditCancel(event: any): void { this.messageService.add({severity: 'info', summary: 'Row index', detail: event.index}); this.messageService.add({severity: 'info', summary: 'Column is ', detail: event.column}); this.messageService.add({severity: 'info', summary: 'Row data', detail: event.data.engine + ' - ' + event.data.browser}); } onPage(event: any): void { this.messageService.add({severity: 'info', summary: 'Index of first record:', detail: event.first}); this.messageService.add({severity: 'info', summary: 'Number of rows: ', detail: event.rows}); } onSort(event: any): void { this.sortField = event.field; } onFilter(event: any): void { this.messageService.add({severity: 'info', summary: 'Filter object(field,value and matchmode):', detail: event.filters}); } onRowExpand(event: any): void { this.messageService.add({severity: 'info', summary: 'Expanded row:', detail: event.data}); } onRowCollapse(event: any): void { this.messageService.add({severity: 'info', summary: 'Collapsed row:', detail: event.data}); } onRowGroupExpand(event: any): void { this.messageService.add({severity: 'info', summary: 'Row group expanded:', detail: event.group}); } onRowGroupCollapse(event: any): void { this.messageService.add({severity: 'info', summary: 'Row group collapsed:', detail: event.group}); } loadBrowsersLazy(event: LazyLoadEvent): void { // event.first = First row offset // event.rows = Number of rows per page // event.sortField = Field name to sort with // event.sortOrder = Sort order as number, 1 for asc and -1 for dec // filters: FilterMetadata object having field as key and filter value, filter matchMode as value this.loading = true; this.browserService.getBrowsers().subscribe((browsers: Browser[]) => { if (event.first && event.rows) { this.browsers = browsers.slice(event.first, (event.first + event.rows)); }}); this.loading = false; } addBrowser(): void { this.newBrowser = true; this.browser = new MyBrowser(); this.displayDialog = true; } save(): void { const browsers = [...this.browsers]; if (this.newBrowser) { browsers.push(this.browser); } else { browsers[this.findSelectedBrowserIndex()] = this.browser; } this.browsers = browsers; this.browser = {} as Browser; this.displayDialog = false; } delete(): void { const index = this.findSelectedBrowserIndex(); this.browsers = this.browsers.filter( (val, i) => i !== index); this.browser = {}; this.displayDialog = false; } onRowSelectCRUD(event: any): void { this.newBrowser = false; this.browser = Object.assign({}, event.data); this.displayDialog = true; } findSelectedBrowserIndex(): number { return this.browsers.indexOf(this.selectedBrowser); } selectBrowser(browser: Browser): void { this.messageService.add({severity: 'info', summary: 'Browser selected', detail: 'Browser: ' + browser.browser}); } toggle(): void { this.stacked = !this.stacked; } onChangeStep(label: string): void { this.messageService.add({severity: 'info', summary: label}); } }
the_stack
import { strict as assert } from "assert"; import { Random } from "best-random"; import { IChannelServices } from "@fluidframework/datastore-definitions"; import { MockFluidDataStoreRuntime, MockStorage, MockContainerRuntimeFactoryForReconnection, MockContainerRuntimeForReconnection, } from "@fluidframework/test-runtime-utils"; import { SharedMatrix, SharedMatrixFactory } from ".."; import { extract, expectSize } from "./utils"; describe("Matrix", () => { describe("stress", () => { let containerRuntimeFactory: MockContainerRuntimeFactoryForReconnection; let matrices: SharedMatrix[]; // Array of matrices under test let runtimes: MockContainerRuntimeForReconnection[] = []; let trace: string[]; // Repro steps to be printed if a failure is encountered. /** * Drains the queue of pending ops for each client and vets that all matrices converged on the same state. */ const expect = async () => { // Reconnect any disconnected clients before processing pending ops. for (let matrixIndex = 0; matrixIndex < runtimes.length; matrixIndex++) { const runtime = runtimes[matrixIndex]; if (!runtime.connected) { trace?.push(`containerRuntime${matrixIndex + 1}.connected = true;`); runtime.connected = true; } } // Broadcast and process all pending messages across all matrices. trace?.push("await expect();"); containerRuntimeFactory.processAllMessages(); // Verify that all matrices have converged on the same final state. const matrix0 = matrices[0]; const actual0 = extract(matrix0); for (let i = 1; i < matrices.length; i++) { const matrixN = matrices[i]; const actualN = extract(matrixN); assert.deepEqual(actual0, actualN); // Vet that empty matrices have identical dimensions (see notes on `expectSize`). expectSize(matrixN, matrix0.rowCount, matrix0.colCount); } }; /** * Performs a stress run using the given parameters. * * 'syncProbability' is the probability that the clients will drain their queue of incoming messages * and check for convergence. * * 'disconnectProbability' is the probability that a client will disconnect, forcing it to regenerate * and resubmit any pending local operations on the next sync. * * 'seed' is the 32-bit integer used to seed the PRNG. */ async function stress(numClients: number, numOps: number, syncProbability: number, disconnectProbability: number, seed: number) { try { matrices = []; runtimes = []; trace = []; containerRuntimeFactory = new MockContainerRuntimeFactoryForReconnection(); // Create matrices for this stress run. for (let i = 0; i < numClients; i++) { const dataStoreRuntimeN = new MockFluidDataStoreRuntime(); const containerRuntimeN = containerRuntimeFactory.createContainerRuntime(dataStoreRuntimeN); const servicesN: IChannelServices = { deltaConnection: containerRuntimeN.createDeltaConnection(), objectStorage: new MockStorage(), }; const matrixN = new SharedMatrix(dataStoreRuntimeN, `matrix-${i}`, SharedMatrixFactory.Attributes); matrixN.connect(servicesN); matrices.push(matrixN); runtimes.push(containerRuntimeN); } const matrix0 = matrices[0]; // Initialize PRNG with given seed. // eslint-disable-next-line @typescript-eslint/unbound-method const float64 = new Random(seed).float64; // Returns a pseudorandom 32b integer in the range [0 .. max). // eslint-disable-next-line no-bitwise const int32 = (max = 0x7FFFFFFF) => (float64() * max) | 0; // Returns an array with 'n' random values, each in the range [0 .. 100). const values = (n: number) => new Array(n) .fill(0) .map(() => int32(100)); // Invokes 'setCells()' on the matrix w/the given index and logs the command to the trace. const setCells = (matrixIndex: number, row: number, col: number, colCount: number, values: any[]) => { const matrix = matrices[matrixIndex]; // eslint-disable-next-line max-len trace?.push(`matrix${matrixIndex + 1}.setCells(/* row: */ ${row}, /* col: */ ${col}, /* colCount: */ ${colCount}, ${JSON.stringify(values)}); // rowCount: ${matrix.rowCount} colCount: ${matrix.colCount} stride: ${matrix.colCount} length: ${values.length}`); matrix.setCells(row, col, colCount, values); }; // Initialize with [0..5] row and [0..5] cols, filling the cells. { const rowCount = int32(5); if (rowCount > 0) { // eslint-disable-next-line max-len trace?.push(`matrix1.insertRows(/* rowStart: */ 0, /* rowCount: */ ${rowCount}); // rowCount: ${matrix0.rowCount}, colCount: ${matrix0.colCount}`); matrix0.insertRows(0, rowCount); } const colCount = int32(5); if (colCount > 0) { // eslint-disable-next-line max-len trace?.push(`matrix1.insertCols(/* colStart: */ 0, /* colCount: */ ${colCount}); // rowCount: ${matrix0.rowCount}, colCount: ${matrix0.colCount}`); matrix0.insertCols(0, colCount); } if (colCount > 0 && rowCount > 0) { setCells(/* matrixIndex: */ 0, /* row: */ 0, /* col: */ 0, colCount, new Array(colCount * rowCount).fill(0).map((_, index) => index)); } } // Loop for the prescribed number of iterations, randomly mutating one of matrices with one // of the following operations: // // * insert or remove rows // * insert or remove cols // * set a range of cells // // Following each operation, there is a `syncProbability` chance that clients will exchange // ops and vet convergence. for (let i = 0; i < numOps; i++) { // Choose a client to perform the operation. const matrixIndex = int32(matrices.length); const matrix = matrices[matrixIndex]; const { rowCount, colCount } = matrix; const row = int32(rowCount); const col = int32(colCount); switch(int32(7)) { case 0: { // remove 1 or more rows (if any exist) if (rowCount > 0) { // 10% probability of removing multiple rows. const numRemoved = float64() < 0.1 ? int32(rowCount - row - 1) + 1 : 1; // eslint-disable-next-line max-len trace?.push(`matrix${matrixIndex + 1}.removeRows(/* rowStart: */ ${row}, /* rowCount: */ ${numRemoved}); // rowCount: ${matrix.rowCount - numRemoved}, colCount: ${matrix.colCount}`); matrix.removeRows(row, numRemoved); } break; } case 1: { // remove 1 or more cols (if any exist) if (colCount > 0) { // 10% probability of removing multiple cols. const numRemoved = float64() < 0.1 ? int32(colCount - col - 1) + 1 : 1; // eslint-disable-next-line max-len trace?.push(`matrix${matrixIndex + 1}.removeCols(/* colStart: */ ${col}, /* colCount: */ ${numRemoved}); // rowCount: ${matrix.rowCount}, colCount: ${matrix.colCount - numRemoved}`); matrix.removeCols(col, numRemoved); } break; } case 2: { // insert 1 or more rows (20% probability of inserting 2-4 rows). const numInserted = float64() < 0.2 ? int32(3) + 1 : 1; // eslint-disable-next-line max-len trace?.push(`matrix${matrixIndex + 1}.insertRows(/* rowStart: */ ${row}, /* rowCount: */ ${numInserted}); // rowCount: ${matrix.rowCount + numInserted}, colCount: ${matrix.colCount}`); matrix.insertRows(row, numInserted); // 90% probability of filling the newly inserted row with values. if (float64() < 0.9) { if (colCount > 0) { setCells(matrixIndex, row, /* col: */ 0, matrix.colCount, values(matrix.colCount * numInserted)); } } break; } case 3: { // insert 1 or more cols (20% probability of inserting 2-4 cols). const numInserted = float64() < 0.2 ? int32(3) + 1 : 1; // eslint-disable-next-line max-len trace?.push(`matrix${matrixIndex + 1}.insertCols(/* colStart: */ ${col}, /* colCount: */ ${numInserted}); // rowCount: ${matrix.rowCount}, colCount: ${matrix.colCount + numInserted}`); matrix.insertCols(col, numInserted); // 90% probability of filling the newly inserted col with values. if (float64() < 0.9) { if (rowCount > 0) { setCells(matrixIndex, /* row: */ 0, col, numInserted, values(matrix.rowCount * numInserted)); } } break; } default: { // set a range of cells (if matrix is non-empty) if (rowCount > 0 && colCount > 0) { const stride = int32(colCount - col - 1) + 1; const length = (int32(rowCount - row - 1) + 1) * stride; setCells(matrixIndex, row, col, stride, values(length)); } break; } } if (float64() < disconnectProbability) { // If the client is already disconnected, first reconnect it to cover the case where // multiple reconnections are required. if (!runtimes[matrixIndex].connected) { trace?.push(`containerRuntime${matrixIndex + 1}.connected = true;`); runtimes[matrixIndex].connected = true; } trace?.push(`containerRuntime${matrixIndex + 1}.connected = false;`); runtimes[matrixIndex].connected = false; } // Clients periodically exchanging ops, at which point we verify they have converged // on the same state. if (float64() < syncProbability) { await expect(); } } // Test is finished. Drain pending ops and vet that clients converged. await expect(); } catch (error) { // If an error occurs, dump the repro instructions. for (const s of trace) { console.log(s); } // Also dump the current state of the matrices. for (const m of matrices) { console.log(m.toString()); } // Finally, rethrow the original error. throw error; } } for (const { numClients, numOps, syncProbability, disconnectProbability, seed } of [ { numClients: 2, numOps: 200, syncProbability: 0.3, disconnectProbability: 0, seed: 0x84d43a0a }, { numClients: 3, numOps: 200, syncProbability: 0.1, disconnectProbability: 0, seed: 0x655c763b }, { numClients: 5, numOps: 200, syncProbability: 0.0, disconnectProbability: 0, seed: 0x2f98736d }, { numClients: 2, numOps: 200, syncProbability: 0.2, disconnectProbability: 0.4, seed: 0x84d43a0a }, ]) { // eslint-disable-next-line max-len it(`Stress (numClients=${numClients} numOps=${numOps} syncProbability=${syncProbability} disconnectProbability=${disconnectProbability} seed=0x${seed.toString(16).padStart(8, "0")})`, // Note: Must use 'function' rather than arrow '() => { .. }' in order to set 'this.timeout(..)' async function() { this.timeout(20000); await stress(numClients, numOps, syncProbability, disconnectProbability, seed); }, ); } it("stress-loop", // Note: Must use 'function' rather than arrow '() => { .. }' in order to set 'this.timeout(..)' async function() { this.timeout(0); // Disable timeouts for stress loop let iterations = 0; const start = Date.now(); // eslint-disable-next-line no-constant-condition while (true) { await stress( /* numClients: */ 3, /* numOps: */ 10000, /* syncProbability: */ 0.1, /* disconnectProbability: */ 0.01, // eslint-disable-next-line no-bitwise /* seed: */ (Math.random() * 0x100000000) >>> 0, ); // Note: Mocha reporter intercepts 'console.log()' so use 'process.stdout.write' instead. process.stdout.write(matrices[0].toString()); process.stdout.write( `Stress loop: ${++iterations} iterations completed - Total Elapsed: ${ ((Date.now() - start) / 1000).toFixed(2) }s\n`); } }, ); }); });
the_stack
import { expect } from '../../../setup' /* External Imports */ import { ethers } from 'hardhat' import { Signer, ContractFactory, Contract, constants } from 'ethers' import { Interface } from 'ethers/lib/utils' import { smockit, MockContract, smoddit } from '@eth-optimism/smock' /* Internal Imports */ import { NON_NULL_BYTES32, NON_ZERO_ADDRESS } from '../../../helpers' import { getContractInterface, predeploys } from '../../../../src' const ERR_INVALID_MESSENGER = 'OVM_XCHAIN: messenger contract unauthenticated' const ERR_INVALID_X_DOMAIN_MSG_SENDER = 'OVM_XCHAIN: wrong sender of cross-domain message' const ERR_ALREADY_INITIALIZED = 'Contract has already been initialized.' const DUMMY_L2_ERC20_ADDRESS = ethers.utils.getAddress('0x' + 'abba'.repeat(10)) const DUMMY_L2_BRIDGE_ADDRESS = ethers.utils.getAddress( '0x' + 'acdc'.repeat(10) ) const INITIAL_TOTAL_L1_SUPPLY = 5000 const FINALIZATION_GAS = 1_200_000 describe('L1StandardBridge', () => { // init signers let l1MessengerImpersonator: Signer let alice: Signer let bob: Signer let bobsAddress let aliceAddress // we can just make up this string since it's on the "other" Layer let Factory__L1ERC20: ContractFactory let IL2ERC20Bridge: Interface before(async () => { ;[l1MessengerImpersonator, alice, bob] = await ethers.getSigners() await smockit(await ethers.getContractFactory('OVM_ETH')) // deploy an ERC20 contract on L1 Factory__L1ERC20 = await smoddit( '@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20' ) // get an L2ER20Bridge Interface IL2ERC20Bridge = getContractInterface('IL2ERC20Bridge') aliceAddress = await alice.getAddress() bobsAddress = await bob.getAddress() }) let L1ERC20: Contract let L1StandardBridge: Contract let Mock__L1CrossDomainMessenger: MockContract beforeEach(async () => { // Get a new mock L1 messenger Mock__L1CrossDomainMessenger = await smockit( await ethers.getContractFactory('L1CrossDomainMessenger'), { address: await l1MessengerImpersonator.getAddress() } // This allows us to use an ethers override {from: Mock__L2CrossDomainMessenger.address} to mock calls ) // Deploy the contract under test L1StandardBridge = await ( await ethers.getContractFactory('L1StandardBridge') ).deploy() await L1StandardBridge.initialize( Mock__L1CrossDomainMessenger.address, DUMMY_L2_BRIDGE_ADDRESS ) L1ERC20 = await Factory__L1ERC20.deploy('L1ERC20', 'ERC') await L1ERC20.smodify.put({ _totalSupply: INITIAL_TOTAL_L1_SUPPLY, _balances: { [aliceAddress]: INITIAL_TOTAL_L1_SUPPLY, }, }) }) describe('initialize', () => { it('Should only be callable once', async () => { await expect( L1StandardBridge.initialize( ethers.constants.AddressZero, DUMMY_L2_BRIDGE_ADDRESS ) ).to.be.revertedWith(ERR_ALREADY_INITIALIZED) }) }) describe('ETH deposits', () => { const depositAmount = 1_000 it('depositETH() escrows the deposit amount and sends the correct deposit message', async () => { const depositer = await alice.getAddress() const initialBalance = await ethers.provider.getBalance(depositer) // alice calls deposit on the bridge and the L1 bridge calls transferFrom on the token const res = await L1StandardBridge.connect(alice).depositETH( FINALIZATION_GAS, NON_NULL_BYTES32, { value: depositAmount, } ) const depositCallToMessenger = Mock__L1CrossDomainMessenger.smocked.sendMessage.calls[0] const depositerBalance = await ethers.provider.getBalance(depositer) const receipt = await res.wait() const depositerFeePaid = receipt.cumulativeGasUsed.mul( receipt.effectiveGasPrice ) expect(depositerBalance).to.equal( initialBalance.sub(depositAmount).sub(depositerFeePaid) ) // bridge's balance is increased const bridgeBalance = await ethers.provider.getBalance( L1StandardBridge.address ) expect(bridgeBalance).to.equal(depositAmount) // Check the correct cross-chain call was sent: // Message should be sent to the L2 bridge expect(depositCallToMessenger._target).to.equal(DUMMY_L2_BRIDGE_ADDRESS) // Message data should be a call telling the L2ETHToken to finalize the deposit // the L1 bridge sends the correct message to the L1 messenger expect(depositCallToMessenger._message).to.equal( IL2ERC20Bridge.encodeFunctionData('finalizeDeposit', [ constants.AddressZero, predeploys.OVM_ETH, depositer, depositer, depositAmount, NON_NULL_BYTES32, ]) ) expect(depositCallToMessenger._gasLimit).to.equal(FINALIZATION_GAS) }) it('depositETHTo() escrows the deposit amount and sends the correct deposit message', async () => { // depositor calls deposit on the bridge and the L1 bridge calls transferFrom on the token const initialBalance = await ethers.provider.getBalance(aliceAddress) const res = await L1StandardBridge.connect(alice).depositETHTo( bobsAddress, FINALIZATION_GAS, NON_NULL_BYTES32, { value: depositAmount, } ) const depositCallToMessenger = Mock__L1CrossDomainMessenger.smocked.sendMessage.calls[0] const depositerBalance = await ethers.provider.getBalance(aliceAddress) const receipt = await res.wait() const depositerFeePaid = receipt.cumulativeGasUsed.mul( receipt.effectiveGasPrice ) expect(depositerBalance).to.equal( initialBalance.sub(depositAmount).sub(depositerFeePaid) ) // bridge's balance is increased const bridgeBalance = await ethers.provider.getBalance( L1StandardBridge.address ) expect(bridgeBalance).to.equal(depositAmount) // Check the correct cross-chain call was sent: // Message should be sent to the L2 bridge expect(depositCallToMessenger._target).to.equal(DUMMY_L2_BRIDGE_ADDRESS) // Message data should be a call telling the L2ETHToken to finalize the deposit // the L1 bridge sends the correct message to the L1 messenger expect(depositCallToMessenger._message).to.equal( IL2ERC20Bridge.encodeFunctionData('finalizeDeposit', [ constants.AddressZero, predeploys.OVM_ETH, aliceAddress, bobsAddress, depositAmount, NON_NULL_BYTES32, ]) ) expect(depositCallToMessenger._gasLimit).to.equal(FINALIZATION_GAS) }) it('cannot depositETH from a contract account', async () => { expect( L1StandardBridge.depositETH(FINALIZATION_GAS, NON_NULL_BYTES32, { value: depositAmount, }) ).to.be.revertedWith('Account not EOA') }) }) describe('ETH withdrawals', () => { it('onlyFromCrossDomainAccount: should revert on calls from a non-crossDomainMessenger L1 account', async () => { // Deploy new bridge, initialize with random messenger await expect( L1StandardBridge.connect(alice).finalizeETHWithdrawal( constants.AddressZero, constants.AddressZero, 1, NON_NULL_BYTES32, { from: aliceAddress, } ) ).to.be.revertedWith(ERR_INVALID_MESSENGER) }) it('onlyFromCrossDomainAccount: should revert on calls from the right crossDomainMessenger, but wrong xDomainMessageSender (ie. not the L2ETHToken)', async () => { L1StandardBridge = await ( await ethers.getContractFactory('L1StandardBridge') ).deploy() await L1StandardBridge.initialize( Mock__L1CrossDomainMessenger.address, DUMMY_L2_BRIDGE_ADDRESS ) Mock__L1CrossDomainMessenger.smocked.xDomainMessageSender.will.return.with( '0x' + '22'.repeat(20) ) await expect( L1StandardBridge.finalizeETHWithdrawal( constants.AddressZero, constants.AddressZero, 1, NON_NULL_BYTES32, { from: Mock__L1CrossDomainMessenger.address, } ) ).to.be.revertedWith(ERR_INVALID_X_DOMAIN_MSG_SENDER) }) it('should revert in nothing to withdraw', async () => { // make sure no balance at start of test expect(await ethers.provider.getBalance(NON_ZERO_ADDRESS)).to.be.equal(0) const withdrawalAmount = 100 Mock__L1CrossDomainMessenger.smocked.xDomainMessageSender.will.return.with( () => DUMMY_L2_BRIDGE_ADDRESS ) await expect( L1StandardBridge.finalizeETHWithdrawal( NON_ZERO_ADDRESS, NON_ZERO_ADDRESS, withdrawalAmount, NON_NULL_BYTES32, { from: Mock__L1CrossDomainMessenger.address, } ) ).to.be.revertedWith( 'TransferHelper::safeTransferETH: ETH transfer failed' ) }) it('should credit funds to the withdrawer and not use too much gas', async () => { // make sure no balance at start of test expect(await ethers.provider.getBalance(NON_ZERO_ADDRESS)).to.be.equal(0) const withdrawalAmount = 100 Mock__L1CrossDomainMessenger.smocked.xDomainMessageSender.will.return.with( () => DUMMY_L2_BRIDGE_ADDRESS ) // thanks Alice await L1StandardBridge.connect(alice).depositETH( FINALIZATION_GAS, NON_NULL_BYTES32, { value: ethers.utils.parseEther('1.0'), } ) await L1StandardBridge.finalizeETHWithdrawal( NON_ZERO_ADDRESS, NON_ZERO_ADDRESS, withdrawalAmount, NON_NULL_BYTES32, { from: Mock__L1CrossDomainMessenger.address, } ) expect(await ethers.provider.getBalance(NON_ZERO_ADDRESS)).to.be.equal( withdrawalAmount ) }) }) describe('ERC20 deposits', () => { const depositAmount = 1_000 beforeEach(async () => { await L1ERC20.connect(alice).approve( L1StandardBridge.address, depositAmount ) }) it('depositERC20() escrows the deposit amount and sends the correct deposit message', async () => { // alice calls deposit on the bridge and the L1 bridge calls transferFrom on the token await L1StandardBridge.connect(alice).depositERC20( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) const depositCallToMessenger = Mock__L1CrossDomainMessenger.smocked.sendMessage.calls[0] const depositerBalance = await L1ERC20.balanceOf(aliceAddress) expect(depositerBalance).to.equal(INITIAL_TOTAL_L1_SUPPLY - depositAmount) // bridge's balance is increased const bridgeBalance = await L1ERC20.balanceOf(L1StandardBridge.address) expect(bridgeBalance).to.equal(depositAmount) // Check the correct cross-chain call was sent: // Message should be sent to the L2 bridge expect(depositCallToMessenger._target).to.equal(DUMMY_L2_BRIDGE_ADDRESS) // Message data should be a call telling the L2DepositedERC20 to finalize the deposit // the L1 bridge sends the correct message to the L1 messenger expect(depositCallToMessenger._message).to.equal( IL2ERC20Bridge.encodeFunctionData('finalizeDeposit', [ L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, aliceAddress, aliceAddress, depositAmount, NON_NULL_BYTES32, ]) ) expect(depositCallToMessenger._gasLimit).to.equal(FINALIZATION_GAS) }) it('depositERC20To() escrows the deposit amount and sends the correct deposit message', async () => { // depositor calls deposit on the bridge and the L1 bridge calls transferFrom on the token await L1StandardBridge.connect(alice).depositERC20To( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, bobsAddress, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) const depositCallToMessenger = Mock__L1CrossDomainMessenger.smocked.sendMessage.calls[0] const depositerBalance = await L1ERC20.balanceOf(aliceAddress) expect(depositerBalance).to.equal(INITIAL_TOTAL_L1_SUPPLY - depositAmount) // bridge's balance is increased const bridgeBalance = await L1ERC20.balanceOf(L1StandardBridge.address) expect(bridgeBalance).to.equal(depositAmount) // Check the correct cross-chain call was sent: // Message should be sent to the L2DepositedERC20 on L2 expect(depositCallToMessenger._target).to.equal(DUMMY_L2_BRIDGE_ADDRESS) // Message data should be a call telling the L2DepositedERC20 to finalize the deposit // the L1 bridge sends the correct message to the L1 messenger expect(depositCallToMessenger._message).to.equal( IL2ERC20Bridge.encodeFunctionData('finalizeDeposit', [ L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, aliceAddress, bobsAddress, depositAmount, NON_NULL_BYTES32, ]) ) expect(depositCallToMessenger._gasLimit).to.equal(FINALIZATION_GAS) }) it('cannot depositERC20 from a contract account', async () => { expect( L1StandardBridge.depositERC20( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) ).to.be.revertedWith('Account not EOA') }) describe('Handling ERC20.transferFrom() failures that revert ', () => { let MOCK__L1ERC20: MockContract before(async () => { // Deploy the L1 ERC20 token, Alice will receive the full initialSupply MOCK__L1ERC20 = await smockit( await Factory__L1ERC20.deploy('L1ERC20', 'ERC') ) MOCK__L1ERC20.smocked.transferFrom.will.revert() }) it('depositERC20(): will revert if ERC20.transferFrom() reverts', async () => { await expect( L1StandardBridge.connect(alice).depositERC20( MOCK__L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) ).to.be.revertedWith('SafeERC20: low-level call failed') }) it('depositERC20To(): will revert if ERC20.transferFrom() reverts', async () => { await expect( L1StandardBridge.connect(alice).depositERC20To( MOCK__L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, bobsAddress, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) ).to.be.revertedWith('SafeERC20: low-level call failed') }) it('depositERC20To(): will revert if the L1 ERC20 has no code or is zero address', async () => { await expect( L1StandardBridge.connect(alice).depositERC20To( ethers.constants.AddressZero, DUMMY_L2_ERC20_ADDRESS, bobsAddress, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) ).to.be.revertedWith('Address: call to non-contract') }) }) describe('Handling ERC20.transferFrom failures that return false', () => { let MOCK__L1ERC20: MockContract before(async () => { MOCK__L1ERC20 = await smockit( await Factory__L1ERC20.deploy('L1ERC20', 'ERC') ) MOCK__L1ERC20.smocked.transferFrom.will.return.with(false) }) it('deposit(): will revert if ERC20.transferFrom() returns false', async () => { await expect( L1StandardBridge.connect(alice).depositERC20( MOCK__L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) ).to.be.revertedWith('SafeERC20: ERC20 operation did not succeed') }) it('depositTo(): will revert if ERC20.transferFrom() returns false', async () => { await expect( L1StandardBridge.depositERC20To( MOCK__L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, bobsAddress, depositAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) ).to.be.revertedWith('SafeERC20: ERC20 operation did not succeed') }) }) }) describe('ERC20 withdrawals', () => { it('onlyFromCrossDomainAccount: should revert on calls from a non-crossDomainMessenger L1 account', async () => { await expect( L1StandardBridge.connect(alice).finalizeERC20Withdrawal( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, constants.AddressZero, constants.AddressZero, 1, NON_NULL_BYTES32 ) ).to.be.revertedWith(ERR_INVALID_MESSENGER) }) it('onlyFromCrossDomainAccount: should revert on calls from the right crossDomainMessenger, but wrong xDomainMessageSender (ie. not the L2DepositedERC20)', async () => { Mock__L1CrossDomainMessenger.smocked.xDomainMessageSender.will.return.with( '0x' + '22'.repeat(20) ) await expect( L1StandardBridge.finalizeERC20Withdrawal( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, constants.AddressZero, constants.AddressZero, 1, NON_NULL_BYTES32, { from: Mock__L1CrossDomainMessenger.address, } ) ).to.be.revertedWith(ERR_INVALID_X_DOMAIN_MSG_SENDER) }) it('should credit funds to the withdrawer and not use too much gas', async () => { // First Alice will 'donate' some tokens so that there's a balance to be withdrawn const withdrawalAmount = 10 await L1ERC20.connect(alice).approve( L1StandardBridge.address, withdrawalAmount ) await L1StandardBridge.connect(alice).depositERC20( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, withdrawalAmount, FINALIZATION_GAS, NON_NULL_BYTES32 ) expect(await L1ERC20.balanceOf(L1StandardBridge.address)).to.be.equal( withdrawalAmount ) // make sure no balance at start of test expect(await L1ERC20.balanceOf(NON_ZERO_ADDRESS)).to.be.equal(0) Mock__L1CrossDomainMessenger.smocked.xDomainMessageSender.will.return.with( () => DUMMY_L2_BRIDGE_ADDRESS ) await L1StandardBridge.finalizeERC20Withdrawal( L1ERC20.address, DUMMY_L2_ERC20_ADDRESS, NON_ZERO_ADDRESS, NON_ZERO_ADDRESS, withdrawalAmount, NON_NULL_BYTES32, { from: Mock__L1CrossDomainMessenger.address } ) expect(await L1ERC20.balanceOf(NON_ZERO_ADDRESS)).to.be.equal( withdrawalAmount ) }) }) })
the_stack
import { Transport, TransportMessage } from '../transport' import { Event, Command, Message, MessageAttributes } from '@node-ts/bus-messages' import { sleep, ClassConstructor, TypedEmitter, CoreDependencies, MiddlewareDispatcher, Middleware, Next} from '../util' import { Handler, FunctionHandler, HandlerDefinition, isClassHandler, HandlerDispatchRejected } from '../handler' import { serializeError } from 'serialize-error' import { BusState } from './bus-state' import { messageHandlingContext } from '../message-handling-context' import { ClassHandlerNotResolved, FailMessageOutsideHandlingContext } from '../error' import { v4 as generateUuid } from 'uuid' import { WorkflowRegistry } from '../workflow/registry' import { Logger } from '../logger' import { InvalidBusState } from './error' const EMPTY_QUEUE_SLEEP_MS = 500 export class BusInstance { readonly beforeSend = new TypedEmitter<{ command: Command, attributes: MessageAttributes }>() readonly beforePublish = new TypedEmitter<{ event: Event, attributes: MessageAttributes }>() readonly onError = new TypedEmitter<{ message: Message, error: Error, attributes?: MessageAttributes, rawMessage?: TransportMessage<unknown> }>() readonly afterReceive = new TypedEmitter<TransportMessage<unknown>>() readonly beforeDispatch = new TypedEmitter<{ message: Message, attributes: MessageAttributes, handlers: HandlerDefinition[] }>() readonly afterDispatch = new TypedEmitter<{ message: Message, attributes: MessageAttributes }>() private internalState: BusState = BusState.Stopped private runningWorkerCount = 0 private logger: Logger constructor ( private readonly transport: Transport<{}>, private readonly concurrency: number, private readonly workflowRegistry: WorkflowRegistry, private readonly coreDependencies: CoreDependencies, private readonly messageReadMiddleware: MiddlewareDispatcher<TransportMessage<unknown>> ) { this.logger = coreDependencies.loggerFactory('@node-ts/bus-core:service-bus') this.messageReadMiddleware.useFinal(this.handleNextMessagePolled) } /** * Publishes an event to the transport * @param event An event to publish * @param messageAttributes A set of attributes to attach to the outgoing message when published */ async publish<TEvent extends Event> ( event: TEvent, messageAttributes: Partial<MessageAttributes> = {} ): Promise<void> { this.logger.debug('Publishing event', { event, messageAttributes }) const attributes = this.prepareTransportOptions(messageAttributes) this.beforePublish.emit({ event, attributes }) return this.transport.publish(event, attributes) } /** * Sends a command to the transport * @param command A command to send * @param messageAttributes A set of attributes to attach to the outgoing messsage when sent */ async send<TCommand extends Command> ( command: TCommand, messageAttributes: Partial<MessageAttributes> = {} ): Promise<void> { this.logger.debug('Sending command', { command, messageAttributes }) const attributes = this.prepareTransportOptions(messageAttributes) this.beforeSend.emit({ command, attributes }) return this.transport.send(command, attributes) } /** * Instructs the bus that the current message being handled cannot be processed even with * retries and instead should immediately be routed to the dead letter queue * @throws FailMessageOutsideHandlingContext if called outside a message handling context */ async fail (): Promise<void> { const context = messageHandlingContext.get() if (!context) { throw new FailMessageOutsideHandlingContext() } const message = context.message this.logger.debug('Failing message', { message }) return this.transport.fail(message) } /** * Instructs the bus to start reading messages from the underlying service queue * and dispatching to message handlers. * * @throws InvalidBusState if the bus is already started or in a starting state */ async start (): Promise<void> { const startedStates = [BusState.Started, BusState.Starting] if (startedStates.includes(this.state)) { throw new InvalidBusState( 'Bus must be stopped before it can be started', this.state, [BusState.Stopped, BusState.Stopping] ) } this.internalState = BusState.Starting this.logger.info('Bus starting...') messageHandlingContext.enable() this.internalState = BusState.Started for (var i = 0; i < this.concurrency; i++) { setTimeout(async () => this.applicationLoop(), 0) } this.logger.info(`Bus started with concurrency ${this.concurrency}`) } /** * Stops a bus that has been started by `.start()`. This will wait for all running workers to complete * their current message handling contexts before returning. * * @throws InvalidBusState if the bus is already stopped or stopping */ async stop (): Promise<void> { const stoppedStates = [BusState.Stopped, BusState.Stopping] if (stoppedStates.includes(this.state)) { throw new InvalidBusState( 'Bus must be started before it can be stopped', this.state, [BusState.Started, BusState.Started] ) } this.internalState = BusState.Stopping this.logger.info('Bus stopping...') while (this.runningWorkerCount > 0) { await sleep(10) } this.internalState = BusState.Stopped this.logger.info('Bus stopped') } /** * Stops and disposes all resources allocated to the bus, as well as removing * all handler registrations. * * The bus instance can not be used after this has been called. */ async dispose (): Promise<void> { this.logger.info('Disposing bus instance...') if (![BusState.Stopped, BusState.Stopped].includes(this.state)) { await this.stop() } if (this.transport.disconnect) { await this.transport.disconnect() } if (this.transport.dispose) { await this.transport.dispose() } await this.workflowRegistry.dispose() this.coreDependencies.handlerRegistry.reset() this.logger.info('Bus disposed') } /** * Gets the current state of a message-handling bus */ get state (): BusState { return this.internalState } private async applicationLoop (): Promise<void> { this.runningWorkerCount++ while (this.internalState === BusState.Started) { const messageHandled = await this.handleNextMessage() // Avoids locking up CPU when there's no messages to be processed if (!messageHandled) { await sleep(EMPTY_QUEUE_SLEEP_MS) } } this.runningWorkerCount-- } private async handleNextMessage (): Promise<boolean> { try { const message = await this.transport.readNextMessage() if (message) { this.logger.debug('Message read from transport', { message }) this.afterReceive.emit(message) try { messageHandlingContext.set(message) await this.messageReadMiddleware.dispatch(message) this.afterDispatch.emit({ message: message.domainMessage, attributes: message.attributes }) } catch (error) { this.logger.warn( 'Message was unsuccessfully handled. Returning to queue', { message, error: serializeError(error) } ) this.onError.emit({ message: message.domainMessage, error, attributes: message.attributes, rawMessage: message }) await this.transport.returnMessage(message) return false } finally { messageHandlingContext.destroy() } return true } } catch (error) { this.logger.error('Failed to handle and dispatch message from transport', { error: serializeError(error) }) } return false } private async dispatchMessageToHandlers (message: Message, messageAttributes: MessageAttributes): Promise<void> { const handlers = this.coreDependencies.handlerRegistry.get(this.coreDependencies.loggerFactory, message) if (handlers.length === 0) { this.logger.error(`No handlers registered for message. Message will be discarded`, { messageName: message.$name }) return } const handlersToInvoke = handlers.map(handler => this.dispatchMessageToHandler( message, messageAttributes, handler )) this.beforeDispatch.emit({ message, attributes: messageAttributes, handlers }) const handlerResults = await Promise.allSettled(handlersToInvoke) const failedHandlers = handlerResults.filter(r => r.status === 'rejected') if (failedHandlers.length) { const reasons = (failedHandlers as PromiseRejectedResult[]).map(h => h.reason) throw new HandlerDispatchRejected(reasons) } this.logger.debug('Message dispatched to all handlers', { message, numHandlers: handlersToInvoke.length }) } private prepareTransportOptions (clientOptions: Partial<MessageAttributes>): MessageAttributes { const handlingContext = messageHandlingContext.get() const messageAttributes: MessageAttributes = { // The optional operator? decided not to work here correlationId: clientOptions.correlationId || (handlingContext ? handlingContext.message.attributes.correlationId : undefined) || generateUuid(), attributes: clientOptions.attributes || {}, stickyAttributes: { ...(handlingContext ? handlingContext.message.attributes.stickyAttributes : {}), ...clientOptions.stickyAttributes } } this.logger.debug('Prepared transport options', { messageAttributes }) return messageAttributes } async dispatchMessageToHandler ( message: Message, attributes: MessageAttributes, handler: HandlerDefinition<Message> ): Promise<void> { if (isClassHandler(handler)) { const classHandler = handler as ClassConstructor<Handler<Message>> let handlerInstance: Handler<Message> | undefined try { handlerInstance = this.coreDependencies.container!.get(classHandler) if (!handlerInstance) { throw new Error('Container failed to resolve an instance.') } } catch (e) { throw new ClassHandlerNotResolved(e.message) } return handlerInstance.handle(message, attributes) } else { const fnHandler = handler as FunctionHandler<Message> return fnHandler( message, attributes ) } } /** * The final middleware that runs, after all the useBeforeHandleNextMessage middlewares have completed * It dispatches a message that has been polled from the queue * and deletes the message from the transport */ private handleNextMessagePolled: Middleware<TransportMessage<{}>> = async ( message: TransportMessage<{}>, next: Next ): Promise<void> => { await this.dispatchMessageToHandlers(message.domainMessage, message.attributes) await this.transport.deleteMessage(message) return next() } }
the_stack
import React, { Component } from "react"; import { withStyles, CircularProgress, Typography, Paper, Button, Chip, Avatar, Slide } from "@material-ui/core"; import { styles } from "./PageLayout.styles"; import Post from "../components/Post"; import { Status } from "../types/Status"; import Mastodon, { StreamListener } from "megalodon"; import { withSnackbar } from "notistack"; import Masonry from "react-masonry-css"; import { getUserDefaultBool } from "../utilities/settings"; import ArrowUpwardIcon from "@material-ui/icons/ArrowUpward"; interface IHomePageState { posts?: [Status]; backlogPosts?: [Status] | null; viewIsLoading: boolean; viewDidLoad?: boolean; viewDidError?: boolean; viewDidErrorCode?: any; isMasonryLayout?: boolean; } /** * The base class for the home timeline. * @deprecated Use TimelinePage with the props `timeline="/timelines/home"` * and `stream="/streaming/user"`. */ class HomePage extends Component<any, IHomePageState> { client: Mastodon; streamListener: StreamListener; constructor(props: any) { super(props); this.state = { viewIsLoading: true, backlogPosts: null, isMasonryLayout: getUserDefaultBool("isMasonryLayout") }; this.client = new Mastodon( localStorage.getItem("access_token") as string, (localStorage.getItem("baseurl") as string) + "/api/v1" ); this.streamListener = this.client.stream("/streaming/user"); } componentWillMount() { this.streamListener.on("connect", () => { this.client .get("/timelines/home", { limit: 40 }) .then((resp: any) => { let statuses: [Status] = resp.data; this.setState({ posts: statuses, viewIsLoading: false, viewDidLoad: true, viewDidError: false }); }) .catch((resp: any) => { this.setState({ viewIsLoading: false, viewDidLoad: true, viewDidError: true, viewDidErrorCode: String(resp) }); this.props.enqueueSnackbar("Failed to get posts.", { variant: "error" }); }); }); this.streamListener.on("update", (status: Status) => { let queue = this.state.backlogPosts; if (queue !== null && queue !== undefined) { queue.unshift(status); } else { queue = [status]; } this.setState({ backlogPosts: queue }); }); this.streamListener.on("delete", (id: number) => { let posts = this.state.posts; if (posts) { posts.forEach((post: Status) => { if (posts && parseInt(post.id) === id) { posts.splice(posts.indexOf(post), 1); } }); this.setState({ posts }); } }); this.streamListener.on("error", (err: Error) => { this.setState({ viewDidError: true, viewDidErrorCode: err.message }); this.props.enqueueSnackbar("An error occured.", { variant: "error" }); }); this.streamListener.on("heartbeat", () => {}); } componentWillUnmount() { this.streamListener.stop(); } insertBacklog() { window.scrollTo(0, 0); let posts = this.state.posts; let backlog = this.state.backlogPosts; if (posts && backlog && backlog.length > 0) { let push = backlog.concat(posts); this.setState({ posts: push as [Status], backlogPosts: null }); } } loadMoreTimelinePieces() { this.setState({ viewDidLoad: false, viewIsLoading: true }); if (this.state.posts) { this.client .get("/timelines/home", { max_id: this.state.posts[this.state.posts.length - 1].id, limit: 20 }) .then((resp: any) => { let newPosts: [Status] = resp.data; let posts = this.state.posts as [Status]; newPosts.forEach((post: Status) => { posts.push(post); }); this.setState({ viewIsLoading: false, viewDidLoad: true, posts }); }) .catch((err: Error) => { this.setState({ viewIsLoading: false, viewDidError: true, viewDidErrorCode: err.message }); this.props.enqueueSnackbar("Failed to get posts", { variant: "error" }); }); } } render() { const { classes } = this.props; const containerClasses = `${classes.pageLayoutMaxConstraints}${ this.state.isMasonryLayout ? " " + classes.pageLayoutMasonry : "" }`; return ( <div className={containerClasses}> {this.state.backlogPosts ? ( <div className={classes.pageTopChipContainer}> <div className={classes.pageTopChips}> <Slide direction="down" in={true}> <Chip avatar={ <Avatar> <ArrowUpwardIcon /> </Avatar> } label={`View ${ this.state.backlogPosts.length } new post${ this.state.backlogPosts.length > 1 ? "s" : "" }`} color="primary" className={classes.pageTopChip} onClick={() => this.insertBacklog()} clickable /> </Slide> </div> </div> ) : null} {this.state.posts ? ( <div> {this.state.isMasonryLayout ? ( <Masonry breakpointCols={{ default: 4, 2000: 3, 1400: 2, 1050: 1 }} className={classes.masonryGrid} columnClassName={ classes["my-masonry-grid_column"] } > {this.state.posts.map((post: Status) => { return ( <div className={classes.masonryGrid_item} > <Post key={post.id} post={post} client={this.client} /> </div> ); })} </Masonry> ) : ( <div> {this.state.posts.map((post: Status) => { return ( <Post key={post.id} post={post} client={this.client} /> ); })} </div> )} <br /> {this.state.viewDidLoad && !this.state.viewDidError ? ( <div style={{ textAlign: "center" }} onClick={() => this.loadMoreTimelinePieces()} > <Button variant="contained">Load more</Button> </div> ) : null} </div> ) : ( <span /> )} {this.state.viewDidError ? ( <Paper className={classes.errorCard}> <Typography variant="h4">Bummer.</Typography> <Typography variant="h6"> Something went wrong when loading this timeline. </Typography> <Typography> {this.state.viewDidErrorCode ? this.state.viewDidErrorCode : ""} </Typography> </Paper> ) : ( <span /> )} {this.state.viewIsLoading ? ( <div style={{ textAlign: "center" }}> <CircularProgress className={classes.progress} color="primary" /> </div> ) : ( <span /> )} </div> ); } } export default withStyles(styles)(withSnackbar(HomePage));
the_stack
import { PluginHooks } from '../../types/pluginHooks' import { findDependencies, getModuleMarker, isSameFilepath, parseOptions } from '../utils' import { builderInfo, EXPOSES_MAP, parsedOptions } from '../public' import { ConfigTypeSet, VitePluginFederationOptions } from 'types' import { walk } from 'estree-walker' import MagicString from 'magic-string' import * as path from 'path' import * as fs from 'fs' const sharedFileReg = /^__federation_shared_.+\.js$/ const pickSharedNameReg = /(?<=^__federation_shared_).+(?=\.js$)/ export function prodSharedPlugin( options: VitePluginFederationOptions ): PluginHooks { parsedOptions.prodShared = parseOptions( options.shared || {}, () => ({ import: true, shareScope: 'default' }), (value) => { value.import = value.import ?? true value.shareScope = value.shareScope || 'default' return value } ) const sharedNames = new Set<string>() parsedOptions.prodShared.forEach((value) => sharedNames.add(value[0])) const exposesModuleIdSet = new Set() EXPOSES_MAP.forEach((value) => { exposesModuleIdSet.add(`${value}.js`) }) let isHost let isRemote const id2Prop = new Map<string, any>() return { name: 'originjs:shared-production', virtualFile: { __federation_lib_semver: 'void 0', __federation_fn_import: ` const moduleMap= ${getModuleMarker('moduleMap', 'var')} const moduleCache = Object.create(null); async function importShared(name,shareScope = 'default') { return moduleCache[name] ? new Promise((r) => r(moduleCache[name])) : getProviderSharedModule(name, shareScope); } async function __federation_import(name){ return import(name); } async function getProviderSharedModule(name,shareScope) { let module = null; if (globalThis?.__federation_shared__?.[shareScope]?.[name]) { const versionObj = globalThis.__federation_shared__[shareScope][name]; const versionKey = Object.keys(versionObj)[0]; const versionValue = Object.values(versionObj)[0]; if (moduleMap[name]?.requiredVersion) { // judge version satisfy const semver= await import('__federation_lib_semver'); const fn = semver.satisfy; if (fn(versionKey, moduleMap[name].requiredVersion)) { module = await versionValue.metaGet(); } else { console.log(\`provider support \${name}(\${versionKey}) is not satisfied requiredVersion(\${moduleMap[name].requiredVersion})\`) } } else { module = await versionValue.metaGet(); } } if(module){ moduleCache[name] = module; return module; }else{ return getConsumerSharedModule(name, shareScope); } } async function getConsumerSharedModule(name , shareScope) { if (moduleMap[name]?.import) { const module = await moduleMap[name].get() moduleCache[name] = module; return module; } else { console.error(\`consumer config import=false,so cant use callback shared module\`) } } export {importShared}; ` }, options(inputOptions) { isHost = !!parsedOptions.prodRemote.length isRemote = !!parsedOptions.prodExpose.length if (sharedNames.size) { // remove item which is both in external and shared inputOptions.external = (inputOptions.external as [])?.filter( (item) => { return !sharedNames.has(item) } ) } return inputOptions }, async buildStart() { // forEach and collect dir const collectDirFn = (filePath: string, collect: string[]) => { const files = fs.readdirSync(filePath) files.forEach((name) => { const tempPath = path.join(filePath, name) const isDir = fs.statSync(tempPath).isDirectory() if (isDir) { collect.push(tempPath) collectDirFn(tempPath, collect) } }) } const monoRepos: { arr: string[]; root: string | ConfigTypeSet }[] = [] const dirPaths: string[] = [] const currentDir = path.resolve() for (const arr of parsedOptions.prodShared) { try { const resolve = await this.resolve(arr[0]) arr[1].id = resolve?.id } catch (e) { // try to resolve monoRepo arr[1].removed = true const dir = path.join(currentDir, 'node_modules', arr[0]) const dirStat = fs.statSync(dir) if (dirStat.isDirectory()) { collectDirFn(dir, dirPaths) } else { this.error(`cant resolve "${arr[0]}"`) } if (dirPaths.length > 0) { monoRepos.push({ arr: dirPaths, root: arr }) } } if (isHost && !arr[1].version) { const packageJsonPath = `${currentDir}${path.sep}node_modules${path.sep}${arr[0]}${path.sep}package.json` arr[1].version = (await import(packageJsonPath)).version if (!arr[1].version) { this.error( `No description file or no version in description file (usually package.json) of ${arr[0]}(${packageJsonPath}). Add version to description file, or manually specify version in shared config.` ) } } } parsedOptions.prodShared = parsedOptions.prodShared.filter( (item) => !item[1].removed ) // assign version to monoRepo if (monoRepos.length > 0) { for (const monoRepo of monoRepos) { for (const id of monoRepo.arr) { try { const idResolve = await this.resolve(id) if (idResolve?.id) { (parsedOptions.prodShared as any[]).push([ `${monoRepo.root[0]}/${path.basename(id)}`, { id: idResolve?.id, import: monoRepo.root[1].import, shareScope: monoRepo.root[1].shareScope, root: monoRepo.root } ]) } } catch (e) { // ignore } } } } // console.log(parsedOptions.prodShared); if (parsedOptions.prodShared.length && isRemote) { for (const prod of parsedOptions.prodShared) { id2Prop.set(prod[1].id, prod[1]) } this.emitFile({ fileName: `${ builderInfo.assetsDir ? builderInfo.assetsDir + '/' : '' }__federation_fn_import.js`, type: 'chunk', id: '__federation_fn_import', preserveSignature: 'strict' }) this.emitFile({ fileName: `${ builderInfo.assetsDir ? builderInfo.assetsDir + '/' : '' }__federation_lib_semver.js`, type: 'chunk', id: '__federation_lib_semver', preserveSignature: 'strict' }) } }, outputOptions: function (outputOption) { // remove rollup generated empty imports,like import './filename.js' outputOption.hoistTransitiveImports = false // sort shared dep const that = this const priority: string[] = [] const depInShared = new Map() parsedOptions.prodShared.forEach((value) => { const shareName = value[0] // pick every shared moduleId const usedSharedModuleIds = new Set<string>() const sharedModuleIds = new Map<string, string>() // exclude itself parsedOptions.prodShared .filter((item) => item[0] !== shareName) .forEach((item) => sharedModuleIds.set(item[1].id, item[0])) depInShared.set(shareName, usedSharedModuleIds) const deps = new Set<string>() findDependencies.apply(that, [ value[1].id, deps, sharedModuleIds, usedSharedModuleIds ]) value[1].dependencies = deps }) // judge dependencies priority const orderByDepCount: Map<string, Set<string>>[] = [] depInShared.forEach((value, key) => { if (!orderByDepCount[value.size]) { orderByDepCount[value.size] = new Map() } orderByDepCount[value.size].set(key, value) }) // dependency nothing is first,handle index = 0 if (orderByDepCount[0]) { for (const key of orderByDepCount[0].keys()) { priority.push(key) } } // handle index >= 1 orderByDepCount .filter((item, index) => item && index >= 1) .forEach((item) => { for (const entry of item.entries()) { addDep(entry, priority, depInShared) } }) function addDep([key, value], priority, depInShared) { for (const dep of value) { if (!priority.includes(dep)) { addDep([dep, depInShared.get(dep)], priority, depInShared) } } if (!priority.includes(key)) { priority.push(key) } } // adjust the map order according to priority parsedOptions.prodShared.sort((a, b) => { const aIndex = priority.findIndex((value) => value === a[0]) const bIndex = priority.findIndex((value) => value === b[0]) return aIndex - bIndex }) // only active when manualChunks is function,array not to solve if (typeof outputOption.manualChunks === 'function') { outputOption.manualChunks = new Proxy(outputOption.manualChunks, { apply(target, thisArg, argArray) { const id = argArray[0] // if id is in shared dependencies, return id ,else return vite function value const find = parsedOptions.prodShared.find((arr) => arr[1].dependencies.has(id) ) return find ? find[0] : target(argArray[0], argArray[1]) } }) } return outputOption }, renderChunk: function (code, chunk, options) { // process shared chunk const sharedFlag = sharedFileReg.test(path.basename(chunk.fileName)) const facadeModuleId = chunk.facadeModuleId const exposesFlag = parsedOptions.prodExpose.some((expose) => isSameFilepath(expose[1].id, facadeModuleId as string) ) const needSharedImport = isRemote && parsedOptions.prodShared.length > 0 && chunk.type === 'chunk' && (sharedFlag || exposesFlag) && chunk.imports.some((importName) => sharedFileReg.test(path.basename(importName)) ) if (needSharedImport) { const ast = this.parse(code) const magicString = new MagicString(code) let modify = false switch (options.format) { case 'es': { walk(ast, { enter(node: any) { if ( node.type === 'ImportDeclaration' && sharedFileReg.test(path.basename(node.source.value)) ) { const sharedName = path .basename(node.source.value) .match(pickSharedNameReg)?.[0] if (sharedName) { const declaration: (string | never)[] = [] node.specifiers?.forEach((specify) => { declaration.push( `${ specify.imported?.name ? `${ specify.imported.name === specify.local.name ? specify.local.name : `${specify.imported.name}:${specify.local.name}` }` : `default:${specify.local.name}` }` ) }) if (declaration.length) { magicString.overwrite( node.start, node.end, `const {${declaration.join( ',' )}} = await importShared('${sharedName}')` ) modify = true } } } } }) if (modify) { const prop = id2Prop.get(facadeModuleId as string) magicString.prepend( `import {importShared} from '${ prop?.root ? '.' : '' }./__federation_fn_import.js'\n` ) return magicString.toString() } } break case 'system': { walk(ast, { enter(node: any) { const expression = node.body.length === 1 ? node.body[0]?.expression : node.body.find( (item) => item.type === 'ExpressionStatement' && item.expression?.callee?.object?.name === 'System' && item.expression.callee.property?.name === 'register' )?.expression if (expression) { const args = expression.arguments if ( args[0].type === 'ArrayExpression' && args[0].elements?.length > 0 ) { const importIndex: any[] = [] let removeLast = false chunk.imports.forEach((importName, index) => { const baseName = path.basename(importName) if (sharedFileReg.test(baseName)) { importIndex.push({ index: index, name: baseName.match(pickSharedNameReg)?.[0] }) if (index === chunk.imports.length - 1) { removeLast = true } } }) if ( importIndex.length && args[1]?.type === 'FunctionExpression' ) { const functionExpression = args[1] const returnStatement = functionExpression?.body?.body.find( (item) => item.type === 'ReturnStatement' ) // insert __federation_import variable magicString.prependLeft( returnStatement.start, 'var __federation_import;\n' ) const setters = returnStatement.argument.properties.find( (property) => property.key.name === 'setters' ) const settersElements = setters.value.elements // insert __federation_import setter magicString.appendRight( setters.end - 1, `${ removeLast ? '' : ',' }function (module){__federation_import=module.importShared}` ) const execute = returnStatement.argument.properties.find( (property) => property.key.name === 'execute' ) const insertPos = execute.value.body.body[0].start importIndex.forEach((item) => { // remove unnecessary setters and import const last = item.index === settersElements.length - 1 magicString.remove( settersElements[item.index].start, last ? settersElements[item.index].end : settersElements[item.index + 1].start - 1 ) magicString.remove( args[0].elements[item.index].start, last ? args[0].elements[item.index].end : args[0].elements[item.index + 1].start - 1 ) // insert federation shared import lib const varName = `__federation_${item.name}` magicString.prependLeft( insertPos, `var ${varName} = await __federation_import('${item.name}');\n` ) // replace it with sharedImport setters.value.elements[item.index].body.body.forEach( (setFn) => { magicString.appendLeft( insertPos, `${setFn.expression.left.name} = ${varName}.${ setFn.expression.right.property.name ?? setFn.expression.right.property.value };\n` ) } ) }) // add async flag to execute function magicString.prependLeft(execute.value.start, ' async ') // add sharedImport import declaration magicString.appendRight( args[0].end - 1, `${ removeLast ? '' : ',' }'./__federation_fn_import.js'` ) modify = true } } } // only need to process once this.skip() } }) if (modify) { return magicString.toString() } } break } } return null } } }
the_stack
export const tabFieldValueVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: '71da814d-5580-4f1f-972a-8089253aeded', title: 'tabBasicFieldValue', visibilityCondition: { leftType: 'field', leftValue: 'TextOne', operator: '==', rightValue: 'showTab', rightType: 'value', nextConditionOperator: '', nextCondition: null } }, { id: '442eea0b-65f9-484e-b37f-f5a91d5e1f21', title: 'tabWithFields', visibilityCondition: null } ], fields: [ { id: 'dcde7e13-2444-48bc-ab30-32902cea549e', name: 'Label', type: 'container', tab: '71da814d-5580-4f1f-972a-8089253aeded', numberOfColumns: 2, fields: { 1: [ { id: 'TextTwo', name: 'TextTwo', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } }, { id: 'df452297-d0e8-4406-b9d3-10842033549d', name: 'Label', type: 'container', tab: '442eea0b-65f9-484e-b37f-f5a91d5e1f21', numberOfColumns: 2, fields: { 1: [ { id: 'TextOne', name: 'TextOne', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } } ], outcomes: [], metadata: {}, variables: [] } } }; export const tabVarValueVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: '71da814d-5580-4f1f-972a-8089253aeded', title: 'tabBasicVarValue', visibilityCondition: { leftType: 'variable', leftValue: 'stringVar', operator: '==', rightValue: 'showTab', rightType: 'value', nextConditionOperator: '' } } ], fields: [ { id: 'dcde7e13-2444-48bc-ab30-32902cea549e', name: 'Label', type: 'container', tab: '71da814d-5580-4f1f-972a-8089253aeded', numberOfColumns: 2, fields: { 1: [ { id: 'TextTwo', name: 'TextTwo', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } } ], outcomes: [], metadata: {}, variables: [ { id: "803269e6-a568-40e2-aec3-75ad2f411688", name: "stringVar", type: "string", value: "showTab" } ] } } }; export const tabVarFieldVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: '71da814d-5580-4f1f-972a-8089253aeded', title: 'tabBasicVarField', visibilityCondition: { leftType: 'variable', leftValue: 'stringVar', operator: '==', rightValue: 'TextOne', rightType: 'field', nextConditionOperator: '' } }, { id: '0e538a28-f8d6-4cb8-ae93-dbfb2efdf3b1', title: 'tabWithFields', visibilityCondition: null } ], fields: [ { id: 'dcde7e13-2444-48bc-ab30-32902cea549e', name: 'Label', type: 'container', tab: '71da814d-5580-4f1f-972a-8089253aeded', numberOfColumns: 2, fields: { 1: [ { id: 'TextTwo', name: 'TextTwo', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } }, { id: '1308e433-08ce-4448-a62a-0accc1187d15', name: 'Label', type: 'container', tab: '0e538a28-f8d6-4cb8-ae93-dbfb2efdf3b1', numberOfColumns: 2, fields: { 1: [ { id: 'TextOne', name: 'TextOne', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } } ], outcomes: [], metadata: {}, variables: [ { id: "803269e6-a568-40e2-aec3-75ad2f411688", name: "stringVar", type: "string", value: "showTab" } ] } } }; export const tabFieldFieldVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: '71da814d-5580-4f1f-972a-8089253aeded', title: 'tabBasicFieldField', visibilityCondition: { leftType: 'field', leftValue: 'TextThree', operator: '==', rightValue: 'TextOne', rightType: 'field', nextConditionOperator: '' } }, { id: '442eea0b-65f9-484e-b37f-f5a91d5e1f21', title: 'tabWithFields', visibilityCondition: null } ], fields: [ { id: 'dcde7e13-2444-48bc-ab30-32902cea549e', name: 'Label', type: 'container', tab: '71da814d-5580-4f1f-972a-8089253aeded', numberOfColumns: 2, fields: { 1: [ { id: 'TextTwo', name: 'TextTwo', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } }, { id: 'df452297-d0e8-4406-b9d3-10842033549d', name: 'Label', type: 'container', tab: '442eea0b-65f9-484e-b37f-f5a91d5e1f21', numberOfColumns: 2, fields: { 1: [ { id: 'TextOne', name: 'TextOne', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [ { id: 'TextThree', name: 'TextThree', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ] } } ], outcomes: [], metadata: {}, variables: [] } } }; export const tabFieldVarVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: '71da814d-5580-4f1f-972a-8089253aeded', title: 'tabBasicVarField', visibilityCondition: { leftType: 'field', leftValue: 'TextOne', operator: '==', rightValue: 'stringVar', rightType: 'variable', nextConditionOperator: '' } }, { id: '0e538a28-f8d6-4cb8-ae93-dbfb2efdf3b1', title: 'tabWithFields', visibilityCondition: null } ], fields: [ { id: 'dcde7e13-2444-48bc-ab30-32902cea549e', name: 'Label', type: 'container', tab: '71da814d-5580-4f1f-972a-8089253aeded', numberOfColumns: 2, fields: { 1: [ { id: 'TextTwo', name: 'TextTwo', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } }, { id: '1308e433-08ce-4448-a62a-0accc1187d15', name: 'Label', type: 'container', tab: '0e538a28-f8d6-4cb8-ae93-dbfb2efdf3b1', numberOfColumns: 2, fields: { 1: [ { id: 'TextOne', name: 'TextOne', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } } ], outcomes: [], metadata: {}, variables: [ { id: "803269e6-a568-40e2-aec3-75ad2f411688", name: "stringVar", type: "string", value: "showTab" } ] } } }; export const tabVarVarVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: 'ef512cb3-0c41-4d12-84ef-a7ef8f0b111a', title: 'tabBasicVarVar', visibilityCondition: { leftType: 'variable', leftValue: 'showTabOne', operator: '==', rightValue: 'showTabTwo', rightType: 'variable', nextConditionOperator: '' } } ], fields: [ { id: '6eeb9e54-e51d-44f3-9557-503308f07361', name: 'Label', type: 'container', tab: 'ef512cb3-0c41-4d12-84ef-a7ef8f0b111a', numberOfColumns: 2, fields: { 1: [ { id: 'TextOne', name: 'TextOne', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } } ], outcomes: [], metadata: {}, variables: [ { id: "b116df99-f6b5-45f8-b48c-15b74f7f1c92", name: "showTabOne", type: "string", value: "showTab" }, { id: "6e3e88ab-848c-4f48-8326-a404d1427f60", name: "showTabTwo", type: "string", value: "showTab" } ] } } }; export const tabNextOperatorsVisibilityJson = { formRepresentation: { id: 'form-3aff57d3-62af-4adf-9b14-1d8f44a28077', name: 'tabvisibility', description: '', version: 0, standalone: true, formDefinition: { tabs: [ { id: '71da814d-5580-4f1f-972a-8089253aeded', title: 'tabNextOperators', visibilityCondition: { leftType: 'field', leftValue: 'TextOne', operator: '==', rightValue: 'showTab', rightType: 'value', nextConditionOperator: 'and', nextCondition: { leftType: 'field', leftValue: 'TextThree', operator: '!=', rightValue: 'showTab', rightType: 'value', nextConditionOperator: '', nextCondition: null } } }, { id: '442eea0b-65f9-484e-b37f-f5a91d5e1f21', title: 'tabWithFields', visibilityCondition: null } ], fields: [ { id: 'dcde7e13-2444-48bc-ab30-32902cea549e', name: 'Label', type: 'container', tab: '71da814d-5580-4f1f-972a-8089253aeded', numberOfColumns: 2, fields: { 1: [ { id: 'TextTwo', name: 'TextTwo', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [] } }, { id: 'df452297-d0e8-4406-b9d3-10842033549d', name: 'Label', type: 'container', tab: '442eea0b-65f9-484e-b37f-f5a91d5e1f21', numberOfColumns: 2, fields: { 1: [ { id: 'TextOne', name: 'TextOne', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ], 2: [ { id: 'TextThree', name: 'TextThree', type: 'text', required: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, regexPattern: null, visibilityCondition: null, params: { existingColspan: 1, maxColspan: 2 } } ] } } ], outcomes: [], metadata: {}, variables: [] } } };
the_stack
import {setupFaucet} from './fixtures'; import {BigNumber} from 'ethers'; import {expectEventWithArgs, waitFor, setupUser} from '../utils'; import {expect} from '../chai-setup'; const DECIMALS_18 = BigNumber.from('1000000000000000000'); const TOTAL_SUPPLY = DECIMALS_18.mul(1000000); describe('Faucet', function () { it('Send cannot exceed Faucet limit amout', async function () { const setUp = await setupFaucet(); const {faucetContract, sandContract, sandBeneficiary, others} = setUp; const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const user = await setupUser(others[4], { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( sandContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); const ASKED_AMOUNT = DECIMALS_18.mul(11); await expect(user.faucetContract.send(ASKED_AMOUNT)).to.be.revertedWith( 'Demand must not exceed 10000000000000000000' ); }); it('Send cannot be executed twice without awaiting', async function () { const setUp = await setupFaucet(); const {faucetContract, sandContract, sandBeneficiary, others} = setUp; const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const user = await setupUser(others[4], { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( faucetContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); const ASKED_AMOUNT = DECIMALS_18.mul(2); await waitFor(user.faucetContract.send(ASKED_AMOUNT)); await expect(user.faucetContract.send(ASKED_AMOUNT)).to.be.revertedWith( 'After each call you must wait 30 seconds.' ); }); it('Send succeded for correct asked amount', async function () { const setUp = await setupFaucet(); const {faucetContract, sandContract, sandBeneficiary, others} = setUp; const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const user = await setupUser(others[4], { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( faucetContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); const ASKED_AMOUNT = DECIMALS_18.mul(3); const receiveReceipt = await waitFor( user.faucetContract.send(ASKED_AMOUNT) ); const receiveEvent = await expectEventWithArgs( faucetContract, receiveReceipt, 'FaucetSent' ); const balance = await sandContract.balanceOf(user.address); expect(receiveEvent.args[0]).to.equal(user.address); // receiver expect(receiveEvent.args[1]).to.equal(ASKED_AMOUNT.toString()); // amount expect(balance.toString()).to.equal(ASKED_AMOUNT.toString()); // amount }); it('Retrieve succeded for deployer', async function () { const setUp = await setupFaucet(); const {faucetContract, deployer, sandContract, sandBeneficiary} = setUp; const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const faucetDeployer = await setupUser(deployer, { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( faucetContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); const receiveReceipt = await waitFor( faucetDeployer.faucetContract.retrieve(faucetDeployer.address) ); const receiveEvent = await expectEventWithArgs( faucetContract, receiveReceipt, 'FaucetRetrieved' ); const balance = await sandContract.balanceOf(faucetDeployer.address); expect(receiveEvent.args[0]).to.equal(faucetDeployer.address); // receiver expect(receiveEvent.args[1]).to.equal(TOTAL_SUPPLY.toString()); // amount expect(balance.toString()).to.equal(TOTAL_SUPPLY.toString()); // amount }); it('Retrieve succeded for deployer with any address', async function () { const setUp = await setupFaucet(); const { faucetContract, deployer, sandContract, sandBeneficiary, others, } = setUp; const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const faucetUser = await setupUser(others[4], { faucetContract, }); const faucetDeployer = await setupUser(deployer, { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( faucetContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); const receiveReceipt = await waitFor( faucetDeployer.faucetContract.retrieve(faucetUser.address) ); const receiveEvent = await expectEventWithArgs( faucetContract, receiveReceipt, 'FaucetRetrieved' ); const balance = await sandContract.balanceOf(faucetUser.address); expect(receiveEvent.args[0]).to.equal(faucetUser.address); // receiver expect(receiveEvent.args[1]).to.equal(TOTAL_SUPPLY.toString()); // amount expect(balance.toString()).to.equal(TOTAL_SUPPLY.toString()); // amount }); it('Retrieve fail for user that is not deployer', async function () { const setUp = await setupFaucet(); const {faucetContract, others, sandContract, sandBeneficiary} = setUp; const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const user = await setupUser(others[4], { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( faucetContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); await expect(user.faucetContract.retrieve(user.address)).to.be.revertedWith( 'Ownable: caller is not the owner' ); }); it('setPeriod succeed for deployer', async function () { const setUp = await setupFaucet(); const {faucetContract, deployer} = setUp; const faucetDeployer = await setupUser(deployer, { faucetContract, }); const periodReceipt = await waitFor( faucetDeployer.faucetContract.setPeriod(40) ); const periodEvent = await expectEventWithArgs( faucetContract, periodReceipt, 'FaucetPeriod' ); const period = await faucetContract.getPeriod(); expect(periodEvent.args[0]).to.equal(40); // amount expect(period).to.equal(40); // amount }); it('setPeriod fail for user that is not deployer', async function () { const setUp = await setupFaucet(); const {faucetContract, others} = setUp; const user = await setupUser(others[4], { faucetContract, }); await expect(user.faucetContract.setPeriod(40)).to.be.revertedWith( 'Ownable: caller is not the owner' ); }); it('setLimit succeed for deployer', async function () { const setUp = await setupFaucet(); const {faucetContract, deployer} = setUp; const faucetDeployer = await setupUser(deployer, { faucetContract, }); const NEW_LIMIT = DECIMALS_18.mul(25); const limitReceipt = await waitFor( faucetDeployer.faucetContract.setLimit(NEW_LIMIT) ); const limitEvent = await expectEventWithArgs( faucetContract, limitReceipt, 'FaucetLimit' ); const limit = await faucetContract.getLimit(); expect(limitEvent.args[0]).to.equal(NEW_LIMIT); // amount expect(limit).to.equal(NEW_LIMIT); // amount }); it('Send with new limit succeed after limit update.', async function () { const setUp = await setupFaucet(); const { faucetContract, sandContract, sandBeneficiary, deployer, others, } = setUp; const faucetDeployer = await setupUser(deployer, { faucetContract, }); const NEW_LIMIT = DECIMALS_18.mul(25); const limitReceipt = await waitFor( faucetDeployer.faucetContract.setLimit(NEW_LIMIT) ); const limitEvent = await expectEventWithArgs( faucetContract, limitReceipt, 'FaucetLimit' ); const limit = await faucetContract.getLimit(); expect(limitEvent.args[0]).to.equal(NEW_LIMIT); // amount expect(limit).to.equal(NEW_LIMIT); // amount const sandBeneficiaryUser = await setupUser(sandBeneficiary, { sandContract, }); const user = await setupUser(others[4], { faucetContract, }); const transferReceipt = await waitFor( sandBeneficiaryUser.sandContract.transfer( faucetContract.address, TOTAL_SUPPLY ) ); await expectEventWithArgs(sandContract, transferReceipt, 'Transfer'); const ASKED_AMOUNT = DECIMALS_18.mul(3); const receiveReceipt = await waitFor( user.faucetContract.send(ASKED_AMOUNT) ); const receiveEvent = await expectEventWithArgs( faucetContract, receiveReceipt, 'FaucetSent' ); const balance = await sandContract.balanceOf(user.address); expect(receiveEvent.args[0]).to.equal(user.address); // receiver expect(receiveEvent.args[1]).to.equal(ASKED_AMOUNT.toString()); // amount expect(balance.toString()).to.equal(ASKED_AMOUNT.toString()); // amount }); it('setLimit fail for user that is not deployer', async function () { const setUp = await setupFaucet(); const {faucetContract, others} = setUp; const user = await setupUser(others[4], { faucetContract, }); const NEW_LIMIT = DECIMALS_18.mul(25); await expect(user.faucetContract.setLimit(NEW_LIMIT)).to.be.revertedWith( 'Ownable: caller is not the owner' ); }); });
the_stack
// The following TSLint rules have been disabled: // unified-signatures: Because there is useful information in the argument names of the overloaded signatures // Convention: // Use 'union types' when: // - parameter types have similar signature type (i.e. 'string | ReadonlyArray<string>') // - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys']) // An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters // have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter // has the same semantic meaning with declaring an overload method by using `commands: ReadonlyArray<string>`, // thus it's preferred to use `command: string | ReadonlyArray<string>` // Use parameterless declaration instead of declaring all parameters optional, // when all parameters are optional and more than one import { DetailedArguments, Configuration } from 'yargs-parser'; declare namespace yargs { type BuilderCallback<T, R> = ((args: Argv<T>) => PromiseLike<Argv<R>>) | ((args: Argv<T>) => Argv<R>) | ((args: Argv<T>) => void); type ParserConfigurationOptions = Configuration & { /** Sort commands alphabetically. Default is `false` */ 'sort-commands': boolean; }; /** * The type parameter `T` is the expected shape of the parsed options. * `Arguments<T>` is those options plus `_` and `$0`, and an indexer falling * back to `unknown` for unknown options. * * For the return type / `argv` property, we create a mapped type over * `Arguments<T>` to simplify the inferred type signature in client code. */ interface Argv<T = {}> { (): { [key in keyof Arguments<T>]: Arguments<T>[key] }; (args: ReadonlyArray<string>, cwd?: string): Argv<T>; /** * Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa. * * Optionally `.alias()` can take an object that maps keys to aliases. * Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings. */ // Aliases for previously declared options can inherit the types of those options. alias<K1 extends keyof T, K2 extends string>(shortName: K1, longName: K2 | ReadonlyArray<K2>): Argv<T & { [key in K2]: T[K1] }>; alias<K1 extends keyof T, K2 extends string>(shortName: K2, longName: K1 | ReadonlyArray<K1>): Argv<T & { [key in K2]: T[K1] }>; alias(shortName: string | ReadonlyArray<string>, longName: string | ReadonlyArray<string>): Argv<T>; alias(aliases: { [shortName: string]: string | ReadonlyArray<string> }): Argv<T>; /** * Get the arguments as a plain old object. * * Arguments without a corresponding flag show up in the `argv._` array. * * The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl. * * If `yargs` is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js), * it will ignore the first parameter since it expects it to be the script name. In order to override * this behavior, use `.parse(process.argv.slice(1))` instead of .argv and the first parameter won't be ignored. */ argv: { [key in keyof Arguments<T>]: Arguments<T>[key] }; /** * Tell the parser to interpret `key` as an array. * If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`. * Also, if you use the option multiple times all the values will be flattened in one array so `--foo foo --foo bar` will be parsed as `['foo', 'bar']` * * When the option is used with a positional, use `--` to tell `yargs` to stop adding values to the array. */ array<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToArray<T[key]> }>; array<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: Array<string | number> | undefined }>; /** * Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`. * * `key` will default to `false`, unless a `default(key, undefined)` is explicitly set. * * If `key` is an array, interpret all the elements as booleans. */ boolean<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: boolean | undefined }>; boolean<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: boolean | undefined }>; /** * Check that certain conditions are met in the provided arguments. * @param func Called with two arguments, the parsed `argv` hash and an array of options and their aliases. * If `func` throws or returns a non-truthy value, show the thrown error, usage information, and exit. * @param global Indicates whether `check()` should be enabled both at the top-level and for each sub-command. */ check(func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean): Argv<T>; /** * Limit valid values for key to a predefined set of choices, given as an array or as an individual value. * If this method is called multiple times, all enumerated values will be merged together. * Choices are generally strings or numbers, and value matching is case-sensitive. * * Optionally `.choices()` can take an object that maps multiple keys to their choices. * * Choices can also be specified as choices in the object given to `option()`. */ choices<K extends keyof T, C extends ReadonlyArray<any>>(key: K, values: C): Argv<Omit<T, K> & { [key in K]: C[number] | undefined }>; choices<K extends string, C extends ReadonlyArray<any>>(key: K, values: C): Argv<T & { [key in K]: C[number] | undefined }>; choices<C extends { [key: string]: ReadonlyArray<any> }>(choices: C): Argv<Omit<T, keyof C> & { [key in keyof C]: C[key][number] | undefined }>; /** * Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`. * * The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error. * The returned value will be used as the value for `key` (or one of its aliases) in `argv`. * * If the function throws, the error will be treated as a validation failure, delegating to either a custom `.fail()` handler or printing the error message in the console. * * Coercion will be applied to a value after all other modifications, such as `.normalize()`. * * Optionally `.coerce()` can take an object that maps several keys to their respective coercion function. * * You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`. * * If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed */ coerce<K extends keyof T, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<Omit<T, K> & { [key in K]: V | undefined }>; coerce<K extends string, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<T & { [key in K]: V | undefined }>; coerce<O extends { [key: string]: (arg: any) => any }>(opts: O): Argv<Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> | undefined }>; /** * Define the commands exposed by your application. * @param command Should be a string representing the command or an array of strings representing the command and its aliases. * @param description Use to provide a description for each command your application accepts (the values stored in `argv._`). * Set `description` to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion. * @param [builder] Object to give hints about the options that your command accepts. * Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help. * * Note that when `void` is returned, the handler `argv` object type will not include command-specific arguments. * @param [handler] Function, which will be executed with the parsed `argv` object. */ command<U = T>( command: string | ReadonlyArray<string>, description: string, builder?: BuilderCallback<T, U>, handler?: (args: Arguments<U>) => void, middlewares?: MiddlewareFunction[], deprecated?: boolean | string, ): Argv<U>; command<O extends { [key: string]: Options }>( command: string | ReadonlyArray<string>, description: string, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void, middlewares?: MiddlewareFunction[], deprecated?: boolean | string, ): Argv<T>; command<U>(command: string | ReadonlyArray<string>, description: string, module: CommandModule<T, U>): Argv<U>; command<U = T>( command: string | ReadonlyArray<string>, showInHelp: false, builder?: BuilderCallback<T, U>, handler?: (args: Arguments<U>) => void, middlewares?: MiddlewareFunction[], deprecated?: boolean | string, ): Argv<T>; command<O extends { [key: string]: Options }>( command: string | ReadonlyArray<string>, showInHelp: false, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void, ): Argv<T>; command<U>(command: string | ReadonlyArray<string>, showInHelp: false, module: CommandModule<T, U>): Argv<U>; command<U>(module: CommandModule<T, U>): Argv<U>; // Advanced API /** Apply command modules from a directory relative to the module calling this method. */ commandDir(dir: string, opts?: RequireDirectoryOptions): Argv<T>; /** * Enable bash/zsh-completion shortcuts for commands and options. * * If invoked without parameters, `.completion()` will make completion the command to output the completion script. * * @param [cmd] When present in `argv._`, will result in the `.bashrc` or `.zshrc` completion script being outputted. * To enable bash/zsh completions, concat the generated script to your `.bashrc` or `.bash_profile` (or `.zshrc` for zsh). * @param [description] Provide a description in your usage instructions for the command that generates the completion scripts. * @param [func] Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method. */ completion(): Argv<T>; completion(cmd: string, func?: AsyncCompletionFunction): Argv<T>; completion(cmd: string, func?: SyncCompletionFunction): Argv<T>; completion(cmd: string, func?: PromiseCompletionFunction): Argv<T>; completion(cmd: string, description?: string | false, func?: AsyncCompletionFunction): Argv<T>; completion(cmd: string, description?: string | false, func?: SyncCompletionFunction): Argv<T>; completion(cmd: string, description?: string | false, func?: PromiseCompletionFunction): Argv<T>; /** * Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file. * The file is loaded and parsed, and its properties are set as arguments. * Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly. * * If invoked without parameters, `.config()` will make --config the option to pass the JSON config file. * * @param [description] Provided to customize the config (`key`) option in the usage string. * @param [explicitConfigurationObject] An explicit configuration `object` */ config(): Argv<T>; config(key: string | ReadonlyArray<string>, description?: string, parseFn?: (configPath: string) => object): Argv<T>; config(key: string | ReadonlyArray<string>, parseFn: (configPath: string) => object): Argv<T>; config(explicitConfigurationObject: object): Argv<T>; /** * Given the key `x` is set, the key `y` must not be set. `y` can either be a single string or an array of argument names that `x` conflicts with. * * Optionally `.conflicts()` can accept an object specifying multiple conflicting keys. */ conflicts(key: string, value: string | ReadonlyArray<string>): Argv<T>; conflicts(conflicts: { [key: string]: string | ReadonlyArray<string> }): Argv<T>; /** * Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`. */ count<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: number }>; count<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number }>; /** * Set `argv[key]` to `value` if no option was specified in `process.argv`. * * Optionally `.default()` can take an object that maps keys to default values. * * The default value can be a `function` which returns a value. The name of the function will be used in the usage string. * * Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions. */ default<K extends keyof T, V>(key: K, value: V, description?: string): Argv<Omit<T, K> & { [key in K]: V }>; default<K extends string, V>(key: K, value: V, description?: string): Argv<T & { [key in K]: V }>; default<D extends { [key: string]: any }>(defaults: D, description?: string): Argv<Omit<T, keyof D> & D>; /** * @deprecated since version 6.6.0 * Use '.demandCommand()' or '.demandOption()' instead */ demand<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; demand<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>; demand(key: string | ReadonlyArray<string>, required?: boolean): Argv<T>; demand(positionals: number, msg: string): Argv<T>; demand(positionals: number, required?: boolean): Argv<T>; demand(positionals: number, max: number, msg?: string): Argv<T>; /** * @param key If is a string, show the usage information and exit if key wasn't specified in `process.argv`. * If is an array, demand each element. * @param msg If string is given, it will be printed when the argument is missing, instead of the standard error message. * @param demand Controls whether the option is demanded; this is useful when using .options() to specify command line parameters. */ demandOption<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; demandOption<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>; demandOption(key: string | ReadonlyArray<string>, demand?: boolean): Argv<T>; /** * Demand in context of commands. * You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met. */ demandCommand(): Argv<T>; demandCommand(min: number, minMsg?: string): Argv<T>; demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>; /** * Shows a [deprecated] notice in front of the option */ deprecateOption(option: string, msg?: string): Argv<T>; /** * Describe a `key` for the generated usage information. * * Optionally `.describe()` can take an object that maps keys to descriptions. */ describe(key: string | ReadonlyArray<string>, description: string): Argv<T>; describe(descriptions: { [key: string]: string }): Argv<T>; /** Should yargs attempt to detect the os' locale? Defaults to `true`. */ detectLocale(detect: boolean): Argv<T>; /** * Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments. * * Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo) * * If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv. * * Program arguments are defined in this order of precedence: * 1. Command line args * 2. Env vars * 3. Config file/objects * 4. Configured defaults * * Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration. */ env(): Argv<T>; env(prefix: string): Argv<T>; env(enable: boolean): Argv<T>; /** A message to print at the end of the usage instructions */ epilog(msg: string): Argv<T>; /** A message to print at the end of the usage instructions */ epilogue(msg: string): Argv<T>; /** * Give some example invocations of your program. * Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. * Examples will be printed out as part of the help message. */ example(command: string, description: string): Argv<T>; example(command: ReadonlyArray<[string, string?]>): Argv<T>; /** Manually indicate that the program should exit, and provide context about why we wanted to exit. Follows the behavior set by `.exitProcess().` */ exit(code: number, err: Error): void; /** * By default, yargs exits the process when the user passes a help flag, the user uses the `.version` functionality, validation fails, or the command handler fails. * Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated. */ exitProcess(enabled: boolean): Argv<T>; /** * Method to execute when a failure occurs, rather than printing the failure message. * @param func Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred. */ fail(func: (msg: string, err: Error, yargs: Argv<T>) => any): Argv<T>; /** * Allows to programmatically get completion choices for any line. * @param args An array of the words in the command line to complete. * @param done The callback to be called with the resulting completions. */ getCompletion(args: ReadonlyArray<string>, done: (completions: ReadonlyArray<string>) => void): Argv<T>; /** * Indicate that an option (or group of options) should not be reset when a command is executed * * Options default to being global. */ global(key: string | ReadonlyArray<string>): Argv<T>; /** Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions */ group(key: string | ReadonlyArray<string>, groupName: string): Argv<T>; /** Hides a key from the generated usage information. Unless a `--show-hidden` option is also passed with `--help` (see `showHidden()`). */ hide(key: string): Argv<T>; /** * Configure an (e.g. `--help`) and implicit command that displays the usage string and exits the process. * By default yargs enables help on the `--help` option. * * Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command. * If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command. * * If invoked without parameters, `.help()` will use `--help` as the option and help as the implicit command to trigger help output. * * @param [description] Customizes the description of the help option in the usage string. * @param [enableExplicit] If `false` is provided, it will disable --help. */ help(): Argv<T>; help(enableExplicit: boolean): Argv<T>; help(option: string, enableExplicit: boolean): Argv<T>; help(option: string, description?: string, enableExplicit?: boolean): Argv<T>; /** * Given the key `x` is set, it is required that the key `y` is set. * y` can either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with `x`. * * Optionally `.implies()` can accept an object specifying multiple implications. */ implies(key: string, value: string | ReadonlyArray<string>): Argv<T>; implies(implies: { [key: string]: string | ReadonlyArray<string> }): Argv<T>; /** * Return the locale that yargs is currently using. * * By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language. */ locale(): string; /** * Override the auto-detected locale from the user's operating system with a static locale. * Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable. */ locale(loc: string): Argv<T>; /** * Define global middleware functions to be called first, in list order, for all cli command. * @param callbacks Can be a function or a list of functions. Each callback gets passed a reference to argv. * @param [applyBeforeValidation] Set to `true` to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing. */ middleware(callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>, applyBeforeValidation?: boolean): Argv<T>; /** * The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity. * * Optionally `.nargs()` can take an object of `key`/`narg` pairs. */ nargs(key: string, count: number): Argv<T>; nargs(nargs: { [key: string]: number }): Argv<T>; /** The key provided represents a path and should have `path.normalize()` applied. */ normalize<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>; normalize<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>; /** * Tell the parser to always interpret key as a number. * * If `key` is an array, all elements will be parsed as numbers. * * If the option is given on the command line without a value, `argv` will be populated with `undefined`. * * If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`. * * Note that decimals, hexadecimals, and scientific notation are all accepted. */ number<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToNumber<T[key]> }>; number<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number | undefined }>; /** * Method to execute when a command finishes successfully. * @param func Is called with the successful result of the command that finished. */ onFinishCommand(func: (result: any) => void): Argv<T>; /** * This method can be used to make yargs aware of options that could exist. * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option. */ option<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>; option<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>; option<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>; /** * This method can be used to make yargs aware of options that could exist. * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option. */ options<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>; options<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>; options<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>; /** * Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may either be a pre-processed argv array, or a raw argument string. * * Note: Providing a callback to parse() disables the `exitProcess` setting until after the callback is invoked. * @param [context] Provides a useful mechanism for passing state information to commands */ parse(): { [key in keyof Arguments<T>]: Arguments<T>[key] }; parse(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] }; /** * If the arguments have not been parsed, this property is `false`. * * If the arguments have been parsed, this contain detailed parsed arguments. */ parsed: DetailedArguments | false; /** Allows to configure advanced yargs features. */ parserConfiguration(configuration: Partial<ParserConfigurationOptions>): Argv<T>; /** * Similar to `config()`, indicates that yargs should interpret the object from the specified key in package.json as a configuration object. * @param [cwd] If provided, the package.json will be read from this location */ pkgConf(key: string | ReadonlyArray<string>, cwd?: string): Argv<T>; /** * Allows you to configure a command's positional arguments with an API similar to `.option()`. * `.positional()` should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error. */ positional<K extends keyof T, O extends PositionalOptions>(key: K, opt: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>; positional<K extends string, O extends PositionalOptions>(key: K, opt: O): Argv<T & { [key in K]: InferredOptionType<O> }>; /** Should yargs provide suggestions regarding similar commands if no matching command is found? */ recommendCommands(): Argv<T>; /** * @deprecated since version 6.6.0 * Use '.demandCommand()' or '.demandOption()' instead */ require<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; require(key: string, msg: string): Argv<T>; require(key: string, required: boolean): Argv<T>; require(keys: ReadonlyArray<number>, msg: string): Argv<T>; require(keys: ReadonlyArray<number>, required: boolean): Argv<T>; require(positionals: number, required: boolean): Argv<T>; require(positionals: number, msg: string): Argv<T>; /** * @deprecated since version 6.6.0 * Use '.demandCommand()' or '.demandOption()' instead */ required<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; required(key: string, msg: string): Argv<T>; required(key: string, required: boolean): Argv<T>; required(keys: ReadonlyArray<number>, msg: string): Argv<T>; required(keys: ReadonlyArray<number>, required: boolean): Argv<T>; required(positionals: number, required: boolean): Argv<T>; required(positionals: number, msg: string): Argv<T>; requiresArg(key: string | ReadonlyArray<string>): Argv<T>; /** * @deprecated since version 6.6.0 * Use '.global()' instead */ reset(): Argv<T>; /** Set the name of your script ($0). Default is the base filename executed by node (`process.argv[1]`) */ scriptName($0: string): Argv<T>; /** * Generate a bash completion script. * Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options. */ showCompletionScript(): Argv<T>; /** * Configure the `--show-hidden` option that displays the hidden keys (see `hide()`). * @param option If `boolean`, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument is `false`. * If `string` it changes the key name ("--show-hidden"). * @param description Changes the default description ("Show hidden options") */ showHidden(option?: string | boolean): Argv<T>; showHidden(option: string, description?: string): Argv<T>; /** * Print the usage data using the console function consoleLevel for printing. * @param [consoleLevel='error'] */ showHelp(consoleLevel?: string): Argv<T>; /** * Provide the usage data as a string. * @param printCallback a function with a single argument. */ showHelp(printCallback: (s: string) => void): Argv<T>; /** * By default, yargs outputs a usage string if any error is detected. * Use the `.showHelpOnFail()` method to customize this behavior. * @param enable If `false`, the usage string is not output. * @param [message] Message that is output after the error message. */ showHelpOnFail(enable: boolean, message?: string): Argv<T>; /** Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. */ skipValidation(key: string | ReadonlyArray<string>): Argv<T>; /** * Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error. * * Unrecognized commands will also be reported as errors. */ strict(): Argv<T>; strict(enabled: boolean): Argv<T>; /** * Similar to `.strict()`, except that it only applies to unrecognized options. A * user can still provide arbitrary positional options, but unknown options * will raise an error. */ strictOptions(): Argv<T>; strictOptions(enabled: boolean): Argv<T>; /** * Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input. * * If `key` is an array, interpret all the elements as strings. * * `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers. */ string<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>; string<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>; // Intended to be used with '.wrap()' terminalWidth(): number; updateLocale(obj: { [key: string]: string }): Argv<T>; /** * Override the default strings used by yargs with the key/value pairs provided in obj * * If you explicitly specify a locale(), you should do so before calling `updateStrings()`. */ updateStrings(obj: { [key: string]: string }): Argv<T>; /** * Set a usage message to show which commands to use. * Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. * * If the optional `description`/`builder`/`handler` are provided, `.usage()` acts an an alias for `.command()`. * This allows you to use `.usage()` to configure the default command that will be run as an entry-point to your application * and allows you to provide configuration for the positional arguments accepted by your program: */ usage(message: string): Argv<T>; usage<U>(command: string | ReadonlyArray<string>, description: string, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>; usage<U>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>; usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, description: string, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>; usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>; /** * Add an option (e.g. `--version`) that displays the version number (given by the version parameter) and exits the process. * By default yargs enables version for the `--version` option. * * If no arguments are passed to version (`.version()`), yargs will parse the package.json of your module and use its version value. * * If the boolean argument `false` is provided, it will disable `--version`. */ version(): Argv<T>; version(version: string): Argv<T>; version(enable: boolean): Argv<T>; version(optionKey: string, version: string): Argv<T>; version(optionKey: string, description: string, version: string): Argv<T>; /** * Format usage output to wrap at columns many columns. * * By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align). * Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions. */ wrap(columns: number | null): Argv<T>; } type Arguments<T = {}> = T & { /** Non-option arguments */ _: string[]; /** The script name or node command */ $0: string; /** All remaining options */ [argName: string]: unknown; }; interface RequireDirectoryOptions { /** Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. */ recurse?: boolean; /** The types of files to look for when requiring command modules. */ extensions?: ReadonlyArray<string>; /** * A synchronous function called for each command module encountered. * Accepts `commandObject`, `pathToFile`, and `filename` as arguments. * Returns `commandObject` to include the command; any falsy value to exclude/skip it. */ visit?: (commandObject: any, pathToFile?: string, filename?: string) => any; /** Whitelist certain modules */ include?: RegExp | ((pathToFile: string) => boolean); /** Blacklist certain modules. */ exclude?: RegExp | ((pathToFile: string) => boolean); } interface Options { /** string or array of strings, alias(es) for the canonical option key, see `alias()` */ alias?: string | ReadonlyArray<string>; /** boolean, interpret option as an array, see `array()` */ array?: boolean; /** boolean, interpret option as a boolean flag, see `boolean()` */ boolean?: boolean; /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */ choices?: Choices; /** function, coerce or transform parsed command line values into another value, see `coerce()` */ coerce?: (arg: any) => any; /** boolean, interpret option as a path to a JSON config file, see `config()` */ config?: boolean; /** function, provide a custom config parsing function, see `config()` */ configParser?: (configPath: string) => object; /** string or object, require certain keys not to be set, see `conflicts()` */ conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** boolean, interpret option as a count of boolean flags, see `count()` */ count?: boolean; /** value, set a default value for the option, see `default()` */ default?: any; /** string, use this description for the default value in help content, see `default()` */ defaultDescription?: string; /** * @deprecated since version 6.6.0 * Use 'demandOption' instead */ demand?: boolean | string; /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */ deprecate?: boolean | string; /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */ deprecated?: boolean | string; /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */ demandOption?: boolean | string; /** string, the option description for help content, see `describe()` */ desc?: string; /** string, the option description for help content, see `describe()` */ describe?: string; /** string, the option description for help content, see `describe()` */ description?: string; /** boolean, indicate that this key should not be reset when a command is invoked, see `global()` */ global?: boolean; /** string, when displaying usage instructions place the option under an alternative group heading, see `group()` */ group?: string; /** don't display option in help output. */ hidden?: boolean; /** string or object, require certain keys to be set, see `implies()` */ implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** number, specify how many arguments should be consumed for the option, see `nargs()` */ nargs?: number; /** boolean, apply path.normalize() to the option, see `normalize()` */ normalize?: boolean; /** boolean, interpret option as a number, `number()` */ number?: boolean; /** * @deprecated since version 6.6.0 * Use 'demandOption' instead */ require?: boolean | string; /** * @deprecated since version 6.6.0 * Use 'demandOption' instead */ required?: boolean | string; /** boolean, require the option be specified with a value, see `requiresArg()` */ requiresArg?: boolean; /** boolean, skips validation if the option is present, see `skipValidation()` */ skipValidation?: boolean; /** boolean, interpret option as a string, see `string()` */ string?: boolean; type?: "array" | "count" | PositionalOptionsType; } interface PositionalOptions { /** string or array of strings, see `alias()` */ alias?: string | ReadonlyArray<string>; /** boolean, interpret option as an array, see `array()` */ array?: boolean; /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */ choices?: Choices; /** function, coerce or transform parsed command line values into another value, see `coerce()` */ coerce?: (arg: any) => any; /** string or object, require certain keys not to be set, see `conflicts()` */ conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** value, set a default value for the option, see `default()` */ default?: any; /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */ demandOption?: boolean | string; /** string, the option description for help content, see `describe()` */ desc?: string; /** string, the option description for help content, see `describe()` */ describe?: string; /** string, the option description for help content, see `describe()` */ description?: string; /** string or object, require certain keys to be set, see `implies()` */ implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** boolean, apply path.normalize() to the option, see normalize() */ normalize?: boolean; type?: PositionalOptionsType; } /** Remove keys K in T */ type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] }; /** Remove undefined as a possible value for keys K in T */ type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined> }; /** Convert T to T[] and T | undefined to T[] | undefined */ type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>; /** Gives string[] if T is an array type, otherwise string. Preserves | undefined. */ type ToString<T> = (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>; /** Gives number[] if T is an array type, otherwise number. Preserves | undefined. */ type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>; type InferredOptionType<O extends Options | PositionalOptions> = O extends { default: any, coerce: (arg: any) => infer T } ? T : O extends { default: infer D } ? D : O extends { type: "count" } ? number : O extends { count: true } ? number : O extends { required: string | true } ? RequiredOptionType<O> : O extends { require: string | true } ? RequiredOptionType<O> : O extends { demand: string | true } ? RequiredOptionType<O> : O extends { demandOption: string | true } ? RequiredOptionType<O> : RequiredOptionType<O> | undefined; type RequiredOptionType<O extends Options | PositionalOptions> = O extends { type: "array", string: true } ? string[] : O extends { type: "array", number: true } ? number[] : O extends { type: "array", normalize: true } ? string[] : O extends { type: "string", array: true } ? string[] : O extends { type: "number", array: true } ? number[] : O extends { string: true, array: true } ? string[] : O extends { number: true, array: true } ? number[] : O extends { normalize: true, array: true } ? string[] : O extends { type: "array" } ? Array<string | number> : O extends { type: "boolean" } ? boolean : O extends { type: "number" } ? number : O extends { type: "string" } ? string : O extends { array: true } ? Array<string | number> : O extends { boolean: true } ? boolean : O extends { number: true } ? number : O extends { string: true } ? string : O extends { normalize: true } ? string : O extends { choices: ReadonlyArray<infer C> } ? C : O extends { coerce: (arg: any) => infer T } ? T : unknown; type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]> }; interface CommandModule<T = {}, U = {}> { /** array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored */ aliases?: ReadonlyArray<string> | string; /** object declaring the options the command accepts, or a function accepting and returning a yargs instance */ builder?: CommandBuilder<T, U>; /** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */ command?: ReadonlyArray<string> | string; /** boolean (or string) to show deprecation notice */ deprecated?: boolean | string; /** string used as the description for the command in help text, use `false` for a hidden command */ describe?: string | false; /** a function which will be passed the parsed argv. */ handler: (args: Arguments<U>) => void; } type ParseCallback<T = {}> = (err: Error | undefined, argv: Arguments<T>, output: string) => void; type CommandBuilder<T = {}, U = {}> = { [key: string]: Options } | ((args: Argv<T>) => Argv<U>) | ((args: Argv<T>) => PromiseLike<Argv<U>>); type SyncCompletionFunction = (current: string, argv: any) => string[]; type AsyncCompletionFunction = (current: string, argv: any, done: (completion: ReadonlyArray<string>) => void) => void; type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>; type MiddlewareFunction<T = {}> = (args: Arguments<T>) => void; type Choices = ReadonlyArray<string | number | true | undefined>; type PositionalOptionsType = "boolean" | "number" | "string"; } declare var yargs: yargs.Argv; export = yargs;
the_stack
import { mount } from '@vue/test-utils' import { Wrapper } from '@vue/test-utils/types' import MainComponent from '~/component.vue' import { MENU_POSITIONS } from '~/constants' import { VueCoolSelectComponentInterface } from '../../types/types' import createLocalVueWithPlugin from './helpers' const comp: VueCoolSelectComponentInterface & any = MainComponent describe('eventsListeners', () => { // обычный import возвращал undefined const Vue = require('vue') const itemsDefault = [ 'JS', 'PHP', 'CSS', 'HTML' ] it('checks click and then focus on input', () => { const localVue = createLocalVueWithPlugin() const wrapper = mount<VueCoolSelectComponentInterface>(comp, { localVue, propsData: { items: itemsDefault } }) // const mainElement = wrapper.find('.IZ-select') // mainElement.trigger('click') const inputForText = wrapper.find({ ref: 'IZ-select__input-for-text' }) wrapper.vm.onClick() // inputForText.trigger('focus') // inputForText.element.focus() expect(wrapper.vm.wishShowMenu).toBeTruthy() expect(wrapper.vm.hasMenu).toBeTruthy() expect(wrapper.emitted().focus).toBeTruthy() expect( inputForText.is(':focus') ).toBe(true) expect(wrapper.vm.focused).toBeTruthy() wrapper.vm.setBlured() expect(wrapper.emitted().blur).toBeTruthy() // expect( // inputForText.is(':focus') // ).toBe(false) expect(wrapper.vm.focused).toBeFalsy() }) it('checks onClick and onClickSelectItem', async () => { const items = itemsDefault const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items } }) wrapper.vm.onClick() expect(wrapper.vm.wishShowMenu).toBeTruthy() expect(wrapper.vm.hasMenu).toBeTruthy() const selectMenu = wrapper.find({ ref: 'IZ-select__menu-' + MENU_POSITIONS.BOTTOM }) // @ts-ignore const selectItems = selectMenu.findAll(`.IZ-select__menu--at-${MENU_POSITIONS.BOTTOM} .IZ-select__item`) expect(selectMenu.isVisible()).toBeTruthy() expect(selectItems.length).toBe(items.length) const selectItem = items[0] wrapper.vm.onClickSelectItem(selectItem) expect(wrapper.vm.selectedItem).toBe(selectItem) expect(wrapper.vm.searchData).toBe('') const inputForText = wrapper.find({ ref: 'IZ-select__input-for-text' }) expect( inputForText.is(':focus') ).toBe(true) expect(wrapper.vm.wishShowMenu).toBe(false) expect(wrapper.vm.selectedItemByArrows).toBe(null) await Vue.nextTick() expect(wrapper.emitted().select).toBeTruthy() expect( wrapper.emitted().select[wrapper.emitted().select.length - 1][0] ).toBe(selectItem) }) it('checks onClick with disabled', async () => { const wrapperWithDisabled = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, disabled: true } }) const wrapperWithReadonly = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, readonly: true } }) await check(wrapperWithDisabled) await check(wrapperWithReadonly) // тут нет ошибки, IDE ошибается! async function check (wrapper: Wrapper<VueCoolSelectComponentInterface>) { wrapper.vm.onClick() // хотя должно быть не как не undefined, а null (похоже null значит undefined в этих инструментах тестов) expect(wrapper.vm.selectedItem).toBe(undefined) const inputForText = wrapper.find({ ref: 'IZ-select__input-for-text' }) expect( inputForText.is(':focus') ).toBe(false) expect(wrapper.vm.wishShowMenu).toBe(false) await Vue.nextTick() expect(wrapper.emitted().select).toBeFalsy() } }) it('checks onSelectByArrow with disabled and readonly', async () => { const wrapperDisabled = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, disabled: true } }) expect( wrapperDisabled.vm.onSelectByArrow({ preventDefault: jest.fn() }) ).toBeUndefined() const wrapperReadonly = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, readonly: true } }) expect( wrapperReadonly.vm.onSelectByArrow({ preventDefault: jest.fn() }) ).toBeUndefined() }) it('checks onSelectByArrow ', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, arrowsDisableInstantSelection: false } }) const eventUp = { key: 'ArrowUp' } const eventDown = { key: 'ArrowDown' } let currentArrowsIndex = -1 const events = [ // arrowsIndex changelog: 0, 1, 2, 3, 0, 1, 0, 3, 2, 1, 0... eventDown, eventDown, eventDown, eventDown, eventDown, eventDown, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp, eventUp ] for await (const e of events) { await onSelectByArrow(e) } wrapper.setProps({ arrowsDisableInstantSelection: true }) for await (const e of events) { await onSelectByArrow(e) } async function onSelectByArrow (e) { // Arrange const preventDefaultMock = jest.fn() e.preventDefault = preventDefaultMock // Action wrapper.vm.onSelectByArrow(e) // Assert // expect(preventDefaultMock.mock.calls.length).toBe(1) if (e.key === 'ArrowUp') { currentArrowsIndex-- } else if (e.key === 'ArrowDown') { currentArrowsIndex++ } const end = wrapper.vm.itemsComputed.length - 1 if (currentArrowsIndex < 0) { currentArrowsIndex = end } if (currentArrowsIndex > end) { currentArrowsIndex = 0 } const expectedArrowsIndex = currentArrowsIndex const itemByArrowsIndex = wrapper.vm.itemsComputed[expectedArrowsIndex] expect(wrapper.vm.wishShowMenu).toBeTruthy() expect(wrapper.vm.arrowsIndex).toBe(expectedArrowsIndex) if (wrapper.vm.arrowsDisableInstantSelection) { expect(wrapper.vm.selectedItemByArrows).toBe(itemByArrowsIndex) } else { expect(wrapper.vm.searchData).toBe('') expect(wrapper.vm.selectedItem).toBe(itemByArrowsIndex) expect(wrapper.vm.selectedItemByArrows).toBeNull() } await Vue.nextTick() expect(wrapper.emitted().select).toBeTruthy() } }) it('checks onSearchKeyDown disabled and readonly', async () => { const wrapperDisabled = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, disabled: true } }) expect( wrapperDisabled.vm.onSearchKeyDown({}) ).toBeUndefined() const wrapperReadonly = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, readonly: true } }) expect( wrapperReadonly.vm.onSearchKeyDown({}) ).toBeUndefined() }) it('checks onSearchKeyDown ignore keys', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault } }) const keys = ['Enter', 'ArrowDown', 'ArrowUp', 'Tab'] for (const key of keys) { expect( wrapper.vm.onSearchKeyDown({ key }) ).toBeUndefined() } }) it('checks onSearchKeyDown reset on Backspace', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault } }) wrapper.vm.onSearchKeyDown({ target: { value: '' }, key: 'Backspace' }) expect( wrapper.vm.selectedItem ).toBeNull() expect( wrapper.vm.arrowsIndex ).toBeNull() expect( wrapper.vm.wishShowMenu ).toBeTruthy() expect(wrapper.emitted().keydown).toBeTruthy() }) it('checks onSearchKeyUp', async () => { const wrapperDisabled = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, disabled: true } }) expect( wrapperDisabled.vm.onSearchKeyUp({}) ).toBeUndefined() const wrapperReadonly = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, readonly: true } }) expect( wrapperReadonly.vm.onSearchKeyUp({}) ).toBeUndefined() const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault } }) const event = {} wrapper.vm.onSearchKeyUp(event) expect(wrapper.emitted().keyup).toBeTruthy() expect(wrapper.emitted().keyup[0][0]).toBe(event) }) it('checks onSearch disabled and readonly', async () => { const localVue = createLocalVueWithPlugin() const wrapperDisabled = mount<VueCoolSelectComponentInterface>(comp, { localVue, propsData: { items: itemsDefault, disabled: true } }) expect( wrapperDisabled.vm.onSearch({}) ).toBeUndefined() const wrapperReadonly = mount<VueCoolSelectComponentInterface>(comp, { localVue, propsData: { items: itemsDefault, readonly: true } }) expect( wrapperReadonly.vm.onSearch({}) ).toBeUndefined() const wrapper = mount<VueCoolSelectComponentInterface>(comp, { localVue, propsData: { items: itemsDefault } }) const event = { target: { value: 'test value' } } wrapper.vm.onSearch(event) expect(wrapper.vm.selectedItemByArrows).toBeNull() expect(wrapper.vm.selectedItem).toBeNull() expect(wrapper.vm.arrowsIndex).toBeNull() expect(wrapper.vm.searchData).toBe(event.target.value) expect(wrapper.emitted().search).toBeTruthy() expect(wrapper.emitted().search[0][0]).toBe(event.target.value) }) it('checks onScroll with ignore', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, scrollItemsLimit: 999999999 } }) // dummy const event = {} expect( wrapper.vm.onScroll(event) ).toBeUndefined() expect(wrapper.emitted().scroll).toBeTruthy() expect(wrapper.emitted().scroll[0][0]).toBe(event) }) it('checks onScroll', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault, scrollItemsLimit: 0 } }) const event = { target: { scrollHeight: 400, scrollTop: 150, clientHeight: 150 } } const beforeVal = wrapper.vm.scrollItemsLimitCurrent expect( wrapper.vm.onScroll(event) ).toBeUndefined() expect(wrapper.emitted().scroll).toBeTruthy() expect(wrapper.emitted().scroll[0][0]).toBe(event) expect(wrapper.vm.scrollItemsLimitCurrent).toBe(beforeVal + wrapper.vm.scrollItemsLimitAddAfterScroll) }) const onEnterEvent = { preventDefault () {} } it('checks onEnter menu', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault } }) expect( wrapper.vm.onEnter(onEnterEvent) ).toBeUndefined() expect(wrapper.vm.wishShowMenu).toBe(true) expect( wrapper.vm.onEnter(onEnterEvent) ).toBeUndefined() expect(wrapper.vm.wishShowMenu).toBe(false) expect( wrapper.vm.onEnter(onEnterEvent) ).toBeUndefined() expect(wrapper.vm.wishShowMenu).toBe(true) }) it('checks onEnter firstItem ', async () => { const wrapper = mount<VueCoolSelectComponentInterface>(comp, { propsData: { items: itemsDefault } }) expect( wrapper.vm.onEnter(onEnterEvent) ).toBeUndefined() expect(wrapper.vm.wishShowMenu).toBe(true) expect( wrapper.vm.onEnter(onEnterEvent) ).toBeUndefined() expect(wrapper.vm.selectedItem).toBe(wrapper.vm.itemsComputed[0]) expect(wrapper.vm.selectedItemByArrows).toBe(null) expect(wrapper.vm.searchData).toBe('') await Vue.nextTick() expect(wrapper.emitted().select).toBeTruthy() }) })
the_stack
import { gte } from "semver"; import { assert, ASTNode, Block, ContractDefinition, DataLocation, Expression, FunctionDefinition, FunctionVisibility, MemberAccess, Mutability, PPIsh, Statement, StateVariableVisibility, StructDefinition, TypeName, TypeNode, UncheckedBlock, VariableDeclaration } from "solc-typed-ast"; import { SForAll, SId, SLet, SUnaryOperation, SUserFunctionDefinition, VarDefSite } from "../spec-lang/ast"; import { SemMap, StateVarScope, TypeEnv } from "../spec-lang/tc"; import { last } from "../util"; import { AnnotationMetaData } from "./annotations"; import { InstrumentationContext } from "./instrumentation_context"; import { makeTypeString } from "./type_string"; import { FactoryMap, ScribbleFactory, StructMap } from "./utils"; export enum InstrumentationSiteType { FunctionAnnotation, ContractInvariant, UserDefinedFunction, StateVarUpdated, Assert } export type ASTMap = Map<ASTNode, ASTNode>; type PositionInBlock = "start" | "end" | ["after", Statement] | ["before", Statement]; type Marker = [Block, PositionInBlock]; export function defSiteToKey(defSite: VarDefSite): string { if (defSite instanceof VariableDeclaration) { return `${defSite.id}`; } if (defSite instanceof Array && defSite[0] instanceof SLet) { return `let_${defSite[0].id}_${defSite[1]}`; } if (defSite instanceof Array && defSite[0] instanceof StateVarScope) { return `svar_path_binding_${defSite[0].annotation.id}_${defSite[1]}`; } if (defSite instanceof SForAll) { return `forall_${defSite.id}`; } assert(false, "NYI debug info for def site {0}", defSite as PPIsh); } export class DbgIdsMap extends StructMap<[VarDefSite], string, [SId[], Expression, TypeNode]> { protected getName(id: VarDefSite): string { return defSiteToKey(id); } } class AnnotationDebugMap extends FactoryMap<[AnnotationMetaData], number, DbgIdsMap> { protected getName(md: AnnotationMetaData): number { return md.parsedAnnot.id; } protected makeNew(): DbgIdsMap { return new DbgIdsMap(); } } /** * Class containing all the context necessary to transpile * a group of spec expression into Solidity code. * * This class is responsible for ensuring that there are no collisions in the * binding names generated while transpiling the expressions. */ export class TranspilingContext { /** * Map from 'binding keys' to the actual temporary binding names. 'binding keys' uniquely identify * the location where a given temporary is generated. We use this 2-level mapping to avoid name collisions */ private bindingMap: Map<string, string> = new Map(); /** * Map from a binding name to the corresponding `VariableDeclaration` for the member field for this binding. */ private bindingDefMap: Map<string, VariableDeclaration> = new Map(); /** * A ref-counter for how many times the temporary bindings struct and temporary bindings var have been used. * As on optimization we only emit those in `finalize()` only if `varRefc > 0`. */ private varRefc = 0; /** * A struct definition containing any temporary values used in the compilation of this context */ private bindingsStructDef: StructDefinition; /** * The declaration of a local var of type `this.bindingsStructDef` used for temporary values. */ private bindingsVar: VariableDeclaration; /** * Positions where 'old' statements are inserted. This is a stack to support building expressions with nested scopes */ private oldMarkerStack?: Marker[]; /** * Positions where statements outside of an `old` context are inserted. This is a stack to support building expressions with nested scopes */ private newMarkerStack!: Marker[]; public get factory(): ScribbleFactory { return this.instrCtx.factory; } /** * Keep track of any UncheckedBlocks inserted by the context, so that we can prune out the empty ones in `finalize()` */ private uncheckedBlocks: UncheckedBlock[] = []; /** * Current annotation being transpiled. Note this can change through the lifetime of a single TranspilingContext object. */ public curAnnotation!: AnnotationMetaData; public readonly contract: ContractDefinition; public readonly dbgInfo = new AnnotationDebugMap(); public get containerContract(): ContractDefinition { const fun = this.containerFun; assert(fun.vScope instanceof ContractDefinition, `Unexpected free function ${fun.name}`); return fun.vScope; } constructor( public readonly typeEnv: TypeEnv, public readonly semInfo: SemMap, public readonly containerFun: FunctionDefinition, public readonly instrCtx: InstrumentationContext, public readonly instrSiteType: InstrumentationSiteType ) { // Create the StructDefinition for temporary bindings. const contract = this.containerFun.vScope; assert( contract instanceof ContractDefinition, "Can't put instrumentation into free functions." ); this.contract = contract; const structName = instrCtx.nameGenerator.getFresh("vars"); const canonicalStructName = `${contract.name}.${structName}`; this.bindingsStructDef = this.factory.makeStructDefinition( structName, canonicalStructName, contract.id, FunctionVisibility.Private, [] ); const bindingsVarType = this.factory.makeUserDefinedTypeName( "<missing>", structName, this.bindingsStructDef.id ); // Create the local struct variable where the temporary bindigngs live this.bindingsVar = this.factory.makeVariableDeclaration( false, false, instrCtx.structVar, this.containerFun.id, false, DataLocation.Memory, StateVariableVisibility.Default, Mutability.Mutable, makeTypeString(bindingsVarType, DataLocation.Memory), undefined, bindingsVarType ); if (gte(instrCtx.compilerVersion, "0.8.0")) { const containerBody = this.containerFun.vBody as Block; if ( this.instrSiteType === InstrumentationSiteType.FunctionAnnotation || this.instrSiteType === InstrumentationSiteType.StateVarUpdated ) { const uncheckedBlock = this.factory.makeUncheckedBlock([]); this.uncheckedBlocks.push(uncheckedBlock); containerBody.insertAtBeginning(uncheckedBlock); this.oldMarkerStack = [[uncheckedBlock, "end"]]; } const newUncheckedBlock = this.factory.makeUncheckedBlock([]); this.uncheckedBlocks.push(newUncheckedBlock); containerBody.appendChild(newUncheckedBlock); this.newMarkerStack = [[newUncheckedBlock, "end"]]; } else { const containerBody = this.containerFun.vBody as Block; if ( this.instrSiteType === InstrumentationSiteType.FunctionAnnotation || this.instrSiteType === InstrumentationSiteType.StateVarUpdated ) { const firstStmt = containerBody.vStatements[0]; this.oldMarkerStack = [[containerBody, ["before", firstStmt]]]; } this.newMarkerStack = [[containerBody, "end"]]; } if (instrCtx.assertionMode === "mstore") { this.addBinding( instrCtx.scratchField, this.factory.makeElementaryTypeName("<missing>", "uint256") ); } } private _insertStatement(stmt: Statement, position: Marker): void { const [block, posInBlock] = position; if (posInBlock === "start") { block.insertAtBeginning(stmt); } else if (posInBlock === "end") { block.appendChild(stmt); } else if (posInBlock[0] === "before") { block.insertBefore(stmt, posInBlock[1]); } else if (posInBlock[0] === "after") { block.insertAfter(stmt, posInBlock[1]); } else { throw new Error(`Unknown position ${posInBlock}`); } } private getMarkerStack(isOld: boolean): Marker[] { if (isOld) { if (this.oldMarkerStack === undefined) { throw new Error( `InternalError: cannot insert statement in the old context of ${this.containerFun.name}. Not support for instrumentation site.` ); } return this.oldMarkerStack; } else { return this.newMarkerStack; } } insertStatement(arg: Statement | Expression, isOld: boolean, addToCurAnnotation = false): void { if (arg instanceof Expression) { arg = this.factory.makeExpressionStatement(arg); } this._insertStatement(arg, last(this.getMarkerStack(isOld))); if (addToCurAnnotation) { this.instrCtx.addAnnotationInstrumentation(this.curAnnotation, arg); } } insertAssignment( lhs: Expression, rhs: Expression, isOld: boolean, addToCurAnnotation = false ): Statement { const assignment = this.factory.makeAssignment("<missing>", "=", lhs, rhs); const stmt = this.factory.makeExpressionStatement(assignment); this.insertStatement(stmt, isOld, addToCurAnnotation); return stmt; } pushMarker(marker: Marker, isOld: boolean): void { this.getMarkerStack(isOld).push(marker); } popMarker(isOld: boolean): void { const stack = this.getMarkerStack(isOld); assert(stack.length > 1, "Popping bottom marker - shouldn't happen"); stack.pop(); } /** * Reset a marker stack to a new starting position. This is used for transpiling assertions, as we share one * TranspilingContext for the whole function. * * @TODO this is a hack. Find a cleaner way to separate the responsibilities between holding function-wide information and * specific annotation instance information during transpiling. */ resetMarkser(marker: Marker, isOld: boolean): void { if (isOld) { this.oldMarkerStack = [marker]; } else { this.newMarkerStack = [marker]; } } /** * When interposing on tuple assignments we generate temporary variables for components of the lhs of the tuple. E.g. for: * * ``` * (x, (a.y, z[1])) = .... * ``` * * We would generate: * * ``` * (_v.tmp1, (_v.tmp2, _v.tmp3)) = .... * z[1] = _v.tmp3; * a.y = _v.tmp2; * x = _v.tmp1; * ``` * * This is used for state var update interposing. */ getTupleAssignmentBinding(tupleComp: Expression): string { const key = `tuple_temp_${tupleComp.id}`; if (!this.bindingMap.has(key)) { const fieldName = this.instrCtx.nameGenerator.getFresh(`tuple_tmp_`); this.bindingMap.set(key, fieldName); return fieldName; } return this.bindingMap.get(key) as string; } /** * Get the binding name for a particular let binding identifier. E.g. in this code: * ``` * let x : = 1 in let x := true in x ? 0 : 1; * ``` * * For the first `x` `getLetBinding` will return `x` and for the second it will return `x1`. */ getLetBinding(arg: SId | [SLet, number]): string { const [letDecl, idx] = arg instanceof SId ? (arg.defSite as [SLet, number]) : arg; const key = `<let_${letDecl.id}_${idx}>`; if (!this.bindingMap.has(key)) { let name = arg instanceof SId ? arg.name : arg[0].lhs[idx].name; if (name === "_") { name = "dummy_"; } const fieldName = this.instrCtx.nameGenerator.getFresh(name, true); this.bindingMap.set(key, fieldName); } return this.bindingMap.get(key) as string; } getUserFunArg(userFun: SUserFunctionDefinition, idx: number): string { const key = `<uf_arg_${userFun.id}_${idx}>`; if (!this.bindingMap.has(key)) { const name = userFun.parameters[idx][0].name; const uniqueName = this.instrCtx.nameGenerator.getFresh(name, true); this.bindingMap.set(key, uniqueName); } return this.bindingMap.get(key) as string; } /** * Get temporary var used to store the result of a let expression. E.g. for this expression: * * ``` * let x : = 1 in x + x >= 2; * ``` * * getLetVar(..) will generate a temporary variable `let_1` that stores the result of the whole expression (true in this case.) */ getLetVar(node: SLet): string { const key = `<let_${node.id}>`; assert(!this.bindingMap.has(key), "getLetVar called more than once for {0}", node); const res = this.instrCtx.nameGenerator.getFresh("let_"); this.bindingMap.set(key, res); return res; } /** * Get temporary var used to store the result of an old expression. E.g. for this expression: * * ``` * old(x > 1) * ``` * * getOldVar(..) will generate a temporary variable `old_1` that stores the result of the whole expression before the function call. */ getOldVar(node: SUnaryOperation): string { const key = `<old_${node.id}>`; assert(!this.bindingMap.has(key), "getOldVar called more than once for {0}", node); const res = this.instrCtx.nameGenerator.getFresh("old_"); this.bindingMap.set(key, res); return res; } /** * Get temporary var used to store the result of a forall expression. E.g. for this expression: * * ``` * forall (uint t in a) a[t] > 10 * ``` * * getForAllVar(..) will generate a temporary variable `forall_1` that stores the result of the ForAll expression and is * updated on every iteration */ getForAllVar(node: SForAll): string { const key = `<forall_${node.id}>`; assert(!this.bindingMap.has(key), "getForAllVar called more than once for {0}", node); const res = this.instrCtx.nameGenerator.getFresh("forall_"); this.bindingMap.set(key, res); return res; } /** * Get temporary var used to store iterator variable of a forall expression. E.g. for this expression: * * ``` * forall (uint t in a) a[t] > 10 * ``` * * getForAllVar(..) will generate a temporary variable `t_1` that stores the value of t across every iteration. */ getForAllIterVar(node: SForAll): string { const key = `<forall_${node.id}_iter>`; let res = this.bindingMap.get(key); if (res === undefined) { res = this.instrCtx.nameGenerator.getFresh(node.iteratorVariable.name); this.bindingMap.set(key, res); } return res; } hasBinding(name: string): boolean { return this.bindingDefMap.has(name); } /** * Add a new binding named `name` with type `type` to the temporary struct. */ addBinding(name: string, type: TypeName): VariableDeclaration { assert(!this.bindingDefMap.has(name), `Binding ${name} already defined.`); const decl = this.factory.makeVariableDeclaration( false, false, name, this.bindingsStructDef.id, false, DataLocation.Default, StateVariableVisibility.Default, Mutability.Mutable, "<missing>", undefined, type ); this.bindingDefMap.set(name, decl); this.bindingsStructDef.appendChild(decl); return decl; } /** * Return an ASTNode (MemberAccess) referring to a particular binding. */ refBinding(name: string): MemberAccess { const member = this.bindingDefMap.get(name); assert(member !== undefined, `No temp binding ${name} defined`); this.varRefc++; return this.factory.makeMemberAccess( makeTypeString(member.vType as TypeName, DataLocation.Memory), this.factory.makeIdentifierFor(this.bindingsVar), name, member.id ); } /** * Return an `SId` refering to the temporary bindings local var. (set defSite accordingly) */ getBindingVarSId(): SId { const res = new SId(this.bindingsVar.name); res.defSite = this.bindingsVar; this.varRefc++; return res; } /** * Finalize this context. Currently adds the temporaries StructDef and local var if they are neccessary */ finalize(): void { // Prune out empty unchecked blocks for (const block of this.uncheckedBlocks) { if (block.vStatements.length === 0) { const container = block.parent; assert( container instanceof Block || container instanceof UncheckedBlock, "Expected container to be a block or unchecked block, got {0}", container ); container.removeChild(block); } } // Insert the temporaries struct def and local var (if neccessary) if (this.varRefc == 0) { return; } this.containerContract.appendChild(this.bindingsStructDef); const block = this.containerFun.vBody as Block; const localVarStmt = this.factory.makeVariableDeclarationStatement([], [this.bindingsVar]); this.instrCtx.addGeneralInstrumentation(localVarStmt); block.insertBefore(localVarStmt, block.children[0]); } /** * Get temporary var used to store the value of an id inside an old expression for debugging purposes. E.g. for this expression: */ getDbgVar(node: SId): string { const key = `<dbg ${defSiteToKey(node.defSite as VarDefSite)}>`; assert(!this.bindingMap.has(key), "getOldVar called more than once for {0}", node); const res = this.instrCtx.nameGenerator.getFresh("dbg_"); this.bindingMap.set(key, res); return res; } }
the_stack
import { Section, translations, mechanicsEngine } from ".."; /** * Tool to transform the book XML to HTML */ export class SectionRenderer { /** * Only illustrations of following authors are rendered (Others are not included on PAON). * This covers up to book 9. There are illustrations of authors that are not distributed (ex. JC Alvarez) */ private static toRenderIllAuthors = [ "Gary Chalk" , "Brian Williams" ]; /** The section to render */ public sectionToRender: Section; /** * The footnotes HTML. * The key is the foot note id, and the value is the foot note HTML */ private footNotes: Array< { [id: string]: string } > = []; /** * List of renderend foot note references ids. * Needed to avoid render not referenced foot notes */ private renderedFootNotesRefs: string[] = []; /** Render text illustration instances for this section? */ public renderIllustrationsText = false; /** * Constructor * @param section The section to render */ public constructor(section: Section) { this.sectionToRender = section; } /** * Get the HTML for the given book section * @return The HTML */ public renderSection(): string { // Collect foot notes const footNotes = this.sectionToRender.getFootNotesXml(); if ( footNotes.length > 0 ) { this.renderNodeChildren( footNotes , 0 ); } // Render the section body let html = this.renderNodeChildren( this.sectionToRender.$data , 0 ); // Render foot notes if ( footNotes.length > 0 ) { html += '<hr/><div class="footnotes">'; for (let i = 0, len = this.footNotes.length; i < len; i++) { if ( this.renderedFootNotesRefs.contains( this.footNotes[i].id ) ) { html += this.footNotes[i].html; } else { // Not really an application error, it's a PAON xml error, so do not call mechanicsEngine.debugWarning() console.log( this.sectionToRender.sectionId + ": Footnote " + this.footNotes[i].id + " not rendered because its not referenced" ); } } html += "</div>"; } return html; } /** * Get the HTML for children of a given book XML tag * @param {jQuery} $tag The XML tag to render * @param level The nesting level index of the tag * @return The HTML */ public renderNodeChildren($tag: JQuery<Element>, level: number ): string { // The HTML to return let sectionContent = ""; // Traverse all child elements, except separated sections // var children = $tag.contents().not('section.frontmatter-separate'); const children = $tag.contents(); for (const node of children.toArray() ) { if ( node.nodeType === 3 ) { // Text node sectionContent += node.textContent; continue; } if ( node.nodeType !== 1 ) { // Not a node, skip it continue; } // Get the tag name let tagName = node.tagName.toLowerCase(); // Replace '-' char by '_' (not valid char for javascript function names) tagName = tagName.replaceAll("-" , "_"); const $node = $(node); if ( tagName === "section" && $node.attr("class") === "frontmatter-separate" ) { // Ignore separated sections continue; } // Call the function renderer (this class method with the tag name) if ( !this[tagName] ) { const msg = this.sectionToRender.sectionId + ": Unkown tag: " + tagName; mechanicsEngine.debugWarning(msg); throw msg; } else { try { sectionContent += this[tagName]( $node , level ); } catch (e) { mechanicsEngine.debugWarning(e); } } } return sectionContent; } //////////////////////////////////////////////////////// // HTML DIRECT RENDERING //////////////////////////////////////////////////////// /** Render nodes with the same meaning on book XML and HTML */ private renderHtmlNode($node: JQuery<Element>, level: number): string { const name = $node[0].nodeName; return "<" + name + ">" + this.renderNodeChildren( $node , level ) + "</" + name + ">"; } /** Paragraph renderer */ private p($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } /** List item renderer */ private li($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } /** blockquote renderer */ private blockquote($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } /** Line break renderer */ private br($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } /** Cite renderer */ private cite($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } /** Emphasized renderer */ private em($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } /** Strong renderer */ private strong($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } //////////////////////////////////////////////////////// // PLAIN TEXT RENDERING //////////////////////////////////////////////////////// /** Render node as plain text */ private renderPlainText = function($node: JQuery<Element>, level: number): string { return this.renderNodeChildren( $node , level ); }; //////////////////////////////////////////////////////// // LISTS RENDERING //////////////////////////////////////////////////////// /** * Unordered list renderer * @param $ul List to render * @return The HTML */ private ul($ul: JQuery<Element>, level: number): string { return '<ul class="list-table">' + this.renderNodeChildren( $ul , level ) + "</ul>"; } /** * Ordered list renderer * @param $ol List to render * @returns The HTML */ private ol($ol: JQuery<Element>, level: number): string { return "<ol>" + this.renderNodeChildren( $ol , level ) + "</ol>"; } //////////////////////////////////////////////////////// // FOOT NOTES //////////////////////////////////////////////////////// /** * Store a foot note definition * @return Always an empty string (this function is for to collect, not for rendering) */ private footnote($footNote: JQuery<Element>, level: number): string { // Note HTML let noteHtml = this.renderNodeChildren( $footNote , level ); // Add the note index to the HTML const $html = $("<div>").html( noteHtml ); $html.find(">:first-child").prepend("[" + (this.footNotes.length + 1) + "] "); noteHtml = $html.html(); // Store the note const n = { id: $footNote.attr("id"), html: noteHtml }; this.footNotes.push( n ); return ""; } /** Foot reference rendering */ private footref($footRef: JQuery<Element>, level: number): string { // Get the foot note id: const id: string = $footRef.attr("idref"); // Render the reference return this.renderNodeChildren( $footRef , level ) + this.getHtmlFootRef(id); } /** * Get the HTML of a footer note id * @param id The footer note id to search * @return The HTML reference, or an empty string */ private getHtmlFootRef(id: string): string { this.renderedFootNotesRefs.push( id ); for (let i = 0, len = this.footNotes.length; i < len; i++) { if ( this.footNotes[i].id === id ) { return "<sup>" + (i + 1) + "</sup>"; } } return ""; } //////////////////////////////////////////////////////// // PUZZLES //////////////////////////////////////////////////////// private puzzle( $puzzle: JQuery<Element> , level: number ): string { return "<p>" + this.renderNodeChildren( $puzzle , level ) + "</p>"; } private choose( $choose: JQuery<Element> , level: number ): string { // TODO: To be complete, we should evaluate the expression. Not needed on book 5, // TODO: just render the otherwise tag return this.renderNodeChildren( $choose.children("otherwise") , level ) ; } //////////////////////////////////////////////////////// // OTHER //////////////////////////////////////////////////////// /** Render line */ private line($line: JQuery<Element> , level: number ): string { return this.renderNodeChildren( $line , level ) + "<br />"; } /** Render book reference */ private bookref($bookref: JQuery<Element> , level: number ): string { return '<span class="bookref">' + this.renderNodeChildren( $bookref , level ) + "</span>"; } /** Player property text */ private typ($typ: JQuery<Element> , level: number): string { const html = this.renderNodeChildren( $typ , level ); if ( $typ.attr("class") === "attribute" ) { return '<span class="attribute">' + html + "</span>"; } else { return html; } } /** Quote renderer */ private quote($quote: JQuery<Element>, level: number): string { return "&ldquo;" + this.renderNodeChildren( $quote , level ) + "&rdquo;"; } /** Links renderer */ private a($a: JQuery<Element>, level: number): string { // Check if it's a anchor target id if ( $a.attr("id") ) { // Check if its a foot note target if ( $a.attr("class") === "footnote" ) { // It is. Render its content and the reference to the foot note return this.renderNodeChildren( $a , level ) + this.getHtmlFootRef( $a.attr("idref") ); } // Ignore return this.renderNodeChildren( $a , level ); } // Check external links (See book 13 > gamerulz) const href = $a.attr("href"); if (href) { return '<a href="' + href + '" target="_blank">' + this.renderNodeChildren( $a , level ) + "</a>"; } let open = ""; let close = "</a>"; let idRef = $a.attr("idref"); if ( !idRef ) { // Removed link by Book.fixXml. Render as plain text idRef = "plaintext"; } switch ( idRef ) { case "action": // Link to action chart open = '<a href="#actionChart">'; break; case "random": // Link to random table open = '<span class="random">'; close = "</span>"; break; case "map": // Link to map open = '<a href="#map">'; break; case "license": // Project Aon license link open = '<a href="#projectAonLicense">'; break; case "crtable": // Combats result table (do not link) open = '<a href="#" class="crtable">'; close = "</a>"; break; case "plaintext": // Plain text open = "<span>"; close = "</span>"; break; case "lorecrcl": // Lore circles info. Link to "Game rules", specifically to the "Lore circles" section open = '<a href="#gameRules?section=lorecrcl">'; close = "</a>"; break; case "err230": // Book 12, sect230: Link to erratas (Plain text) open = "<span>"; close = "</span>"; break; default: if ( this.sectionToRender.book.hasSection( idRef ) ) { // Link to other section (ignore) return this.renderNodeChildren( $a , level ); } else if ( this.sectionToRender.hasTargetLink( idRef ) ) { // Link to anchor on this section. Ignore return this.renderNodeChildren( $a , level ); } else { const msg = "a tag: Unknown idref type: " + $a.attr("idref"); mechanicsEngine.debugWarning(msg); throw msg; } } return open + this.renderNodeChildren( $a , level ) + close; } /** * Definition list renderer * @param $dl List to render * @returns The HTML */ private dl($dl: JQuery<Element>, level: number): string { let definitionContent = ""; const self = this; for ( const element of $dl.find("> dt, > dd").toArray() ) { const $this = $(element); const content = self.renderNodeChildren( $this , level ); if ( $this.is("dt") ) { definitionContent += "<tr><td><dl><dt>" + content + "</dt>"; } else if ( $this.is("dd") ) { definitionContent += "<dd>" + content + "</dd></dl></td></tr>"; } } return '<table class="table table-striped table-bordered table-dl"><tbody>' + definitionContent + "</tbody></table>"; } /** Choice links renderer */ private link_text($linkText: JQuery<Element>, level: number): string { const section = $linkText.parent().attr("idref"); return '<a href="#" class="action choice-link" data-section="' + section + '">' + this.renderNodeChildren( $linkText , level ) + "</a>"; } /** * Choice renderer * @param $choice Choice to render * @returns The HTML */ private choice($choice: JQuery<Element>, level: number): string { return '<p class="choice"><span class="glyphicon glyphicon-chevron-right"></span> ' + this.renderNodeChildren( $choice , level ) + "</p>"; } /** * Render an illustration * @param section The ill. Section owner * @param $illustration Illustration to render (jQuery) * @returns The illustration HTML */ public static renderIllustration(section: Section, $illustration: any ): string { const renderer = new SectionRenderer(section); return renderer.illustration($illustration, 0); } /** * Illustration renderer * @param $illustration Illustration to render * @returns The HTML */ private illustration($illustration: JQuery<Element>, level: number): string { const creator: string = $illustration.find("> meta > creator").text(); if ( !SectionRenderer.toRenderIllAuthors.contains( creator ) ) { // Author images not distributed console.log( "Illustration of " + creator + " author not rendered"); return ""; } let illustrationContent = ""; const description = $illustration.find("> meta > description").text(); const fileName: string = $illustration.find("> instance.html").attr("src"); // Get the translated image URL: const source = this.sectionToRender.book.getIllustrationURL(fileName, this.sectionToRender.mechanics); const isLargeIllustration = (fileName.indexOf("ill") === 0); illustrationContent += '<div class="illustration' + (isLargeIllustration ? " ill" : "") + '"><img src="' + source + '" alt="' + description + '" title="' + description + '"></div><p class="illustration-label">' + description + "</p>"; if ( this.renderIllustrationsText ) { // Render the text instance too const $textInstance = $illustration.find("> instance.text"); if ( $textInstance ) { illustrationContent += this.renderNodeChildren( $textInstance , level ); } } return illustrationContent; } /** * Dead end renderer * @param $deadend Dead end to render * @returns The HTML */ private deadend( $deadend: JQuery<Element>, level: number ): string { /*return '<ul class="list-table deadend"><li class="title">' + this.renderNodeChildren( $deadend , level ) + '</li></ul>'*/ return "<p>" + this.renderNodeChildren( $deadend , level ) + "</p>"; } /** Onomatopoeia renderer */ private onomatopoeia( $onomatopoeia: JQuery<Element> , level: number ): string { return "<i>" + this.renderNodeChildren( $onomatopoeia , level ) + "</i>"; } /** Foreign language renderer */ private foreign( $foreign: JQuery<Element> , level: number ): string { return "<i>" + this.renderNodeChildren( $foreign , level ) + "</i>"; } /** Spell language renderer */ private spell( $spell: JQuery<Element> , level: number ): string { return "<i>" + this.renderNodeChildren( $spell , level ) + "</i>"; } public static getEnemyEndurance( $combat: JQuery<Element> ): any { let $enduranceAttr = $combat.find("enemy-attribute[class=endurance]"); if ( $enduranceAttr.length === 0 ) { // Book 6 / sect26: The endurance attribute is "target" $enduranceAttr = $combat.find("enemy-attribute[class=target]"); } if ( $enduranceAttr.length === 0 ) { // Book 6 / sect156: The endurance attribute is "resistance" $enduranceAttr = $combat.find("enemy-attribute[class=resistance]"); } if ( $enduranceAttr.length === 0 ) { // Book 9 / sect3 (Spanish version bug) $enduranceAttr = $combat.find("enemy-attribute[class=RESISTENCIA]"); } return $enduranceAttr; } public static getEnemyCombatSkill( $combat: JQuery<Element> ): any { let $cs = $combat.find(".combatskill"); if ( $cs.length === 0 ) { // Book 9 / sect3 (Spanish version bug) $cs = $combat.find('enemy-attribute[class="DESTREZA EN EL COMBATE"]'); } return $cs; } /** * Combat renderer * @param $combat Combat to render * @returns The HTML */ private combat( $combat: JQuery<Element> , level: number ): string { const enemyHtml = this.renderNodeChildren( $combat.find("enemy") , level ); const combatSkill = SectionRenderer.getEnemyCombatSkill( $combat ).text(); const endurance = SectionRenderer.getEnemyEndurance( $combat ).text(); return '<div class="combat well"><b>' + enemyHtml + "</b><br />" + '<span class="attribute">' + translations.text("combatSkillUpper") + "</span>: " + combatSkill + ' &nbsp;&nbsp; <span class="attribute">' + translations.text("enduranceUpper") + "</span>: " + '<span class="enemy-current-endurance">' + endurance + "</span> / " + endurance + "</div>"; } /** * Inner sections renderer * @param $section Inner section to render * @returns The HTML */ private section( $section: JQuery<Element> , level: number ): string { const sectionId = $section.attr("id"); const innerSectionData = $section.find("data").first(); const headingLevel = level + 1; let sectionContent = '<div class="subsection" id="' + sectionId + '"><h4 class="subsectionTitle">' + $section.find( "> meta > title").text() + "</h4>"; sectionContent += this.renderNodeChildren(innerSectionData, level + 1); sectionContent += "</div>"; return sectionContent; } private signpost( $signpost: JQuery<Element> , level: number ): string { return '<div class="signpost">' + this.renderNodeChildren( $signpost , level ) + "</div>"; } private poetry( $poetry: JQuery<Element> , level: number ): string { return '<blockquote class="poetry">' + this.renderNodeChildren( $poetry , level ) + "</blockquote>"; } private thought( $thought: JQuery<Element> , level: number ): string { return "<i>" + this.renderNodeChildren( $thought , level ) + "</i>"; } //////////////////////////////////////////////////////// // TABLES. These only appears in some spanish books // They seems errors, because they are not renderend in HTML pages in PAON web site... // See one in book 8, Spanish, sect13 //////////////////////////////////////////////////////// private table($node: JQuery<Element>, level: number): string { return '<table class="table table-striped">' + this.renderNodeChildren( $node , level ) + "</table>"; } private tr($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } private th($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } private td($node: JQuery<Element>, level: number): string { return this.renderHtmlNode( $node , level ); } }
the_stack
import { GraphQLClient } from "graphql-request"; import { print } from "graphql"; import { GraphQLResponse } from "graphql-request/dist/types"; import gql from "graphql-tag"; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K]; }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; json: any; jsonb: any; timestamp: any; timestamptz: any; uuid: any; }; export type Alertmanager = { config?: Maybe<Scalars["String"]>; online: Scalars["Boolean"]; tenant_id: Scalars["String"]; }; export type AlertmanagerInput = { config: Scalars["String"]; }; /** expression to compare columns of type Boolean. All fields are combined with logical 'AND'. */ export type Boolean_Comparison_Exp = { _eq?: Maybe<Scalars["Boolean"]>; _gt?: Maybe<Scalars["Boolean"]>; _gte?: Maybe<Scalars["Boolean"]>; _in?: Maybe<Array<Scalars["Boolean"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["Boolean"]>; _lte?: Maybe<Scalars["Boolean"]>; _neq?: Maybe<Scalars["Boolean"]>; _nin?: Maybe<Array<Scalars["Boolean"]>>; }; export enum ErrorType { ServiceError = "SERVICE_ERROR", ServiceOffline = "SERVICE_OFFLINE", ValidationFailed = "VALIDATION_FAILED" } export type RuleGroup = { namespace: Scalars["String"]; online: Scalars["Boolean"]; rule_group?: Maybe<Scalars["String"]>; rule_group_name: Scalars["String"]; tenant_id: Scalars["String"]; }; export type RuleGroupInput = { rule_group: Scalars["String"]; }; export type Rules = { online: Scalars["Boolean"]; rules?: Maybe<Scalars["String"]>; tenant_id: Scalars["String"]; }; export type StatusResponse = { error_message?: Maybe<Scalars["String"]>; error_raw_response?: Maybe<Scalars["String"]>; error_type?: Maybe<ErrorType>; success: Scalars["Boolean"]; }; /** expression to compare columns of type String. All fields are combined with logical 'AND'. */ export type String_Comparison_Exp = { _eq?: Maybe<Scalars["String"]>; _gt?: Maybe<Scalars["String"]>; _gte?: Maybe<Scalars["String"]>; _ilike?: Maybe<Scalars["String"]>; _in?: Maybe<Array<Scalars["String"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _like?: Maybe<Scalars["String"]>; _lt?: Maybe<Scalars["String"]>; _lte?: Maybe<Scalars["String"]>; _neq?: Maybe<Scalars["String"]>; _nilike?: Maybe<Scalars["String"]>; _nin?: Maybe<Array<Scalars["String"]>>; _nlike?: Maybe<Scalars["String"]>; _nsimilar?: Maybe<Scalars["String"]>; _similar?: Maybe<Scalars["String"]>; }; /** columns and relationships of "integration" */ export type Integration = { created_at: Scalars["timestamp"]; data: Scalars["jsonb"]; id: Scalars["uuid"]; key: Scalars["String"]; kind: Scalars["String"]; name: Scalars["String"]; /** An object relationship */ tenant: Tenant; tenant_id: Scalars["uuid"]; updated_at: Scalars["timestamp"]; }; /** columns and relationships of "integration" */ export type IntegrationDataArgs = { path?: Maybe<Scalars["String"]>; }; /** aggregated selection of "integration" */ export type Integration_Aggregate = { aggregate?: Maybe<Integration_Aggregate_Fields>; nodes: Array<Integration>; }; /** aggregate fields of "integration" */ export type Integration_Aggregate_Fields = { count?: Maybe<Scalars["Int"]>; max?: Maybe<Integration_Max_Fields>; min?: Maybe<Integration_Min_Fields>; }; /** aggregate fields of "integration" */ export type Integration_Aggregate_FieldsCountArgs = { columns?: Maybe<Array<Integration_Select_Column>>; distinct?: Maybe<Scalars["Boolean"]>; }; /** order by aggregate values of table "integration" */ export type Integration_Aggregate_Order_By = { count?: Maybe<Order_By>; max?: Maybe<Integration_Max_Order_By>; min?: Maybe<Integration_Min_Order_By>; }; /** append existing jsonb value of filtered columns with new jsonb value */ export type Integration_Append_Input = { data?: Maybe<Scalars["jsonb"]>; }; /** input type for inserting array relation for remote table "integration" */ export type Integration_Arr_Rel_Insert_Input = { data: Array<Integration_Insert_Input>; on_conflict?: Maybe<Integration_On_Conflict>; }; /** Boolean expression to filter rows from the table "integration". All fields are combined with a logical 'AND'. */ export type Integration_Bool_Exp = { _and?: Maybe<Array<Maybe<Integration_Bool_Exp>>>; _not?: Maybe<Integration_Bool_Exp>; _or?: Maybe<Array<Maybe<Integration_Bool_Exp>>>; created_at?: Maybe<Timestamp_Comparison_Exp>; data?: Maybe<Jsonb_Comparison_Exp>; id?: Maybe<Uuid_Comparison_Exp>; key?: Maybe<String_Comparison_Exp>; kind?: Maybe<String_Comparison_Exp>; name?: Maybe<String_Comparison_Exp>; tenant?: Maybe<Tenant_Bool_Exp>; tenant_id?: Maybe<Uuid_Comparison_Exp>; updated_at?: Maybe<Timestamp_Comparison_Exp>; }; /** unique or primary key constraints on table "integration" */ export enum Integration_Constraint { /** unique or primary key constraint */ IntegrationKeyTenantIdKey = "integration_key_tenant_id_key", /** unique or primary key constraint */ IntegrationsNameTenantIdKey = "integrations_name_tenant_id_key", /** unique or primary key constraint */ IntegrationsPkey = "integrations_pkey" } /** delete the field or element with specified path (for JSON arrays, negative integers count from the end) */ export type Integration_Delete_At_Path_Input = { data?: Maybe<Array<Maybe<Scalars["String"]>>>; }; /** delete the array element with specified index (negative integers count from the end). throws an error if top level container is not an array */ export type Integration_Delete_Elem_Input = { data?: Maybe<Scalars["Int"]>; }; /** delete key/value pair or string element. key/value pairs are matched based on their key value */ export type Integration_Delete_Key_Input = { data?: Maybe<Scalars["String"]>; }; /** input type for inserting data into table "integration" */ export type Integration_Insert_Input = { created_at?: Maybe<Scalars["timestamp"]>; data?: Maybe<Scalars["jsonb"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; kind?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; tenant?: Maybe<Tenant_Obj_Rel_Insert_Input>; tenant_id?: Maybe<Scalars["uuid"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** aggregate max on columns */ export type Integration_Max_Fields = { created_at?: Maybe<Scalars["timestamp"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; kind?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; tenant_id?: Maybe<Scalars["uuid"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** order by max() on columns of table "integration" */ export type Integration_Max_Order_By = { created_at?: Maybe<Order_By>; id?: Maybe<Order_By>; key?: Maybe<Order_By>; kind?: Maybe<Order_By>; name?: Maybe<Order_By>; tenant_id?: Maybe<Order_By>; updated_at?: Maybe<Order_By>; }; /** aggregate min on columns */ export type Integration_Min_Fields = { created_at?: Maybe<Scalars["timestamp"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; kind?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; tenant_id?: Maybe<Scalars["uuid"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** order by min() on columns of table "integration" */ export type Integration_Min_Order_By = { created_at?: Maybe<Order_By>; id?: Maybe<Order_By>; key?: Maybe<Order_By>; kind?: Maybe<Order_By>; name?: Maybe<Order_By>; tenant_id?: Maybe<Order_By>; updated_at?: Maybe<Order_By>; }; /** response of any mutation on the table "integration" */ export type Integration_Mutation_Response = { /** number of affected rows by the mutation */ affected_rows: Scalars["Int"]; /** data of the affected rows by the mutation */ returning: Array<Integration>; }; /** input type for inserting object relation for remote table "integration" */ export type Integration_Obj_Rel_Insert_Input = { data: Integration_Insert_Input; on_conflict?: Maybe<Integration_On_Conflict>; }; /** on conflict condition type for table "integration" */ export type Integration_On_Conflict = { constraint: Integration_Constraint; update_columns: Array<Integration_Update_Column>; where?: Maybe<Integration_Bool_Exp>; }; /** ordering options when selecting data from "integration" */ export type Integration_Order_By = { created_at?: Maybe<Order_By>; data?: Maybe<Order_By>; id?: Maybe<Order_By>; key?: Maybe<Order_By>; kind?: Maybe<Order_By>; name?: Maybe<Order_By>; tenant?: Maybe<Tenant_Order_By>; tenant_id?: Maybe<Order_By>; updated_at?: Maybe<Order_By>; }; /** primary key columns input for table: "integration" */ export type Integration_Pk_Columns_Input = { id: Scalars["uuid"]; }; /** prepend existing jsonb value of filtered columns with new jsonb value */ export type Integration_Prepend_Input = { data?: Maybe<Scalars["jsonb"]>; }; /** select columns of table "integration" */ export enum Integration_Select_Column { /** column name */ CreatedAt = "created_at", /** column name */ Data = "data", /** column name */ Id = "id", /** column name */ Key = "key", /** column name */ Kind = "kind", /** column name */ Name = "name", /** column name */ TenantId = "tenant_id", /** column name */ UpdatedAt = "updated_at" } /** input type for updating data in table "integration" */ export type Integration_Set_Input = { created_at?: Maybe<Scalars["timestamp"]>; data?: Maybe<Scalars["jsonb"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; kind?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; tenant_id?: Maybe<Scalars["uuid"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** update columns of table "integration" */ export enum Integration_Update_Column { /** column name */ CreatedAt = "created_at", /** column name */ Data = "data", /** column name */ Id = "id", /** column name */ Key = "key", /** column name */ Kind = "kind", /** column name */ Name = "name", /** column name */ TenantId = "tenant_id", /** column name */ UpdatedAt = "updated_at" } /** expression to compare columns of type json. All fields are combined with logical 'AND'. */ export type Json_Comparison_Exp = { _eq?: Maybe<Scalars["json"]>; _gt?: Maybe<Scalars["json"]>; _gte?: Maybe<Scalars["json"]>; _in?: Maybe<Array<Scalars["json"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["json"]>; _lte?: Maybe<Scalars["json"]>; _neq?: Maybe<Scalars["json"]>; _nin?: Maybe<Array<Scalars["json"]>>; }; /** expression to compare columns of type jsonb. All fields are combined with logical 'AND'. */ export type Jsonb_Comparison_Exp = { /** is the column contained in the given json value */ _contained_in?: Maybe<Scalars["jsonb"]>; /** does the column contain the given json value at the top level */ _contains?: Maybe<Scalars["jsonb"]>; _eq?: Maybe<Scalars["jsonb"]>; _gt?: Maybe<Scalars["jsonb"]>; _gte?: Maybe<Scalars["jsonb"]>; /** does the string exist as a top-level key in the column */ _has_key?: Maybe<Scalars["String"]>; /** do all of these strings exist as top-level keys in the column */ _has_keys_all?: Maybe<Array<Scalars["String"]>>; /** do any of these strings exist as top-level keys in the column */ _has_keys_any?: Maybe<Array<Scalars["String"]>>; _in?: Maybe<Array<Scalars["jsonb"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["jsonb"]>; _lte?: Maybe<Scalars["jsonb"]>; _neq?: Maybe<Scalars["jsonb"]>; _nin?: Maybe<Array<Scalars["jsonb"]>>; }; /** mutation root */ export type Mutation_Root = { /** perform the action: "deleteRuleGroup" */ deleteRuleGroup?: Maybe<StatusResponse>; /** delete data from the table: "integration" */ delete_integration?: Maybe<Integration_Mutation_Response>; /** delete single row from the table: "integration" */ delete_integration_by_pk?: Maybe<Integration>; /** delete data from the table: "tenant" */ delete_tenant?: Maybe<Tenant_Mutation_Response>; /** delete single row from the table: "tenant" */ delete_tenant_by_pk?: Maybe<Tenant>; /** delete data from the table: "user" */ delete_user?: Maybe<User_Mutation_Response>; /** delete single row from the table: "user" */ delete_user_by_pk?: Maybe<User>; /** delete data from the table: "user_preference" */ delete_user_preference?: Maybe<User_Preference_Mutation_Response>; /** delete single row from the table: "user_preference" */ delete_user_preference_by_pk?: Maybe<User_Preference>; /** insert data into the table: "integration" */ insert_integration?: Maybe<Integration_Mutation_Response>; /** insert a single row into the table: "integration" */ insert_integration_one?: Maybe<Integration>; /** insert data into the table: "tenant" */ insert_tenant?: Maybe<Tenant_Mutation_Response>; /** insert a single row into the table: "tenant" */ insert_tenant_one?: Maybe<Tenant>; /** insert data into the table: "user" */ insert_user?: Maybe<User_Mutation_Response>; /** insert a single row into the table: "user" */ insert_user_one?: Maybe<User>; /** insert data into the table: "user_preference" */ insert_user_preference?: Maybe<User_Preference_Mutation_Response>; /** insert a single row into the table: "user_preference" */ insert_user_preference_one?: Maybe<User_Preference>; /** perform the action: "updateAlertmanager" */ updateAlertmanager?: Maybe<StatusResponse>; /** perform the action: "updateRuleGroup" */ updateRuleGroup?: Maybe<StatusResponse>; /** update data of the table: "integration" */ update_integration?: Maybe<Integration_Mutation_Response>; /** update single row of the table: "integration" */ update_integration_by_pk?: Maybe<Integration>; /** update data of the table: "tenant" */ update_tenant?: Maybe<Tenant_Mutation_Response>; /** update single row of the table: "tenant" */ update_tenant_by_pk?: Maybe<Tenant>; /** update data of the table: "user" */ update_user?: Maybe<User_Mutation_Response>; /** update single row of the table: "user" */ update_user_by_pk?: Maybe<User>; /** update data of the table: "user_preference" */ update_user_preference?: Maybe<User_Preference_Mutation_Response>; /** update single row of the table: "user_preference" */ update_user_preference_by_pk?: Maybe<User_Preference>; }; /** mutation root */ export type Mutation_RootDeleteRuleGroupArgs = { namespace: Scalars["String"]; rule_group_name: Scalars["String"]; tenant_id: Scalars["String"]; }; /** mutation root */ export type Mutation_RootDelete_IntegrationArgs = { where: Integration_Bool_Exp; }; /** mutation root */ export type Mutation_RootDelete_Integration_By_PkArgs = { id: Scalars["uuid"]; }; /** mutation root */ export type Mutation_RootDelete_TenantArgs = { where: Tenant_Bool_Exp; }; /** mutation root */ export type Mutation_RootDelete_Tenant_By_PkArgs = { name: Scalars["String"]; }; /** mutation root */ export type Mutation_RootDelete_UserArgs = { where: User_Bool_Exp; }; /** mutation root */ export type Mutation_RootDelete_User_By_PkArgs = { id: Scalars["uuid"]; }; /** mutation root */ export type Mutation_RootDelete_User_PreferenceArgs = { where: User_Preference_Bool_Exp; }; /** mutation root */ export type Mutation_RootDelete_User_Preference_By_PkArgs = { id: Scalars["uuid"]; }; /** mutation root */ export type Mutation_RootInsert_IntegrationArgs = { objects: Array<Integration_Insert_Input>; on_conflict?: Maybe<Integration_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_Integration_OneArgs = { object: Integration_Insert_Input; on_conflict?: Maybe<Integration_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_TenantArgs = { objects: Array<Tenant_Insert_Input>; on_conflict?: Maybe<Tenant_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_Tenant_OneArgs = { object: Tenant_Insert_Input; on_conflict?: Maybe<Tenant_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_UserArgs = { objects: Array<User_Insert_Input>; on_conflict?: Maybe<User_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_User_OneArgs = { object: User_Insert_Input; on_conflict?: Maybe<User_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_User_PreferenceArgs = { objects: Array<User_Preference_Insert_Input>; on_conflict?: Maybe<User_Preference_On_Conflict>; }; /** mutation root */ export type Mutation_RootInsert_User_Preference_OneArgs = { object: User_Preference_Insert_Input; on_conflict?: Maybe<User_Preference_On_Conflict>; }; /** mutation root */ export type Mutation_RootUpdateAlertmanagerArgs = { input?: Maybe<AlertmanagerInput>; tenant_id: Scalars["String"]; }; /** mutation root */ export type Mutation_RootUpdateRuleGroupArgs = { namespace: Scalars["String"]; rule_group: RuleGroupInput; tenant_id: Scalars["String"]; }; /** mutation root */ export type Mutation_RootUpdate_IntegrationArgs = { _append?: Maybe<Integration_Append_Input>; _delete_at_path?: Maybe<Integration_Delete_At_Path_Input>; _delete_elem?: Maybe<Integration_Delete_Elem_Input>; _delete_key?: Maybe<Integration_Delete_Key_Input>; _prepend?: Maybe<Integration_Prepend_Input>; _set?: Maybe<Integration_Set_Input>; where: Integration_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdate_Integration_By_PkArgs = { _append?: Maybe<Integration_Append_Input>; _delete_at_path?: Maybe<Integration_Delete_At_Path_Input>; _delete_elem?: Maybe<Integration_Delete_Elem_Input>; _delete_key?: Maybe<Integration_Delete_Key_Input>; _prepend?: Maybe<Integration_Prepend_Input>; _set?: Maybe<Integration_Set_Input>; pk_columns: Integration_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdate_TenantArgs = { _set?: Maybe<Tenant_Set_Input>; where: Tenant_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdate_Tenant_By_PkArgs = { _set?: Maybe<Tenant_Set_Input>; pk_columns: Tenant_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdate_UserArgs = { _set?: Maybe<User_Set_Input>; where: User_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdate_User_By_PkArgs = { _set?: Maybe<User_Set_Input>; pk_columns: User_Pk_Columns_Input; }; /** mutation root */ export type Mutation_RootUpdate_User_PreferenceArgs = { _set?: Maybe<User_Preference_Set_Input>; where: User_Preference_Bool_Exp; }; /** mutation root */ export type Mutation_RootUpdate_User_Preference_By_PkArgs = { _set?: Maybe<User_Preference_Set_Input>; pk_columns: User_Preference_Pk_Columns_Input; }; /** column ordering options */ export enum Order_By { /** in the ascending order, nulls last */ Asc = "asc", /** in the ascending order, nulls first */ AscNullsFirst = "asc_nulls_first", /** in the ascending order, nulls last */ AscNullsLast = "asc_nulls_last", /** in the descending order, nulls first */ Desc = "desc", /** in the descending order, nulls first */ DescNullsFirst = "desc_nulls_first", /** in the descending order, nulls last */ DescNullsLast = "desc_nulls_last" } /** query root */ export type Query_Root = { /** perform the action: "getAlertmanager" */ getAlertmanager?: Maybe<Alertmanager>; /** perform the action: "getRuleGroup" */ getRuleGroup?: Maybe<RuleGroup>; /** fetch data from the table: "integration" */ integration: Array<Integration>; /** fetch aggregated fields from the table: "integration" */ integration_aggregate: Integration_Aggregate; /** fetch data from the table: "integration" using primary key columns */ integration_by_pk?: Maybe<Integration>; /** perform the action: "listRules" */ listRules?: Maybe<Rules>; /** fetch data from the table: "tenant" */ tenant: Array<Tenant>; /** fetch aggregated fields from the table: "tenant" */ tenant_aggregate: Tenant_Aggregate; /** fetch data from the table: "tenant" using primary key columns */ tenant_by_pk?: Maybe<Tenant>; /** fetch data from the table: "user" */ user: Array<User>; /** fetch aggregated fields from the table: "user" */ user_aggregate: User_Aggregate; /** fetch data from the table: "user" using primary key columns */ user_by_pk?: Maybe<User>; /** fetch data from the table: "user_preference" */ user_preference: Array<User_Preference>; /** fetch aggregated fields from the table: "user_preference" */ user_preference_aggregate: User_Preference_Aggregate; /** fetch data from the table: "user_preference" using primary key columns */ user_preference_by_pk?: Maybe<User_Preference>; /** perform the action: "validateCredential" */ validateCredential?: Maybe<StatusResponse>; /** perform the action: "validateExporter" */ validateExporter?: Maybe<StatusResponse>; }; /** query root */ export type Query_RootGetAlertmanagerArgs = { tenant_id: Scalars["String"]; }; /** query root */ export type Query_RootGetRuleGroupArgs = { namespace: Scalars["String"]; rule_group_name: Scalars["String"]; tenant_id: Scalars["String"]; }; /** query root */ export type Query_RootIntegrationArgs = { distinct_on?: Maybe<Array<Integration_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Integration_Order_By>>; where?: Maybe<Integration_Bool_Exp>; }; /** query root */ export type Query_RootIntegration_AggregateArgs = { distinct_on?: Maybe<Array<Integration_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Integration_Order_By>>; where?: Maybe<Integration_Bool_Exp>; }; /** query root */ export type Query_RootIntegration_By_PkArgs = { id: Scalars["uuid"]; }; /** query root */ export type Query_RootListRulesArgs = { tenant_id: Scalars["String"]; }; /** query root */ export type Query_RootTenantArgs = { distinct_on?: Maybe<Array<Tenant_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Tenant_Order_By>>; where?: Maybe<Tenant_Bool_Exp>; }; /** query root */ export type Query_RootTenant_AggregateArgs = { distinct_on?: Maybe<Array<Tenant_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Tenant_Order_By>>; where?: Maybe<Tenant_Bool_Exp>; }; /** query root */ export type Query_RootTenant_By_PkArgs = { name: Scalars["String"]; }; /** query root */ export type Query_RootUserArgs = { distinct_on?: Maybe<Array<User_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Order_By>>; where?: Maybe<User_Bool_Exp>; }; /** query root */ export type Query_RootUser_AggregateArgs = { distinct_on?: Maybe<Array<User_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Order_By>>; where?: Maybe<User_Bool_Exp>; }; /** query root */ export type Query_RootUser_By_PkArgs = { id: Scalars["uuid"]; }; /** query root */ export type Query_RootUser_PreferenceArgs = { distinct_on?: Maybe<Array<User_Preference_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Preference_Order_By>>; where?: Maybe<User_Preference_Bool_Exp>; }; /** query root */ export type Query_RootUser_Preference_AggregateArgs = { distinct_on?: Maybe<Array<User_Preference_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Preference_Order_By>>; where?: Maybe<User_Preference_Bool_Exp>; }; /** query root */ export type Query_RootUser_Preference_By_PkArgs = { id: Scalars["uuid"]; }; /** query root */ export type Query_RootValidateCredentialArgs = { name: Scalars["String"]; tenant_id: Scalars["String"]; type: Scalars["String"]; value: Scalars["json"]; }; /** query root */ export type Query_RootValidateExporterArgs = { config: Scalars["json"]; credential?: Maybe<Scalars["String"]>; name: Scalars["String"]; tenant_id: Scalars["String"]; type: Scalars["String"]; }; /** subscription root */ export type Subscription_Root = { /** perform the action: "getAlertmanager" */ getAlertmanager?: Maybe<Alertmanager>; /** perform the action: "getRuleGroup" */ getRuleGroup?: Maybe<RuleGroup>; /** fetch data from the table: "integration" */ integration: Array<Integration>; /** fetch aggregated fields from the table: "integration" */ integration_aggregate: Integration_Aggregate; /** fetch data from the table: "integration" using primary key columns */ integration_by_pk?: Maybe<Integration>; /** perform the action: "listRules" */ listRules?: Maybe<Rules>; /** fetch data from the table: "tenant" */ tenant: Array<Tenant>; /** fetch aggregated fields from the table: "tenant" */ tenant_aggregate: Tenant_Aggregate; /** fetch data from the table: "tenant" using primary key columns */ tenant_by_pk?: Maybe<Tenant>; /** fetch data from the table: "user" */ user: Array<User>; /** fetch aggregated fields from the table: "user" */ user_aggregate: User_Aggregate; /** fetch data from the table: "user" using primary key columns */ user_by_pk?: Maybe<User>; /** fetch data from the table: "user_preference" */ user_preference: Array<User_Preference>; /** fetch aggregated fields from the table: "user_preference" */ user_preference_aggregate: User_Preference_Aggregate; /** fetch data from the table: "user_preference" using primary key columns */ user_preference_by_pk?: Maybe<User_Preference>; /** perform the action: "validateCredential" */ validateCredential?: Maybe<StatusResponse>; /** perform the action: "validateExporter" */ validateExporter?: Maybe<StatusResponse>; }; /** subscription root */ export type Subscription_RootGetAlertmanagerArgs = { tenant_id: Scalars["String"]; }; /** subscription root */ export type Subscription_RootGetRuleGroupArgs = { namespace: Scalars["String"]; rule_group_name: Scalars["String"]; tenant_id: Scalars["String"]; }; /** subscription root */ export type Subscription_RootIntegrationArgs = { distinct_on?: Maybe<Array<Integration_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Integration_Order_By>>; where?: Maybe<Integration_Bool_Exp>; }; /** subscription root */ export type Subscription_RootIntegration_AggregateArgs = { distinct_on?: Maybe<Array<Integration_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Integration_Order_By>>; where?: Maybe<Integration_Bool_Exp>; }; /** subscription root */ export type Subscription_RootIntegration_By_PkArgs = { id: Scalars["uuid"]; }; /** subscription root */ export type Subscription_RootListRulesArgs = { tenant_id: Scalars["String"]; }; /** subscription root */ export type Subscription_RootTenantArgs = { distinct_on?: Maybe<Array<Tenant_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Tenant_Order_By>>; where?: Maybe<Tenant_Bool_Exp>; }; /** subscription root */ export type Subscription_RootTenant_AggregateArgs = { distinct_on?: Maybe<Array<Tenant_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Tenant_Order_By>>; where?: Maybe<Tenant_Bool_Exp>; }; /** subscription root */ export type Subscription_RootTenant_By_PkArgs = { name: Scalars["String"]; }; /** subscription root */ export type Subscription_RootUserArgs = { distinct_on?: Maybe<Array<User_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Order_By>>; where?: Maybe<User_Bool_Exp>; }; /** subscription root */ export type Subscription_RootUser_AggregateArgs = { distinct_on?: Maybe<Array<User_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Order_By>>; where?: Maybe<User_Bool_Exp>; }; /** subscription root */ export type Subscription_RootUser_By_PkArgs = { id: Scalars["uuid"]; }; /** subscription root */ export type Subscription_RootUser_PreferenceArgs = { distinct_on?: Maybe<Array<User_Preference_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Preference_Order_By>>; where?: Maybe<User_Preference_Bool_Exp>; }; /** subscription root */ export type Subscription_RootUser_Preference_AggregateArgs = { distinct_on?: Maybe<Array<User_Preference_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<User_Preference_Order_By>>; where?: Maybe<User_Preference_Bool_Exp>; }; /** subscription root */ export type Subscription_RootUser_Preference_By_PkArgs = { id: Scalars["uuid"]; }; /** subscription root */ export type Subscription_RootValidateCredentialArgs = { name: Scalars["String"]; tenant_id: Scalars["String"]; type: Scalars["String"]; value: Scalars["json"]; }; /** subscription root */ export type Subscription_RootValidateExporterArgs = { config: Scalars["json"]; credential?: Maybe<Scalars["String"]>; name: Scalars["String"]; tenant_id: Scalars["String"]; type: Scalars["String"]; }; /** columns and relationships of "tenant" */ export type Tenant = { created_at: Scalars["timestamp"]; id: Scalars["uuid"]; /** An array relationship */ integrations: Array<Integration>; /** An aggregated array relationship */ integrations_aggregate: Integration_Aggregate; key: Scalars["String"]; name: Scalars["String"]; type: Scalars["String"]; updated_at: Scalars["timestamp"]; }; /** columns and relationships of "tenant" */ export type TenantIntegrationsArgs = { distinct_on?: Maybe<Array<Integration_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Integration_Order_By>>; where?: Maybe<Integration_Bool_Exp>; }; /** columns and relationships of "tenant" */ export type TenantIntegrations_AggregateArgs = { distinct_on?: Maybe<Array<Integration_Select_Column>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<Integration_Order_By>>; where?: Maybe<Integration_Bool_Exp>; }; /** aggregated selection of "tenant" */ export type Tenant_Aggregate = { aggregate?: Maybe<Tenant_Aggregate_Fields>; nodes: Array<Tenant>; }; /** aggregate fields of "tenant" */ export type Tenant_Aggregate_Fields = { count?: Maybe<Scalars["Int"]>; max?: Maybe<Tenant_Max_Fields>; min?: Maybe<Tenant_Min_Fields>; }; /** aggregate fields of "tenant" */ export type Tenant_Aggregate_FieldsCountArgs = { columns?: Maybe<Array<Tenant_Select_Column>>; distinct?: Maybe<Scalars["Boolean"]>; }; /** order by aggregate values of table "tenant" */ export type Tenant_Aggregate_Order_By = { count?: Maybe<Order_By>; max?: Maybe<Tenant_Max_Order_By>; min?: Maybe<Tenant_Min_Order_By>; }; /** input type for inserting array relation for remote table "tenant" */ export type Tenant_Arr_Rel_Insert_Input = { data: Array<Tenant_Insert_Input>; on_conflict?: Maybe<Tenant_On_Conflict>; }; /** Boolean expression to filter rows from the table "tenant". All fields are combined with a logical 'AND'. */ export type Tenant_Bool_Exp = { _and?: Maybe<Array<Maybe<Tenant_Bool_Exp>>>; _not?: Maybe<Tenant_Bool_Exp>; _or?: Maybe<Array<Maybe<Tenant_Bool_Exp>>>; created_at?: Maybe<Timestamp_Comparison_Exp>; id?: Maybe<Uuid_Comparison_Exp>; integrations?: Maybe<Integration_Bool_Exp>; key?: Maybe<String_Comparison_Exp>; name?: Maybe<String_Comparison_Exp>; type?: Maybe<String_Comparison_Exp>; updated_at?: Maybe<Timestamp_Comparison_Exp>; }; /** unique or primary key constraints on table "tenant" */ export enum Tenant_Constraint { /** unique or primary key constraint */ TenantIdKey = "tenant_id_key", /** unique or primary key constraint */ TenantKeyKey = "tenant_key_key", /** unique or primary key constraint */ TenantPkey = "tenant_pkey" } /** input type for inserting data into table "tenant" */ export type Tenant_Insert_Input = { created_at?: Maybe<Scalars["timestamp"]>; id?: Maybe<Scalars["uuid"]>; integrations?: Maybe<Integration_Arr_Rel_Insert_Input>; key?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; type?: Maybe<Scalars["String"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** aggregate max on columns */ export type Tenant_Max_Fields = { created_at?: Maybe<Scalars["timestamp"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; type?: Maybe<Scalars["String"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** order by max() on columns of table "tenant" */ export type Tenant_Max_Order_By = { created_at?: Maybe<Order_By>; id?: Maybe<Order_By>; key?: Maybe<Order_By>; name?: Maybe<Order_By>; type?: Maybe<Order_By>; updated_at?: Maybe<Order_By>; }; /** aggregate min on columns */ export type Tenant_Min_Fields = { created_at?: Maybe<Scalars["timestamp"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; type?: Maybe<Scalars["String"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** order by min() on columns of table "tenant" */ export type Tenant_Min_Order_By = { created_at?: Maybe<Order_By>; id?: Maybe<Order_By>; key?: Maybe<Order_By>; name?: Maybe<Order_By>; type?: Maybe<Order_By>; updated_at?: Maybe<Order_By>; }; /** response of any mutation on the table "tenant" */ export type Tenant_Mutation_Response = { /** number of affected rows by the mutation */ affected_rows: Scalars["Int"]; /** data of the affected rows by the mutation */ returning: Array<Tenant>; }; /** input type for inserting object relation for remote table "tenant" */ export type Tenant_Obj_Rel_Insert_Input = { data: Tenant_Insert_Input; on_conflict?: Maybe<Tenant_On_Conflict>; }; /** on conflict condition type for table "tenant" */ export type Tenant_On_Conflict = { constraint: Tenant_Constraint; update_columns: Array<Tenant_Update_Column>; where?: Maybe<Tenant_Bool_Exp>; }; /** ordering options when selecting data from "tenant" */ export type Tenant_Order_By = { created_at?: Maybe<Order_By>; id?: Maybe<Order_By>; integrations_aggregate?: Maybe<Integration_Aggregate_Order_By>; key?: Maybe<Order_By>; name?: Maybe<Order_By>; type?: Maybe<Order_By>; updated_at?: Maybe<Order_By>; }; /** primary key columns input for table: "tenant" */ export type Tenant_Pk_Columns_Input = { name: Scalars["String"]; }; /** select columns of table "tenant" */ export enum Tenant_Select_Column { /** column name */ CreatedAt = "created_at", /** column name */ Id = "id", /** column name */ Key = "key", /** column name */ Name = "name", /** column name */ Type = "type", /** column name */ UpdatedAt = "updated_at" } /** input type for updating data in table "tenant" */ export type Tenant_Set_Input = { created_at?: Maybe<Scalars["timestamp"]>; id?: Maybe<Scalars["uuid"]>; key?: Maybe<Scalars["String"]>; name?: Maybe<Scalars["String"]>; type?: Maybe<Scalars["String"]>; updated_at?: Maybe<Scalars["timestamp"]>; }; /** update columns of table "tenant" */ export enum Tenant_Update_Column { /** column name */ CreatedAt = "created_at", /** column name */ Id = "id", /** column name */ Key = "key", /** column name */ Name = "name", /** column name */ Type = "type", /** column name */ UpdatedAt = "updated_at" } /** expression to compare columns of type timestamp. All fields are combined with logical 'AND'. */ export type Timestamp_Comparison_Exp = { _eq?: Maybe<Scalars["timestamp"]>; _gt?: Maybe<Scalars["timestamp"]>; _gte?: Maybe<Scalars["timestamp"]>; _in?: Maybe<Array<Scalars["timestamp"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["timestamp"]>; _lte?: Maybe<Scalars["timestamp"]>; _neq?: Maybe<Scalars["timestamp"]>; _nin?: Maybe<Array<Scalars["timestamp"]>>; }; /** expression to compare columns of type timestamptz. All fields are combined with logical 'AND'. */ export type Timestamptz_Comparison_Exp = { _eq?: Maybe<Scalars["timestamptz"]>; _gt?: Maybe<Scalars["timestamptz"]>; _gte?: Maybe<Scalars["timestamptz"]>; _in?: Maybe<Array<Scalars["timestamptz"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["timestamptz"]>; _lte?: Maybe<Scalars["timestamptz"]>; _neq?: Maybe<Scalars["timestamptz"]>; _nin?: Maybe<Array<Scalars["timestamptz"]>>; }; /** columns and relationships of "user" */ export type User = { active: Scalars["Boolean"]; avatar?: Maybe<Scalars["String"]>; created_at: Scalars["timestamptz"]; email: Scalars["String"]; id: Scalars["uuid"]; /** An object relationship */ preference?: Maybe<User_Preference>; role: Scalars["String"]; session_last_updated?: Maybe<Scalars["timestamptz"]>; username: Scalars["String"]; }; /** aggregated selection of "user" */ export type User_Aggregate = { aggregate?: Maybe<User_Aggregate_Fields>; nodes: Array<User>; }; /** aggregate fields of "user" */ export type User_Aggregate_Fields = { count?: Maybe<Scalars["Int"]>; max?: Maybe<User_Max_Fields>; min?: Maybe<User_Min_Fields>; }; /** aggregate fields of "user" */ export type User_Aggregate_FieldsCountArgs = { columns?: Maybe<Array<User_Select_Column>>; distinct?: Maybe<Scalars["Boolean"]>; }; /** order by aggregate values of table "user" */ export type User_Aggregate_Order_By = { count?: Maybe<Order_By>; max?: Maybe<User_Max_Order_By>; min?: Maybe<User_Min_Order_By>; }; /** input type for inserting array relation for remote table "user" */ export type User_Arr_Rel_Insert_Input = { data: Array<User_Insert_Input>; on_conflict?: Maybe<User_On_Conflict>; }; /** Boolean expression to filter rows from the table "user". All fields are combined with a logical 'AND'. */ export type User_Bool_Exp = { _and?: Maybe<Array<Maybe<User_Bool_Exp>>>; _not?: Maybe<User_Bool_Exp>; _or?: Maybe<Array<Maybe<User_Bool_Exp>>>; active?: Maybe<Boolean_Comparison_Exp>; avatar?: Maybe<String_Comparison_Exp>; created_at?: Maybe<Timestamptz_Comparison_Exp>; email?: Maybe<String_Comparison_Exp>; id?: Maybe<Uuid_Comparison_Exp>; preference?: Maybe<User_Preference_Bool_Exp>; role?: Maybe<String_Comparison_Exp>; session_last_updated?: Maybe<Timestamptz_Comparison_Exp>; username?: Maybe<String_Comparison_Exp>; }; /** unique or primary key constraints on table "user" */ export enum User_Constraint { /** unique or primary key constraint */ UserEmailKey = "user_email_key", /** unique or primary key constraint */ UserIdKey = "user_id_key", /** unique or primary key constraint */ UserPkey = "user_pkey" } /** input type for inserting data into table "user" */ export type User_Insert_Input = { active?: Maybe<Scalars["Boolean"]>; avatar?: Maybe<Scalars["String"]>; created_at?: Maybe<Scalars["timestamptz"]>; email?: Maybe<Scalars["String"]>; id?: Maybe<Scalars["uuid"]>; preference?: Maybe<User_Preference_Obj_Rel_Insert_Input>; role?: Maybe<Scalars["String"]>; session_last_updated?: Maybe<Scalars["timestamptz"]>; username?: Maybe<Scalars["String"]>; }; /** aggregate max on columns */ export type User_Max_Fields = { avatar?: Maybe<Scalars["String"]>; created_at?: Maybe<Scalars["timestamptz"]>; email?: Maybe<Scalars["String"]>; id?: Maybe<Scalars["uuid"]>; role?: Maybe<Scalars["String"]>; session_last_updated?: Maybe<Scalars["timestamptz"]>; username?: Maybe<Scalars["String"]>; }; /** order by max() on columns of table "user" */ export type User_Max_Order_By = { avatar?: Maybe<Order_By>; created_at?: Maybe<Order_By>; email?: Maybe<Order_By>; id?: Maybe<Order_By>; role?: Maybe<Order_By>; session_last_updated?: Maybe<Order_By>; username?: Maybe<Order_By>; }; /** aggregate min on columns */ export type User_Min_Fields = { avatar?: Maybe<Scalars["String"]>; created_at?: Maybe<Scalars["timestamptz"]>; email?: Maybe<Scalars["String"]>; id?: Maybe<Scalars["uuid"]>; role?: Maybe<Scalars["String"]>; session_last_updated?: Maybe<Scalars["timestamptz"]>; username?: Maybe<Scalars["String"]>; }; /** order by min() on columns of table "user" */ export type User_Min_Order_By = { avatar?: Maybe<Order_By>; created_at?: Maybe<Order_By>; email?: Maybe<Order_By>; id?: Maybe<Order_By>; role?: Maybe<Order_By>; session_last_updated?: Maybe<Order_By>; username?: Maybe<Order_By>; }; /** response of any mutation on the table "user" */ export type User_Mutation_Response = { /** number of affected rows by the mutation */ affected_rows: Scalars["Int"]; /** data of the affected rows by the mutation */ returning: Array<User>; }; /** input type for inserting object relation for remote table "user" */ export type User_Obj_Rel_Insert_Input = { data: User_Insert_Input; on_conflict?: Maybe<User_On_Conflict>; }; /** on conflict condition type for table "user" */ export type User_On_Conflict = { constraint: User_Constraint; update_columns: Array<User_Update_Column>; where?: Maybe<User_Bool_Exp>; }; /** ordering options when selecting data from "user" */ export type User_Order_By = { active?: Maybe<Order_By>; avatar?: Maybe<Order_By>; created_at?: Maybe<Order_By>; email?: Maybe<Order_By>; id?: Maybe<Order_By>; preference?: Maybe<User_Preference_Order_By>; role?: Maybe<Order_By>; session_last_updated?: Maybe<Order_By>; username?: Maybe<Order_By>; }; /** primary key columns input for table: "user" */ export type User_Pk_Columns_Input = { id: Scalars["uuid"]; }; /** columns and relationships of "user_preference" */ export type User_Preference = { dark_mode: Scalars["Boolean"]; id: Scalars["uuid"]; /** An object relationship */ user?: Maybe<User>; user_id?: Maybe<Scalars["uuid"]>; }; /** aggregated selection of "user_preference" */ export type User_Preference_Aggregate = { aggregate?: Maybe<User_Preference_Aggregate_Fields>; nodes: Array<User_Preference>; }; /** aggregate fields of "user_preference" */ export type User_Preference_Aggregate_Fields = { count?: Maybe<Scalars["Int"]>; max?: Maybe<User_Preference_Max_Fields>; min?: Maybe<User_Preference_Min_Fields>; }; /** aggregate fields of "user_preference" */ export type User_Preference_Aggregate_FieldsCountArgs = { columns?: Maybe<Array<User_Preference_Select_Column>>; distinct?: Maybe<Scalars["Boolean"]>; }; /** order by aggregate values of table "user_preference" */ export type User_Preference_Aggregate_Order_By = { count?: Maybe<Order_By>; max?: Maybe<User_Preference_Max_Order_By>; min?: Maybe<User_Preference_Min_Order_By>; }; /** input type for inserting array relation for remote table "user_preference" */ export type User_Preference_Arr_Rel_Insert_Input = { data: Array<User_Preference_Insert_Input>; on_conflict?: Maybe<User_Preference_On_Conflict>; }; /** Boolean expression to filter rows from the table "user_preference". All fields are combined with a logical 'AND'. */ export type User_Preference_Bool_Exp = { _and?: Maybe<Array<Maybe<User_Preference_Bool_Exp>>>; _not?: Maybe<User_Preference_Bool_Exp>; _or?: Maybe<Array<Maybe<User_Preference_Bool_Exp>>>; dark_mode?: Maybe<Boolean_Comparison_Exp>; id?: Maybe<Uuid_Comparison_Exp>; user?: Maybe<User_Bool_Exp>; user_id?: Maybe<Uuid_Comparison_Exp>; }; /** unique or primary key constraints on table "user_preference" */ export enum User_Preference_Constraint { /** unique or primary key constraint */ UserPreferenceIdKey = "user_preference_id_key", /** unique or primary key constraint */ UserPreferencePkey = "user_preference_pkey", /** unique or primary key constraint */ UserPreferenceUserIdKey = "user_preference_user_id_key" } /** input type for inserting data into table "user_preference" */ export type User_Preference_Insert_Input = { dark_mode?: Maybe<Scalars["Boolean"]>; id?: Maybe<Scalars["uuid"]>; user?: Maybe<User_Obj_Rel_Insert_Input>; user_id?: Maybe<Scalars["uuid"]>; }; /** aggregate max on columns */ export type User_Preference_Max_Fields = { id?: Maybe<Scalars["uuid"]>; user_id?: Maybe<Scalars["uuid"]>; }; /** order by max() on columns of table "user_preference" */ export type User_Preference_Max_Order_By = { id?: Maybe<Order_By>; user_id?: Maybe<Order_By>; }; /** aggregate min on columns */ export type User_Preference_Min_Fields = { id?: Maybe<Scalars["uuid"]>; user_id?: Maybe<Scalars["uuid"]>; }; /** order by min() on columns of table "user_preference" */ export type User_Preference_Min_Order_By = { id?: Maybe<Order_By>; user_id?: Maybe<Order_By>; }; /** response of any mutation on the table "user_preference" */ export type User_Preference_Mutation_Response = { /** number of affected rows by the mutation */ affected_rows: Scalars["Int"]; /** data of the affected rows by the mutation */ returning: Array<User_Preference>; }; /** input type for inserting object relation for remote table "user_preference" */ export type User_Preference_Obj_Rel_Insert_Input = { data: User_Preference_Insert_Input; on_conflict?: Maybe<User_Preference_On_Conflict>; }; /** on conflict condition type for table "user_preference" */ export type User_Preference_On_Conflict = { constraint: User_Preference_Constraint; update_columns: Array<User_Preference_Update_Column>; where?: Maybe<User_Preference_Bool_Exp>; }; /** ordering options when selecting data from "user_preference" */ export type User_Preference_Order_By = { dark_mode?: Maybe<Order_By>; id?: Maybe<Order_By>; user?: Maybe<User_Order_By>; user_id?: Maybe<Order_By>; }; /** primary key columns input for table: "user_preference" */ export type User_Preference_Pk_Columns_Input = { id: Scalars["uuid"]; }; /** select columns of table "user_preference" */ export enum User_Preference_Select_Column { /** column name */ DarkMode = "dark_mode", /** column name */ Id = "id", /** column name */ UserId = "user_id" } /** input type for updating data in table "user_preference" */ export type User_Preference_Set_Input = { dark_mode?: Maybe<Scalars["Boolean"]>; id?: Maybe<Scalars["uuid"]>; user_id?: Maybe<Scalars["uuid"]>; }; /** update columns of table "user_preference" */ export enum User_Preference_Update_Column { /** column name */ DarkMode = "dark_mode", /** column name */ Id = "id", /** column name */ UserId = "user_id" } /** select columns of table "user" */ export enum User_Select_Column { /** column name */ Active = "active", /** column name */ Avatar = "avatar", /** column name */ CreatedAt = "created_at", /** column name */ Email = "email", /** column name */ Id = "id", /** column name */ Role = "role", /** column name */ SessionLastUpdated = "session_last_updated", /** column name */ Username = "username" } /** input type for updating data in table "user" */ export type User_Set_Input = { active?: Maybe<Scalars["Boolean"]>; avatar?: Maybe<Scalars["String"]>; created_at?: Maybe<Scalars["timestamptz"]>; email?: Maybe<Scalars["String"]>; id?: Maybe<Scalars["uuid"]>; role?: Maybe<Scalars["String"]>; session_last_updated?: Maybe<Scalars["timestamptz"]>; username?: Maybe<Scalars["String"]>; }; /** update columns of table "user" */ export enum User_Update_Column { /** column name */ Active = "active", /** column name */ Avatar = "avatar", /** column name */ CreatedAt = "created_at", /** column name */ Email = "email", /** column name */ Id = "id", /** column name */ Role = "role", /** column name */ SessionLastUpdated = "session_last_updated", /** column name */ Username = "username" } /** expression to compare columns of type uuid. All fields are combined with logical 'AND'. */ export type Uuid_Comparison_Exp = { _eq?: Maybe<Scalars["uuid"]>; _gt?: Maybe<Scalars["uuid"]>; _gte?: Maybe<Scalars["uuid"]>; _in?: Maybe<Array<Scalars["uuid"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["uuid"]>; _lte?: Maybe<Scalars["uuid"]>; _neq?: Maybe<Scalars["uuid"]>; _nin?: Maybe<Array<Scalars["uuid"]>>; }; export type DeleteIntegrationMutationVariables = Exact<{ tenant_id: Scalars["uuid"]; id: Scalars["uuid"]; }>; export type DeleteIntegrationMutation = { delete_integration?: Maybe<{ returning: Array<Pick<Integration, "id">> }>; }; export type GetIntegrationsQueryVariables = Exact<{ tenant_id: Scalars["uuid"]; }>; export type GetIntegrationsQuery = { integration: Array< Pick< Integration, | "id" | "tenant_id" | "name" | "key" | "kind" | "data" | "created_at" | "updated_at" > >; }; export type GetIntegrationsDumpQueryVariables = Exact<{ [key: string]: never }>; export type GetIntegrationsDumpQuery = { integration: Array< Pick<Integration, "id" | "tenant_id" | "name" | "key" | "kind" | "data"> >; }; export type InsertIntegrationMutationVariables = Exact<{ name: Scalars["String"]; kind: Scalars["String"]; data: Scalars["jsonb"]; tenant_id: Scalars["uuid"]; }>; export type InsertIntegrationMutation = { insert_integration_one?: Maybe< Pick< Integration, | "id" | "kind" | "name" | "key" | "data" | "tenant_id" | "created_at" | "updated_at" > >; }; export type SubscribeToIntegrationListSubscriptionVariables = Exact<{ tenant_name: Scalars["String"]; }>; export type SubscribeToIntegrationListSubscription = { tenant_by_pk?: Maybe<{ integrations: Array< Pick< Integration, | "id" | "tenant_id" | "name" | "key" | "kind" | "data" | "created_at" | "updated_at" > >; }>; }; export type UpdateIntegrationDataMutationVariables = Exact<{ id: Scalars["uuid"]; data: Scalars["jsonb"]; }>; export type UpdateIntegrationDataMutation = { update_integration_by_pk?: Maybe< Pick<Integration, "id" | "data" | "updated_at"> >; }; export type UpdateIntegrationNameMutationVariables = Exact<{ id: Scalars["uuid"]; name: Scalars["String"]; }>; export type UpdateIntegrationNameMutation = { update_integration_by_pk?: Maybe< Pick<Integration, "id" | "name" | "updated_at"> >; }; export type CreateTenantsMutationVariables = Exact<{ tenants: Array<Tenant_Insert_Input> | Tenant_Insert_Input; }>; export type CreateTenantsMutation = { insert_tenant?: Maybe<{ returning: Array<Pick<Tenant, "name">> }>; }; export type DeleteTenantMutationVariables = Exact<{ name: Scalars["String"]; }>; export type DeleteTenantMutation = { delete_tenant_by_pk?: Maybe<Pick<Tenant, "name">>; }; export type GetAlertmanagerQueryVariables = Exact<{ tenant_id: Scalars["String"]; }>; export type GetAlertmanagerQuery = { getAlertmanager?: Maybe<Pick<Alertmanager, "config" | "online">>; }; export type GetTenantsQueryVariables = Exact<{ [key: string]: never }>; export type GetTenantsQuery = { tenant: Array< Pick<Tenant, "id" | "name" | "created_at" | "updated_at" | "type" | "key"> >; }; export type SubscribeToTenantListSubscriptionVariables = Exact<{ [key: string]: never; }>; export type SubscribeToTenantListSubscription = { tenant: Array< Pick<Tenant, "id" | "name" | "created_at" | "updated_at" | "type" | "key"> >; }; export type UpdateAlertmanagerMutationVariables = Exact<{ tenant_id: Scalars["String"]; input: AlertmanagerInput; }>; export type UpdateAlertmanagerMutation = { updateAlertmanager?: Maybe< Pick< StatusResponse, "success" | "error_type" | "error_message" | "error_raw_response" > >; }; export type CreateUserMutationVariables = Exact<{ email: Scalars["String"]; username: Scalars["String"]; avatar: Scalars["String"]; }>; export type CreateUserMutation = { insert_user_preference_one?: Maybe<{ user?: Maybe< Pick< User, | "id" | "email" | "username" | "role" | "active" | "avatar" | "created_at" | "session_last_updated" > >; }>; }; export type DeactivateUserMutationVariables = Exact<{ id: Scalars["uuid"]; }>; export type DeactivateUserMutation = { update_user_by_pk?: Maybe<Pick<User, "id" | "active">>; }; export type GetActiveUserForAuthQueryVariables = Exact<{ email: Scalars["String"]; }>; export type GetActiveUserForAuthQuery = { user: Array<Pick<User, "id" | "email" | "avatar" | "username" | "active">>; active_user_count: { aggregate?: Maybe<Pick<User_Aggregate_Fields, "count">>; }; }; export type GetCurrentUserQueryVariables = Exact<{ [key: string]: never }>; export type GetCurrentUserQuery = { user: Array< Pick<User, "id" | "email" | "avatar" | "username" | "active"> & { preference?: Maybe<Pick<User_Preference, "dark_mode">>; } >; }; export type GetUserQueryVariables = Exact<{ id: Scalars["uuid"]; }>; export type GetUserQuery = { user_by_pk?: Maybe< Pick<User, "id" | "email" | "avatar" | "username" | "active"> & { preference?: Maybe<Pick<User_Preference, "dark_mode">>; } >; }; export type ReactivateUserMutationVariables = Exact<{ id: Scalars["uuid"]; }>; export type ReactivateUserMutation = { update_user_by_pk?: Maybe<Pick<User, "id" | "active">>; }; export type SetDarkModeMutationVariables = Exact<{ user_id: Scalars["uuid"]; dark_mode?: Maybe<Scalars["Boolean"]>; }>; export type SetDarkModeMutation = { update_user_preference?: Maybe<{ returning: Array<Pick<User_Preference, "dark_mode">>; }>; }; export type SubscribeToUserListSubscriptionVariables = Exact<{ [key: string]: never; }>; export type SubscribeToUserListSubscription = { user: Array< Pick< User, | "id" | "email" | "username" | "session_last_updated" | "role" | "active" | "avatar" | "created_at" > & { preference?: Maybe<Pick<User_Preference, "dark_mode">> } >; }; export type UpdateUserMutationVariables = Exact<{ id: Scalars["uuid"]; email: Scalars["String"]; avatar: Scalars["String"]; username: Scalars["String"]; }>; export type UpdateUserMutation = { update_user_by_pk?: Maybe< Pick<User, "id" | "email" | "username" | "avatar" | "session_last_updated"> >; }; export type UpdateUserSessionMutationVariables = Exact<{ id: Scalars["uuid"]; timestamp: Scalars["timestamptz"]; }>; export type UpdateUserSessionMutation = { update_user_by_pk?: Maybe<Pick<User, "id" | "session_last_updated">>; }; export const DeleteIntegrationDocument = gql` mutation DeleteIntegration($tenant_id: uuid!, $id: uuid!) { delete_integration( where: { id: { _eq: $id }, tenant_id: { _eq: $tenant_id } } ) { returning { id } } } `; export const GetIntegrationsDocument = gql` query GetIntegrations($tenant_id: uuid!) { integration(where: { tenant_id: { _eq: $tenant_id } }) { id tenant_id name key kind data created_at updated_at } } `; export const GetIntegrationsDumpDocument = gql` query GetIntegrationsDump { integration { id tenant_id name key kind data } } `; export const InsertIntegrationDocument = gql` mutation InsertIntegration( $name: String! $kind: String! $data: jsonb! $tenant_id: uuid! ) { insert_integration_one( object: { name: $name, kind: $kind, data: $data, tenant_id: $tenant_id } ) { id kind name key data tenant_id created_at updated_at } } `; export const SubscribeToIntegrationListDocument = gql` subscription SubscribeToIntegrationList($tenant_name: String!) { tenant_by_pk(name: $tenant_name) { integrations { id tenant_id name key kind data created_at updated_at } } } `; export const UpdateIntegrationDataDocument = gql` mutation UpdateIntegrationData($id: uuid!, $data: jsonb!) { update_integration_by_pk(pk_columns: { id: $id }, _set: { data: $data }) { id data updated_at } } `; export const UpdateIntegrationNameDocument = gql` mutation UpdateIntegrationName($id: uuid!, $name: String!) { update_integration_by_pk(pk_columns: { id: $id }, _set: { name: $name }) { id name updated_at } } `; export const CreateTenantsDocument = gql` mutation CreateTenants($tenants: [tenant_insert_input!]!) { insert_tenant(objects: $tenants) { returning { name } } } `; export const DeleteTenantDocument = gql` mutation DeleteTenant($name: String!) { delete_tenant_by_pk(name: $name) { name } } `; export const GetAlertmanagerDocument = gql` query GetAlertmanager($tenant_id: String!) { getAlertmanager(tenant_id: $tenant_id) { config online } } `; export const GetTenantsDocument = gql` query GetTenants { tenant { id name created_at updated_at type key } } `; export const SubscribeToTenantListDocument = gql` subscription SubscribeToTenantList { tenant { id name created_at updated_at type key } } `; export const UpdateAlertmanagerDocument = gql` mutation UpdateAlertmanager($tenant_id: String!, $input: AlertmanagerInput!) { updateAlertmanager(tenant_id: $tenant_id, input: $input) { success error_type error_message error_raw_response } } `; export const CreateUserDocument = gql` mutation CreateUser($email: String!, $username: String!, $avatar: String!) { insert_user_preference_one( object: { dark_mode: false user: { data: { email: $email username: $username active: true avatar: $avatar } } } ) { user { id email username role active avatar created_at session_last_updated } } } `; export const DeactivateUserDocument = gql` mutation DeactivateUser($id: uuid!) { update_user_by_pk(_set: { active: false }, pk_columns: { id: $id }) { id active } } `; export const GetActiveUserForAuthDocument = gql` query GetActiveUserForAuth($email: String!) { user( where: { email: { _eq: $email }, active: { _eq: true } } limit: 1 order_by: { created_at: asc } ) { id email avatar username active } active_user_count: user_aggregate(where: { active: { _eq: true } }) { aggregate { count } } } `; export const GetCurrentUserDocument = gql` query GetCurrentUser { user { id email avatar username active preference { dark_mode } } } `; export const GetUserDocument = gql` query GetUser($id: uuid!) { user_by_pk(id: $id) { id email avatar username active preference { dark_mode } } } `; export const ReactivateUserDocument = gql` mutation ReactivateUser($id: uuid!) { update_user_by_pk(pk_columns: { id: $id }, _set: { active: true }) { id active } } `; export const SetDarkModeDocument = gql` mutation SetDarkMode($user_id: uuid!, $dark_mode: Boolean = true) { update_user_preference( where: { user_id: { _eq: $user_id } } _set: { dark_mode: $dark_mode } ) { returning { dark_mode } } } `; export const SubscribeToUserListDocument = gql` subscription SubscribeToUserList { user { id email username session_last_updated role active avatar preference { dark_mode } created_at } } `; export const UpdateUserDocument = gql` mutation UpdateUser( $id: uuid! $email: String! $avatar: String! $username: String! ) { update_user_by_pk( pk_columns: { id: $id } _set: { email: $email, avatar: $avatar, username: $username } ) { id email username avatar session_last_updated } } `; export const UpdateUserSessionDocument = gql` mutation UpdateUserSession($id: uuid!, $timestamp: timestamptz!) { update_user_by_pk( pk_columns: { id: $id } _set: { session_last_updated: $timestamp } ) { id session_last_updated } } `; export type SdkFunctionWrapper = <T>(action: () => Promise<T>) => Promise<T>; const defaultWrapper: SdkFunctionWrapper = sdkFunction => sdkFunction(); export function getSdk( client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper ) { return { DeleteIntegration( variables: DeleteIntegrationMutationVariables ): Promise<GraphQLResponse<DeleteIntegrationMutation>> { return withWrapper(() => client.rawRequest<DeleteIntegrationMutation>( print(DeleteIntegrationDocument), variables ) ); }, GetIntegrations( variables: GetIntegrationsQueryVariables ): Promise<GraphQLResponse<GetIntegrationsQuery>> { return withWrapper(() => client.rawRequest<GetIntegrationsQuery>( print(GetIntegrationsDocument), variables ) ); }, GetIntegrationsDump( variables?: GetIntegrationsDumpQueryVariables ): Promise<GraphQLResponse<GetIntegrationsDumpQuery>> { return withWrapper(() => client.rawRequest<GetIntegrationsDumpQuery>( print(GetIntegrationsDumpDocument), variables ) ); }, InsertIntegration( variables: InsertIntegrationMutationVariables ): Promise<GraphQLResponse<InsertIntegrationMutation>> { return withWrapper(() => client.rawRequest<InsertIntegrationMutation>( print(InsertIntegrationDocument), variables ) ); }, SubscribeToIntegrationList( variables: SubscribeToIntegrationListSubscriptionVariables ): Promise<GraphQLResponse<SubscribeToIntegrationListSubscription>> { return withWrapper(() => client.rawRequest<SubscribeToIntegrationListSubscription>( print(SubscribeToIntegrationListDocument), variables ) ); }, UpdateIntegrationData( variables: UpdateIntegrationDataMutationVariables ): Promise<GraphQLResponse<UpdateIntegrationDataMutation>> { return withWrapper(() => client.rawRequest<UpdateIntegrationDataMutation>( print(UpdateIntegrationDataDocument), variables ) ); }, UpdateIntegrationName( variables: UpdateIntegrationNameMutationVariables ): Promise<GraphQLResponse<UpdateIntegrationNameMutation>> { return withWrapper(() => client.rawRequest<UpdateIntegrationNameMutation>( print(UpdateIntegrationNameDocument), variables ) ); }, CreateTenants( variables: CreateTenantsMutationVariables ): Promise<GraphQLResponse<CreateTenantsMutation>> { return withWrapper(() => client.rawRequest<CreateTenantsMutation>( print(CreateTenantsDocument), variables ) ); }, DeleteTenant( variables: DeleteTenantMutationVariables ): Promise<GraphQLResponse<DeleteTenantMutation>> { return withWrapper(() => client.rawRequest<DeleteTenantMutation>( print(DeleteTenantDocument), variables ) ); }, GetAlertmanager( variables: GetAlertmanagerQueryVariables ): Promise<GraphQLResponse<GetAlertmanagerQuery>> { return withWrapper(() => client.rawRequest<GetAlertmanagerQuery>( print(GetAlertmanagerDocument), variables ) ); }, GetTenants( variables?: GetTenantsQueryVariables ): Promise<GraphQLResponse<GetTenantsQuery>> { return withWrapper(() => client.rawRequest<GetTenantsQuery>(print(GetTenantsDocument), variables) ); }, SubscribeToTenantList( variables?: SubscribeToTenantListSubscriptionVariables ): Promise<GraphQLResponse<SubscribeToTenantListSubscription>> { return withWrapper(() => client.rawRequest<SubscribeToTenantListSubscription>( print(SubscribeToTenantListDocument), variables ) ); }, UpdateAlertmanager( variables: UpdateAlertmanagerMutationVariables ): Promise<GraphQLResponse<UpdateAlertmanagerMutation>> { return withWrapper(() => client.rawRequest<UpdateAlertmanagerMutation>( print(UpdateAlertmanagerDocument), variables ) ); }, CreateUser( variables: CreateUserMutationVariables ): Promise<GraphQLResponse<CreateUserMutation>> { return withWrapper(() => client.rawRequest<CreateUserMutation>( print(CreateUserDocument), variables ) ); }, DeactivateUser( variables: DeactivateUserMutationVariables ): Promise<GraphQLResponse<DeactivateUserMutation>> { return withWrapper(() => client.rawRequest<DeactivateUserMutation>( print(DeactivateUserDocument), variables ) ); }, GetActiveUserForAuth( variables: GetActiveUserForAuthQueryVariables ): Promise<GraphQLResponse<GetActiveUserForAuthQuery>> { return withWrapper(() => client.rawRequest<GetActiveUserForAuthQuery>( print(GetActiveUserForAuthDocument), variables ) ); }, GetCurrentUser( variables?: GetCurrentUserQueryVariables ): Promise<GraphQLResponse<GetCurrentUserQuery>> { return withWrapper(() => client.rawRequest<GetCurrentUserQuery>( print(GetCurrentUserDocument), variables ) ); }, GetUser( variables: GetUserQueryVariables ): Promise<GraphQLResponse<GetUserQuery>> { return withWrapper(() => client.rawRequest<GetUserQuery>(print(GetUserDocument), variables) ); }, ReactivateUser( variables: ReactivateUserMutationVariables ): Promise<GraphQLResponse<ReactivateUserMutation>> { return withWrapper(() => client.rawRequest<ReactivateUserMutation>( print(ReactivateUserDocument), variables ) ); }, SetDarkMode( variables: SetDarkModeMutationVariables ): Promise<GraphQLResponse<SetDarkModeMutation>> { return withWrapper(() => client.rawRequest<SetDarkModeMutation>( print(SetDarkModeDocument), variables ) ); }, SubscribeToUserList( variables?: SubscribeToUserListSubscriptionVariables ): Promise<GraphQLResponse<SubscribeToUserListSubscription>> { return withWrapper(() => client.rawRequest<SubscribeToUserListSubscription>( print(SubscribeToUserListDocument), variables ) ); }, UpdateUser( variables: UpdateUserMutationVariables ): Promise<GraphQLResponse<UpdateUserMutation>> { return withWrapper(() => client.rawRequest<UpdateUserMutation>( print(UpdateUserDocument), variables ) ); }, UpdateUserSession( variables: UpdateUserSessionMutationVariables ): Promise<GraphQLResponse<UpdateUserSessionMutation>> { return withWrapper(() => client.rawRequest<UpdateUserSessionMutation>( print(UpdateUserSessionDocument), variables ) ); } }; } export type Sdk = ReturnType<typeof getSdk>;
the_stack
* Additions Copyright (c) 2019 Seven Bridges. All rights reserved. * Licensed under the Apache 2.0 License. See License.txt for license information. * * This file has been modified from the original LSP example published by Microsoft. * Code to drive the webview component code has been added. * ------------------------------------------------------------------------------------------ */ 'use strict'; import * as net from 'net'; import { Selection, TextEditorRevealType, workspace, Disposable, ExtensionContext, commands, window, ViewColumn, Uri, WebviewPanel, DebugConsoleMode, OutputChannel } from 'vscode'; import * as path from 'path'; import { LanguageClient, LanguageClientOptions, SettingMonitor, ServerOptions, ErrorAction, ErrorHandler, CloseAction, TransportKind } from 'vscode-languageclient'; import { Md5 } from 'ts-md5' import * as fs from 'fs' import { openStdin } from 'process'; import { exec, execFileSync } from 'child_process'; import { homedir } from 'os'; import * as https from 'https'; import { IncomingMessage } from 'http'; import * as unzip from 'unzip-stream'; import * as tar from 'tar-fs'; import * as gunzip from 'gunzip-maybe'; const thispackage = require('../package.json'); const github_release_url = `https://github.com/rabix/benten/releases/download/${thispackage.version}/`; type ActivateCallback = (executable: string, out_chan: OutputChannel, msg: string) => void; export function activate(context: ExtensionContext) { const default_executable = workspace.getConfiguration().get('benten.server.path'); get_language_server(default_executable, (executable, out_chan, msg) => { if (executable === null) { window.showErrorMessage("Benten (CWL). Error trying to install/use server. Please look at log."); out_chan.show(); } else { activate_server(executable, context); activate_preview(context); if (msg != null) { window.showInformationMessage(msg); } } }); } export function activate_server(executable: string, context: ExtensionContext) { const args = ["--debug"] context.subscriptions.push(startLangServer(executable, args, ["cwl"])); } function startLangServer(command: string, args: string[], documentSelector: string[]): Disposable { const serverOptions: ServerOptions = { command, args, }; const clientOptions: LanguageClientOptions = { outputChannelName: 'Benten (CWL): Log', documentSelector: documentSelector, synchronize: { configurationSection: "cwl" } } return new LanguageClient(command, serverOptions, clientOptions).start(); } function startLangServerTCP(addr: number, documentSelector: string[]): Disposable { const serverOptions: ServerOptions = function () { return new Promise((resolve, reject) => { var client = new net.Socket(); client.connect(addr, "127.0.0.1", function () { resolve({ reader: client, writer: client }); }); }); } const clientOptions: LanguageClientOptions = { documentSelector: documentSelector, } return new LanguageClient(`tcp lang server (port ${addr})`, serverOptions, clientOptions).start(); } function get_user_dir() { return process.env.APPDATA || process.env.XDG_DATA_HOME || (process.platform == 'darwin' ? path.join(homedir(), "Library", "Preferences") : path.join(homedir(), ".local", "share")); } function get_scratch_dir() { const scratch_directory = path.join(get_user_dir(), "sevenbridges", "benten", "scratch") console.log(`scratch directory: ${scratch_directory}`) return scratch_directory } const preview_scratch_directory = get_scratch_dir(); function benten_ls_exists(executable: string) { try { execFileSync(executable, ["-h"]); return true; } catch (e) { return false; } } function show_err_msg(msg: string) { console.error(msg) window.showErrorMessage(msg); } function get_language_server(default_executable, callback: ActivateCallback) { const out_chan = window.createOutputChannel("Benten (CWL): Download"); if(default_executable) { if (benten_ls_exists(default_executable)) { out_chan.appendLine(`Found user specified server ${default_executable}.`); callback(default_executable, out_chan, null); return; } else { const msg = `Can not run user specified server ${default_executable}. Fix the path in Benten settings, or remove to install server automatically.`; window.showErrorMessage(msg); out_chan.appendLine(msg); return; } } const pipx_executable = "benten-ls"; if (benten_ls_exists(pipx_executable)) { out_chan.appendLine("Found pip/pipx installed benten-ls."); callback(pipx_executable, out_chan, null); return; } else { out_chan.appendLine("No pipx installed benten-ls found."); } const userdir = get_user_dir(); const sbgdir = path.join(userdir, "sevenbridges", "benten"); const executable = path.join(sbgdir, `benten-${thispackage.version}`, "benten-ls"); if (benten_ls_exists(executable)) { out_chan.appendLine(`Found server: ${executable}`); callback(executable, out_chan, null); return; } else { out_chan.appendLine(`No downloaded benten-ls found (${executable}).`); } const pkgname = `benten-ls-${process.platform}.zip`; // https://nodejs.org/api/process.html#process_process_platform // 'aix', 'darwin', 'freebsd', 'linux', 'openbsd', 'sunos', 'win32' window.showInformationMessage(`Trying to download Benten (CWL) language server ${thispackage.version}`); fs.mkdir(sbgdir, { recursive: true }, (err) => { if (err) { // Fatal: Couldn't make the directory out_chan.appendLine(`Failed to create directory: ${sbgdir}. This is where the downloaded Benten server binaries would have been stored.`); callback(null, out_chan, null); } // Download from github releases page const package_url = `${github_release_url}/${pkgname}`; out_chan.appendLine(`Downloading server code from ${package_url}`); get_redirect(package_url, out_chan, (response) => { if (response === null) { callback(null, out_chan, null); } const server_response = `Server response: ${response.statusCode} ${response.statusMessage}`; if (response.statusCode != 200) { out_chan.appendLine(`Failed to download Benten server binary from ${package_url}. ${server_response}`); callback(null, out_chan, null); } else { out_chan.appendLine(server_response); } // The github zip contains only one file: benten-ls.tar.gz response.pipe(unzip.Parse()) .on('entry', (entry) => { entry.pipe(gunzip()).pipe(tar.extract(sbgdir)) .on('finish', () => { out_chan.appendLine("Extracted server binary!"); callback(executable, out_chan, `Installed Benten ${thispackage.version} from ${package_url}`); }) .on('error', (e) => { out_chan.appendLine(`Error extracting Benten server binary: ${e}`); out_chan.show(); callback(null, out_chan, null); }); }); }); }); } type ResponseCallback = (response: IncomingMessage) => void; function get_redirect(url: string, out_chan: OutputChannel, callback: ResponseCallback) { https.get(url, (response) => { if (response.headers.location) { var loc = response.headers.location; out_chan.appendLine(`Redirect to: ${loc.toString()}`); get_redirect(loc, out_chan, callback); } else { callback(response); } }).on('error', (e) => { out_chan.appendLine(`Failed trying to download Benten server binaries from ${url}. Site responded with ${e}`); out_chan.show(); callback(null); }); } export function activate_preview(context: ExtensionContext) { context.subscriptions.push( commands.registerCommand('cwl.show_graph', () => { // Create and show panel const panel = window.createWebviewPanel( 'preview', 'CWL Preview', ViewColumn.Two, { enableScripts: true, localResourceRoots: [ Uri.file(path.join(context.extensionPath, 'include')), Uri.file(preview_scratch_directory) ] } ); const on_disk_files: any = {} const files = ["vis-network.min.js", "vis-network.min.css"] for (let f of files) { on_disk_files[f] = Uri.file( path.join(context.extensionPath, 'include', f)) .with({ scheme: 'vscode-resource' }) } // And set its HTML content updateWebviewContent(panel, on_disk_files) // Handle interactions on the graph panel.webview.onDidReceiveMessage( message => { for (let te of window.visibleTextEditors) { if (te.document.uri.toString() === message.uri) { let line = te.document.lineAt(parseInt(message.line)) te.selection = new Selection(line.range.start, line.range.end) te.revealRange(line.range, TextEditorRevealType.InCenter) break } } }, undefined, context.subscriptions ); // When we switch tabs we want the view to update // But we don't need this because we have onDidChangeTextEditorSelection window.onDidChangeActiveTextEditor( e => { updateWebviewContent(panel, on_disk_files) }, null, context.subscriptions ) // We update the diagram each time we change the text window.onDidChangeTextEditorSelection( e => { updateWebviewContent(panel, on_disk_files) }, null, context.subscriptions ) }) ); } function updateWebviewContent(panel: WebviewPanel, on_disk_files: [string, Uri]) { const activeEditor = window.activeTextEditor; if (!activeEditor) { return; } const graph_name = Md5.hashStr(activeEditor.document.uri.toString()) + ".json" const data_uri = path.join(preview_scratch_directory, graph_name); var graph_data = JSON.parse(fs.readFileSync(data_uri, "utf8")); panel.webview.html = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Benten: ${activeEditor.document.uri.toString()}</title> <script type="text/javascript" src="${on_disk_files["vis-network.min.js"]}"></script> <link href="${on_disk_files["vis-network.min.css"]}" rel="stylesheet" type="text/css" /> <style type="text/css"> html, body { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; font-family: sans-serif; background-color: white; } #cwl-graph { width: 100%; height: 100%; border: 1px solid lightgray; } </style> </head> <body> <div id="cwl-graph"></div> <script type="text/javascript"> // create an array with nodes var nodes = new vis.DataSet(${JSON.stringify(graph_data["nodes"])}) var edges = new vis.DataSet(${JSON.stringify(graph_data["edges"])}) // metadata for scrolling to nodes var line_numbers = ${JSON.stringify(graph_data["line-numbers"])} // create a network var container = document.getElementById('cwl-graph'); var data = { nodes: nodes, edges: edges }; var options = { "autoResize": true, "interaction": { "tooltipDelay": 50, "navigationButtons": false }, "manipulation": { "enabled": false }, "nodes": { "shape": "dot", "borderWidth": 2 }, "edges": { "arrows": { "to": { "enabled": true, "scaleFactor": 0.5 } }, "smooth": { "type": "cubicBezier", "roundness": 0.6 } }, "groups": { "useDefaultGroups": true, "inputs": { "color": "#00AA28", "shadow": {"enabled": false} }, "outputs": { "color": "#FFFF00", "shadow": {"enabled": false} }, "steps": { "color": "#0000FF", "shadow": {"enabled": true} } }, "layout": { "hierarchical": { "enabled": true, "levelSeparation": 100, "direction": "LR", "sortMethod": "directed" } } } var network = new vis.Network(container, data, options); const vscode = acquireVsCodeApi(); // From https://visjs.github.io/vis-network/examples/network/events/interactionEvents.html // From https://code.visualstudio.com/api/extension-guides/webview#passing-messages-from-a-webview-to-an-extension network.on("selectNode", function (params) { const node_id = params.nodes[0] vscode.postMessage({ "uri": "${activeEditor.document.uri.toString()}", "line": line_numbers[node_id]}); }); </script> </body> </html>`; }
the_stack
import * as cdk from '@aws-cdk/core'; import * as sfn from '@aws-cdk/aws-stepfunctions'; import { LambdaInvoke } from '@aws-cdk/aws-stepfunctions-tasks'; import * as lambda from '@aws-cdk/aws-lambda'; import { PolicyDocument, PolicyStatement, Role, Effect, ServicePrincipal, CfnRole } from '@aws-cdk/aws-iam'; import { StringParameter } from '@aws-cdk/aws-ssm'; export interface ConstructProps { roleArn: string; ssmDocStateLambda: string; ssmExecDocLambda: string; ssmExecMonitorLambda: string; notifyLambda: string; getApprovalRequirementLambda: string; solutionId: string; solutionName: string; solutionVersion: string; orchLogGroup: string; kmsKeyParm: StringParameter; // to force dependency } export class OrchestratorConstruct extends cdk.Construct { public readonly orchArnParm: StringParameter constructor(scope: cdk.Construct, id: string, props: ConstructProps) { super(scope, id); const stack = cdk.Stack.of(this); const RESOURCE_PREFIX = props.solutionId.replace(/^DEV-/,''); // prefix on every resource name const extractFindings = new sfn.Pass(this, 'Get Finding Data from Input', { comment: 'Extract top-level data needed for remediation', parameters: { "EventType.$": "$.detail-type", "Findings.$": "$.detail.findings" } }) const reuseOrchLogGroup = new cdk.CfnParameter(this, 'Reuse Log Group', { type: "String", description: `Reuse existing Orchestrator Log Group? Choose "yes" if the log group already exists, else "no"`, default: "no", allowedValues: ["yes", "no"], }) reuseOrchLogGroup.overrideLogicalId(`ReuseOrchestratorLogGroup`) const nestedLogStack = new cdk.CfnStack(this, "NestedLogStack", { parameters: { KmsKeyArn: props.kmsKeyParm.stringValue, ReuseOrchestratorLogGroup: reuseOrchLogGroup.valueAsString }, templateUrl: "https://" + cdk.Fn.findInMap("SourceCode", "General", "S3Bucket") + "-reference.s3.amazonaws.com/" + cdk.Fn.findInMap("SourceCode", "General", "KeyPrefix") + "/aws-sharr-orchestrator-log.template" }) let getDocStateFunc: lambda.IFunction = lambda.Function.fromFunctionAttributes(this, 'getDocStateFunc',{ functionArn: props.ssmDocStateLambda }) let execRemediationFunc: lambda.IFunction = lambda.Function.fromFunctionAttributes(this, 'execRemediationFunc',{ functionArn: props.ssmExecDocLambda }) let execMonFunc: lambda.IFunction = lambda.Function.fromFunctionAttributes(this, 'getExecStatusFunc',{ functionArn: props.ssmExecMonitorLambda }) let notifyFunc: lambda.IFunction = lambda.Function.fromFunctionAttributes(this, 'notifyFunc',{ functionArn: props.notifyLambda }) let getApprovalRequirementFunc: lambda.IFunction = lambda.Function.fromFunctionAttributes(this, 'getRequirementFunc',{ functionArn: props.getApprovalRequirementLambda }) const orchestratorFailed = new sfn.Pass(this, 'Orchestrator Failed', { parameters: { "Notification": { "Message.$": "States.Format('Orchestrator failed: {}', $.Error)", "State.$": "States.Format('LAMBDAERROR')", "Details.$": "States.Format('Cause: {}', $.Cause)" }, "Payload.$": "$" } }) const getDocState = new LambdaInvoke(this, 'Get Automation Document State', { comment: "Get the status of the remediation automation document in the target account", lambdaFunction: getDocStateFunc, timeout: cdk.Duration.minutes(1), resultSelector: { "DocState.$": "$.Payload.status", "Message.$": "$.Payload.message", "SecurityStandard.$": "$.Payload.securitystandard", "SecurityStandardVersion.$": "$.Payload.securitystandardversion", "SecurityStandardSupported.$": "$.Payload.standardsupported", "ControlId.$": "$.Payload.controlid", "AccountId.$": "$.Payload.accountid", "RemediationRole.$": "$.Payload.remediationrole", "AutomationDocId.$": "$.Payload.automationdocid", "ResourceRegion.$": "$.Payload.resourceregion" }, resultPath: "$.AutomationDocument" }) getDocState.addCatch(orchestratorFailed) const getApprovalRequirement = new LambdaInvoke(this, 'Get Remediation Approval Requirement', { comment: "Determine whether the selected remediation requires manual approval", lambdaFunction: getApprovalRequirementFunc, timeout: cdk.Duration.minutes(5), resultSelector: { "WorkflowDocument.$": "$.Payload.workflowdoc", "WorkflowAccount.$": "$.Payload.workflowaccount", "WorkflowRole.$": "$.Payload.workflowrole", "WorkflowConfig.$": "$.Payload.workflow_data" }, resultPath: "$.Workflow" }) getApprovalRequirement.addCatch(orchestratorFailed) const remediateFinding = new LambdaInvoke(this, 'Execute Remediation', { comment: "Execute the SSM Automation Document in the target account", lambdaFunction: execRemediationFunc, heartbeat: cdk.Duration.seconds(60), timeout: cdk.Duration.minutes(5), resultSelector: { "ExecState.$": "$.Payload.status", "Message.$": "$.Payload.message", "ExecId.$": "$.Payload.executionid", "Account.$": "$.Payload.executionaccount", "Region.$": "$.Payload.executionregion" }, resultPath: "$.SSMExecution" }) remediateFinding.addCatch(orchestratorFailed) const execMonitor = new LambdaInvoke(this, 'execMonitor', { comment: "Monitor the remediation execution until done", lambdaFunction: execMonFunc, heartbeat: cdk.Duration.seconds(60), timeout: cdk.Duration.minutes(5), resultSelector: { "ExecState.$": "$.Payload.status", "ExecId.$": "$.Payload.executionid", "RemediationState.$": "$.Payload.remediation_status", "Message.$": "$.Payload.message", "LogData.$": "$.Payload.logdata", "AffectedObject.$": "$.Payload.affected_object", }, resultPath: "$.Remediation" }) execMonitor.addCatch(orchestratorFailed) const notify = new LambdaInvoke(this, 'notify', { comment: "Send notifications", lambdaFunction: notifyFunc, heartbeat: cdk.Duration.seconds(60), timeout: cdk.Duration.minutes(5) }) const notifyQueued = new LambdaInvoke(this, 'Queued Notification', { comment: "Send notification that a remediation has queued", lambdaFunction: notifyFunc, heartbeat: cdk.Duration.seconds(60), timeout: cdk.Duration.minutes(5), resultPath: "$.notificationResult" }) new sfn.Fail(this, 'Job Failed', { cause: 'AWS Batch Job Failed', error: 'DescribeJob returned FAILED', }); const eoj = new sfn.Pass(this, 'EOJ', { comment: 'END-OF-JOB' }) const processFindings = new sfn.Map(this, 'Process Findings', { comment: 'Process all findings in CloudWatch Event', parameters: { "Finding.$": "$$.Map.Item.Value", "EventType.$": "$.EventType" }, itemsPath: '$.Findings' }) // Set notification. If the when is not matched then this will be the notification sent const checkWorkflowNew = new sfn.Choice(this, 'Finding Workflow State NEW?') const docNotNew = new sfn.Pass(this, 'Finding Workflow State is not NEW', { parameters: { "Notification": { "Message.$": "States.Format('Finding Workflow State is not NEW ({}).', $.Finding.Workflow.Status)", "State.$": "States.Format('NOTNEW')" }, "EventType.$": "$.EventType", "Finding.$": "$.Finding" } }) const checkDocState = new sfn.Choice(this, 'Automation Doc Active?') const docStateNotActive = new sfn.Pass(this, 'Automation Document is not Active', { parameters: { "Notification": { "Message.$": "States.Format('Automation Document ({}) is not active ({}) in the member account({}).', $.AutomationDocId, $.AutomationDocument.DocState, $.Finding.AwsAccountId)", "State.$": "States.Format('REMEDIATIONNOTACTIVE')", "updateSecHub": "yes" }, "EventType.$": "$.EventType", "Finding.$": "$.Finding", "AccountId.$": "$.AutomationDocument.AccountId", "AutomationDocId.$": "$.AutomationDocument.AutomationDocId", "RemediationRole.$": "$.AutomationDocument.RemediationRole", "ControlId.$": "$.AutomationDocument.ControlId", "SecurityStandard.$": "$.AutomationDocument.SecurityStandard", "SecurityStandardVersion.$": "$.AutomationDocument.SecurityStandardVersion" } }) const controlNoRemediation = new sfn.Pass(this, 'No Remediation for Control', { parameters: { "Notification": { "Message.$": "States.Format('Security Standard {} v{} control {} has no automated remediation.', $.AutomationDocument.SecurityStandard, $.AutomationDocument.SecurityStandardVersion, $.AutomationDocument.ControlId)", "State.$": "States.Format('NOREMEDIATION')", "updateSecHub": "yes" }, "EventType.$": "$.EventType", "Finding.$": "$.Finding", "AccountId.$": "$.AutomationDocument.AccountId", "AutomationDocId.$": "$.AutomationDocument.AutomationDocId", "RemediationRole.$": "$.AutomationDocument.RemediationRole", "ControlId.$": "$.AutomationDocument.ControlId", "SecurityStandard.$": "$.AutomationDocument.SecurityStandard", "SecurityStandardVersion.$": "$.AutomationDocument.SecurityStandardVersion" } }) const standardNotEnabled = new sfn.Pass(this, 'Security Standard is not enabled', { parameters: { "Notification": { "Message.$": "States.Format('Security Standard ({}) v{} is not enabled.', $.AutomationDocument.SecurityStandard, $.AutomationDocument.SecurityStandardVersion)", "State.$": "States.Format('STANDARDNOTENABLED')", "updateSecHub": "yes" }, "EventType.$": "$.EventType", "Finding.$": "$.Finding", "AccountId.$": "$.AutomationDocument.AccountId", "AutomationDocId.$": "$.AutomationDocument.AutomationDocId", "RemediationRole.$": "$.AutomationDocument.RemediationRole", "ControlId.$": "$.AutomationDocument.ControlId", "SecurityStandard.$": "$.AutomationDocument.SecurityStandard", "SecurityStandardVersion.$": "$.AutomationDocument.SecurityStandardVersion" } }) const docStateError = new sfn.Pass(this, 'check_ssm_doc_state Error', { parameters: { "Notification": { "Message.$": "States.Format('check_ssm_doc_state returned an error: {}', $.AutomationDocument.Message)", "State.$": "States.Format('LAMBDAERROR')" }, "EventType.$": "$.EventType", "Finding.$": "$.Finding" } }) const isdone = new sfn.Choice(this, 'Remediation completed?') const waitForRemediation = new sfn.Wait(this, 'Wait for Remediation', { time: sfn.WaitTime.duration(cdk.Duration.seconds(15)) }) const remediationFailed = new sfn.Pass(this, 'Remediation Failed', { comment: 'Set parameters for notification', parameters: { "EventType.$": "$.EventType", "Finding.$": "$.Finding", "SSMExecution.$": "$.SSMExecution", "AutomationDocument.$": "$.AutomationDocument", "Notification": { "Message.$": "States.Format('Remediation failed for {} control {} in account {}: {}', $.AutomationDocument.SecurityStandard, $.AutomationDocument.ControlId, $.AutomationDocument.AccountId, $.Remediation.Message)", "State.$": "$.Remediation.ExecState", "Details.$": "$.Remediation.LogData", "ExecId.$": "$.Remediation.ExecId", "AffectedObject.$": "$.Remediation.AffectedObject", } } }) const remediationSucceeded = new sfn.Pass(this, 'Remediation Succeeded', { comment: 'Set parameters for notification', parameters: { "EventType.$": "$.EventType", "Finding.$": "$.Finding", "AccountId.$": "$.AutomationDocument.AccountId", "AutomationDocId.$": "$.AutomationDocument.AutomationDocId", "RemediationRole.$": "$.AutomationDocument.RemediationRole", "ControlId.$": "$.AutomationDocument.ControlId", "SecurityStandard.$": "$.AutomationDocument.SecurityStandard", "SecurityStandardVersion.$": "$.AutomationDocument.SecurityStandardVersion", "Notification": { "Message.$": "States.Format('Remediation succeeded for {} control {} in account {}: {}', $.AutomationDocument.SecurityStandard, $.AutomationDocument.ControlId, $.AutomationDocument.AccountId, $.Remediation.Message)", "State.$": "States.Format('SUCCESS')", "Details.$": "$.Remediation.LogData", "ExecId.$": "$.Remediation.ExecId", "AffectedObject.$": "$.Remediation.AffectedObject", } } }) const remediationQueued = new sfn.Pass(this, 'Remediation Queued', { comment: 'Set parameters for notification', parameters: { "EventType.$": "$.EventType", "Finding.$": "$.Finding", "AutomationDocument.$": "$.AutomationDocument", "SSMExecution.$": "$.SSMExecution", "Notification": { "Message.$": "States.Format('Remediation queued for {} control {} in account {}', $.AutomationDocument.SecurityStandard, $.AutomationDocument.ControlId, $.AutomationDocument.AccountId)", "State.$": "States.Format('QUEUED')", "ExecId.$": "$.SSMExecution.ExecId" } } }) //----------------------------------------------------------------- // State Machine // extractFindings.next(processFindings) checkWorkflowNew.when( sfn.Condition.or( sfn.Condition.stringEquals( '$.EventType', 'Security Hub Findings - Custom Action' ), sfn.Condition.and( sfn.Condition.stringEquals( '$.Finding.Workflow.Status', 'NEW' ), sfn.Condition.stringEquals( '$.EventType', 'Security Hub Findings - Imported' ), ) ), getApprovalRequirement ) checkWorkflowNew.otherwise(docNotNew) docNotNew.next(notify) // Call Lambda to get status of the automation document in the target account getDocState.next(checkDocState) getApprovalRequirement.next(getDocState) checkDocState.when( sfn.Condition.stringEquals( '$.AutomationDocument.DocState', 'ACTIVE'), remediateFinding ) checkDocState.when( sfn.Condition.stringEquals( '$.AutomationDocument.DocState', 'NOTACTIVE'), docStateNotActive ) checkDocState.when( sfn.Condition.stringEquals( '$.AutomationDocument.DocState', 'NOTENABLED'), standardNotEnabled ) checkDocState.when( sfn.Condition.stringEquals( '$.AutomationDocument.DocState', 'NOTFOUND'), controlNoRemediation ) checkDocState.otherwise(docStateError) docStateNotActive.next(notify) standardNotEnabled.next(notify) controlNoRemediation.next(notify) docStateError.next(notify) // Execute the remediation // remediateFinding.next(execMonitor) // Send a notification remediateFinding.next(remediationQueued) remediationQueued.next(notifyQueued) notifyQueued.next(execMonitor) execMonitor.next(isdone) isdone.when( sfn.Condition.stringEquals( '$.Remediation.RemediationState', 'Failed' ), remediationFailed ) isdone.when( sfn.Condition.stringEquals( '$.Remediation.ExecState', 'Success'), remediationSucceeded ) isdone.when( sfn.Condition.stringEquals( '$.Remediation.ExecState', 'TimedOut'), remediationFailed ) isdone.when( sfn.Condition.stringEquals( '$.Remediation.ExecState', 'Cancelling'), remediationFailed ) isdone.when( sfn.Condition.stringEquals( '$.Remediation.ExecState', 'Cancelled'), remediationFailed ) isdone.when( sfn.Condition.stringEquals( '$.Remediation.ExecState', 'Failed'), remediationFailed ) isdone.otherwise(waitForRemediation) waitForRemediation.next(execMonitor) orchestratorFailed.next(notify) remediationFailed.next(notify) remediationSucceeded.next(notify) processFindings.iterator(checkWorkflowNew).next(eoj); const orchestratorPolicy = new PolicyDocument(); orchestratorPolicy.addStatements( new PolicyStatement({ actions: [ "logs:CreateLogDelivery", "logs:GetLogDelivery", "logs:UpdateLogDelivery", "logs:DeleteLogDelivery", "logs:ListLogDeliveries", "logs:PutResourcePolicy", "logs:DescribeResourcePolicies", "logs:DescribeLogGroups" ], effect: Effect.ALLOW, resources: [ '*' ] }) ) orchestratorPolicy.addStatements( new PolicyStatement({ actions: [ "lambda:InvokeFunction" ], effect: Effect.ALLOW, resources: [ `arn:${stack.partition}:lambda:${stack.region}:${stack.account}:function:${getDocStateFunc.functionName}`, `arn:${stack.partition}:lambda:${stack.region}:${stack.account}:function:${execRemediationFunc.functionName}`, `arn:${stack.partition}:lambda:${stack.region}:${stack.account}:function:${execMonFunc.functionName}`, `arn:${stack.partition}:lambda:${stack.region}:${stack.account}:function:${notifyFunc.functionName}`, `arn:${stack.partition}:lambda:${stack.region}:${stack.account}:function:${getApprovalRequirementFunc.functionName}` ] }) ) orchestratorPolicy.addStatements( new PolicyStatement({ actions: [ "kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey" ], effect: Effect.ALLOW, resources: [ `arn:${stack.partition}:kms:${stack.region}:${stack.account}:alias/${RESOURCE_PREFIX}-SHARR-Key` ] }) ) const principal = new ServicePrincipal(`states.amazonaws.com`); const orchestratorRole = new Role(this, 'Role', { assumedBy: principal, inlinePolicies: { 'BasePolicy': orchestratorPolicy } }); orchestratorRole.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN) { let childToMod = orchestratorRole.node.defaultChild as CfnRole childToMod.cfnOptions.metadata = { cfn_nag: { rules_to_suppress: [{ id: 'W11', reason: 'CloudWatch Logs permissions require resource * except for DescribeLogGroups, except for GovCloud, which only works with resource *' }] } }; } const orchestratorStateMachine = new sfn.StateMachine(this, 'StateMachine', { definition: extractFindings, stateMachineName: `${RESOURCE_PREFIX}-SHARR-Orchestrator`, timeout: cdk.Duration.minutes(15), role: orchestratorRole }); new StringParameter(this, 'SHARR_Orchestrator_Arn', { description: 'Arn of the SHARR Orchestrator Step Function. This step function routes findings to remediation runbooks.', parameterName: '/Solutions/' + RESOURCE_PREFIX + '/OrchestratorArn', stringValue: orchestratorStateMachine.stateMachineArn }); // The arn for the CloudWatch logs group will be the same, regardless of encryption or not, // regardless of reuse or not. Set it here: const orchestratorLogGroupArn = `arn:${stack.partition}:logs:${stack.region}:${stack.account}:log-group:${props.orchLogGroup}:*` // Use an escape hatch to handle conditionally using the encrypted or unencrypted CW LogsGroup const stateMachineConstruct = orchestratorStateMachine.node.defaultChild as sfn.CfnStateMachine stateMachineConstruct.addOverride('Properties.LoggingConfiguration', { "Destinations": [ { "CloudWatchLogsLogGroup": { "LogGroupArn": orchestratorLogGroupArn } } ], "IncludeExecutionData": true, "Level": "ALL" }) stateMachineConstruct.addDependsOn(nestedLogStack) // Remove the unnecessary Policy created by the L2 StateMachine construct let roleToModify = this.node.findChild('Role') as CfnRole; if (roleToModify) { roleToModify.node.tryRemoveChild('DefaultPolicy') } } }
the_stack