text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/projectsMappers";
import * as Parameters from "../models/parameters";
import { AzureMigrateContext } from "../azureMigrateContext";
/** Class representing a Projects. */
export class Projects {
private readonly client: AzureMigrateContext;
/**
* Create a Projects.
* @param {AzureMigrateContext} client Reference to the service client.
*/
constructor(client: AzureMigrateContext) {
this.client = client;
}
/**
* Get all the projects in the subscription.
* @summary Get all projects.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsListBySubscriptionResponse>
*/
listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.ProjectsListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.ProjectResultList>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectResultList>): void;
listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectResultList>, callback?: msRest.ServiceCallback<Models.ProjectResultList>): Promise<Models.ProjectsListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.ProjectsListBySubscriptionResponse>;
}
/**
* Get all the projects in the resource group.
* @summary Get all projects.
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsListByResourceGroupResponse>;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ProjectResultList>): void;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectResultList>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectResultList>, callback?: msRest.ServiceCallback<Models.ProjectResultList>): Promise<Models.ProjectsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.ProjectsListByResourceGroupResponse>;
}
/**
* Get the project with the specified name.
* @summary Get the specified project.
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsGetResponse>
*/
get(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsGetResponse>;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param callback The callback
*/
get(resourceGroupName: string, projectName: string, callback: msRest.ServiceCallback<Models.Project>): void;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Project>): void;
get(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Project>, callback?: msRest.ServiceCallback<Models.Project>): Promise<Models.ProjectsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
projectName,
options
},
getOperationSpec,
callback) as Promise<Models.ProjectsGetResponse>;
}
/**
* Create a project with specified name. If a project already exists, update it.
* @summary Create or update project.
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsCreateResponse>
*/
create(resourceGroupName: string, projectName: string, options?: Models.ProjectsCreateOptionalParams): Promise<Models.ProjectsCreateResponse>;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param callback The callback
*/
create(resourceGroupName: string, projectName: string, callback: msRest.ServiceCallback<Models.Project>): void;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param options The optional parameters
* @param callback The callback
*/
create(resourceGroupName: string, projectName: string, options: Models.ProjectsCreateOptionalParams, callback: msRest.ServiceCallback<Models.Project>): void;
create(resourceGroupName: string, projectName: string, options?: Models.ProjectsCreateOptionalParams | msRest.ServiceCallback<Models.Project>, callback?: msRest.ServiceCallback<Models.Project>): Promise<Models.ProjectsCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
projectName,
options
},
createOperationSpec,
callback) as Promise<Models.ProjectsCreateResponse>;
}
/**
* Update a project with specified name. Supports partial updates, for example only tags can be
* provided.
* @summary Update project.
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsUpdateResponse>
*/
update(resourceGroupName: string, projectName: string, options?: Models.ProjectsUpdateOptionalParams): Promise<Models.ProjectsUpdateResponse>;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param callback The callback
*/
update(resourceGroupName: string, projectName: string, callback: msRest.ServiceCallback<Models.Project>): void;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, projectName: string, options: Models.ProjectsUpdateOptionalParams, callback: msRest.ServiceCallback<Models.Project>): void;
update(resourceGroupName: string, projectName: string, options?: Models.ProjectsUpdateOptionalParams | msRest.ServiceCallback<Models.Project>, callback?: msRest.ServiceCallback<Models.Project>): Promise<Models.ProjectsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
projectName,
options
},
updateOperationSpec,
callback) as Promise<Models.ProjectsUpdateResponse>;
}
/**
* Delete the project. Deleting non-existent project is a no-operation.
* @summary Delete the project
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsDeleteResponse>
*/
deleteMethod(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsDeleteResponse>;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, projectName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.ProjectsDeleteResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
projectName,
options
},
deleteMethodOperationSpec,
callback) as Promise<Models.ProjectsDeleteResponse>;
}
/**
* Gets the Log Analytics Workspace ID and Primary Key for the specified project.
* @summary Get shared keys for the project.
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param [options] The optional parameters
* @returns Promise<Models.ProjectsGetKeysResponse>
*/
getKeys(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsGetKeysResponse>;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param callback The callback
*/
getKeys(resourceGroupName: string, projectName: string, callback: msRest.ServiceCallback<Models.ProjectKey>): void;
/**
* @param resourceGroupName Name of the Azure Resource Group that project is part of.
* @param projectName Name of the Azure Migrate project.
* @param options The optional parameters
* @param callback The callback
*/
getKeys(resourceGroupName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectKey>): void;
getKeys(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectKey>, callback?: msRest.ServiceCallback<Models.ProjectKey>): Promise<Models.ProjectsGetKeysResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
projectName,
options
},
getKeysOperationSpec,
callback) as Promise<Models.ProjectsGetKeysResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Migrate/projects",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProjectResultList,
headersMapper: Mappers.ProjectsListBySubscriptionHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Migrate/projects",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProjectResultList,
headersMapper: Mappers.ProjectsListByResourceGroupHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.projectName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Project,
headersMapper: Mappers.ProjectsGetHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.projectName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"project"
],
mapper: Mappers.Project
},
responses: {
200: {
bodyMapper: Mappers.Project,
headersMapper: Mappers.ProjectsCreateHeaders
},
201: {
bodyMapper: Mappers.Project,
headersMapper: Mappers.ProjectsCreateHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.projectName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"project"
],
mapper: Mappers.Project
},
responses: {
200: {
bodyMapper: Mappers.Project,
headersMapper: Mappers.ProjectsUpdateHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.projectName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
headersMapper: Mappers.ProjectsDeleteHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getKeysOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/keys",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.projectName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProjectKey,
headersMapper: Mappers.ProjectsGetKeysHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import { deserialize, getBSONDecoder, getBSONSerializer, getBSONSizer, Writer } from '@deepkit/bson';
import { ClassType } from '@deepkit/core';
import { ClassSchema, getClassSchema, getGlobalStore, jsonSerializer } from '@deepkit/type';
import { rpcChunk, rpcError, RpcTypes } from './model';
import type { SingleProgress } from './writer';
export const enum RpcMessageRouteType {
client = 0,
server = 1,
sourceDest = 2,
peer = 3,
}
// export class RpcMessageRoute {
// public peerId?: string;
// public source?: string;
// public destination?: string;
// constructor(
// public type: RpcMessageRouteType = 0,
// ) {
// }
// }
/*
* A message is binary data and has the following structure:
*
* <size> <version> <id> <route>[<routeConfig>] <composite> <messageBody>
*
* size: uint32 //total message size
* version: uint8
* id: uint32 //message id
*
* //type of routing:
* //0=client (context from client -> server), //client initiated a message context (message id created on client)
* //1=server (context from server -> client), //server initiated a message context (message id created on server)
* //2=sourceDest //route this message to a specific client using its client id
* //4=peer //route this message to a client using a peer alias (the peer alias needs to be registered). replies will be rewritten to sourceDest
*
* //when route=0
* routeConfig: not defined
*
* //when route=1
* routeConfig: not defined
*
* //when route=2
* routeConfig: <source><destination>, each 16 bytes, uuid v4
*
* //when route=3
* routeConfig: <source><peerId> //where source=uuid v4, and peerId=ascii string (terminated by \0)
*
* composite: uint8 //when 1 then there are multiple messageBody, each prefixed with uint32 for their size
*
* composite=0 then messageBody=<type><body>:
* type: uint8 (256 types supported) //supported type
* body: BSON|any //arbitrary payload passed to type
*
* composite=1 then messageBody=<size><type><body>:
* size: uint32
* type: uint8 (256 types supported) //supported type
* body: BSON|any //arbitrary payload passed to type
*
*/
export class RpcMessage {
protected peerId?: string;
protected source?: string;
protected destination?: string;
constructor(
public id: number,
public composite: boolean,
public type: number,
public routeType: RpcMessageRouteType,
public bodyOffset: number,
public bodySize: number,
public buffer?: Uint8Array,
) {
}
debug() {
return {
type: this.type,
id: this.id,
date: new Date,
composite: this.composite,
body: this.bodySize ? this.parseGenericBody() : undefined,
messages: this.composite ? this.getBodies().map(message => {
return {
id: message.id, type: message.type, date: new Date, body: message.bodySize ? message.parseGenericBody() : undefined,
};
}) : [],
}
}
getBuffer(): Uint8Array {
if (!this.buffer) throw new Error('No buffer');
return this.buffer;
}
getPeerId(): string {
if (!this.buffer) throw new Error('No buffer');
if (this.routeType !== RpcMessageRouteType.peer) throw new Error(`Message is not routed via peer, but ${this.routeType}`);
if (this.peerId) return this.peerId;
this.peerId = '';
for (let offset = 10 + 16, c: number = this.buffer[offset]; c !== 0; offset++, c = this.buffer[offset]) {
this.peerId += String.fromCharCode(c);
}
return this.peerId;
}
getSource(): Uint8Array {
if (!this.buffer) throw new Error('No buffer');
if (this.routeType !== RpcMessageRouteType.sourceDest && this.routeType !== RpcMessageRouteType.peer) throw new Error(`Message is not routed via sourceDest, but ${this.routeType}`);
return this.buffer.slice(4 + 1 + 4 + 1, 4 + 1 + 4 + 1 + 16);
}
getDestination(): Uint8Array {
if (!this.buffer) throw new Error('No buffer');
if (this.routeType !== RpcMessageRouteType.sourceDest) throw new Error(`Message is not routed via sourceDest, but ${this.routeType}`);
return this.buffer.slice(4 + 1 + 4 + 1 + 16, 4 + 1 + 4 + 1 + 16 + 16);
}
getError(): Error {
if (!this.buffer) throw new Error('No buffer');
const error = getBSONDecoder(rpcError)(this.buffer, this.bodyOffset);
return rpcDecodeError(error);
}
isError(): boolean {
return this.type === RpcTypes.Error;
}
parseGenericBody(): object {
if (!this.bodySize) throw new Error('Message has no body');
if (!this.buffer) throw new Error('No buffer');
if (this.composite) throw new Error('Composite message can not be read directly');
return deserialize(this.buffer, this.bodyOffset);
}
parseBody<T>(schema: ClassSchema<T>): T {
if (!this.bodySize) throw new Error('Message has no body');
if (!this.buffer) throw new Error('No buffer');
if (this.composite) throw new Error('Composite message can not be read directly');
if (!schema.jit.bsonEncoder) getBSONDecoder(schema);
return schema.jit.bsonEncoder(this.buffer, this.bodyOffset);
}
getBodies(): RpcMessage[] {
if (!this.composite) throw new Error('Not a composite message');
const messages: RpcMessage[] = [];
const buffer = this.getBuffer();
const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
const totalSize = view.getUint32(0, true);
let offset = this.bodyOffset;
while (offset < totalSize) {
const bodySize = view.getUint32(offset, true);
offset += 4;
const type = view.getUint8(offset++);
messages.push(new RpcMessage(this.id, false, type, this.routeType, offset, bodySize, buffer));
offset += bodySize;
}
return messages;
}
}
export class ErroredRpcMessage extends RpcMessage {
constructor(
public id: number,
public error: Error,
) {
super(id, false, RpcTypes.Error, 0, 0, 0);
}
getError(): Error {
return this.error;
}
}
export function readRpcMessage(buffer: Uint8Array): RpcMessage {
const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
const size = view.getUint32(0, true);
if (size !== buffer.byteLength) throw new Error(`Message buffer size wrong. Message size=${size}, buffer size=${buffer.byteLength}`);
const id = view.getUint32(5, true);
let offset = 9;
const routeType = buffer[offset++];
if (routeType === RpcMessageRouteType.peer) {
offset += 16; //<source>
while (buffer[offset++] !== 0); //feed until \0 byte
} else if (routeType === RpcMessageRouteType.sourceDest) {
offset += 16 + 16; //uuid is each 16 bytes
}
const composite = buffer[offset++] === 1;
const type = buffer[offset++];
return new RpcMessage(id, composite, type, routeType, offset, size - offset, buffer);
}
export const createBuffer: (size: number) => Uint8Array = 'undefined' !== typeof Buffer && 'function' === typeof Buffer.allocUnsafe ? Buffer.allocUnsafe : (size) => new Uint8Array(size);
export interface RpcCreateMessageDef<T> {
type: number;
schema?: ClassSchema<T>;
body?: T
}
export function createRpcCompositeMessage<T>(
id: number,
type: number,
messages: RpcCreateMessageDef<any>[],
routeType: RpcMessageRouteType.client | RpcMessageRouteType.server = RpcMessageRouteType.client,
): Uint8Array {
let bodySize = 0;
for (const message of messages) {
bodySize += 4 + 1 + (message.schema && message.body ? getBSONSizer(message.schema)(message.body) : 0);
}
//<size> <version> <messageId> <routeType>[routeData] <isComposite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + 1 + 1 + bodySize;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(routeType);
writer.writeByte(1);
writer.writeByte(type);
for (const message of messages) {
writer.writeUint32(message.schema && message.body ? getBSONSizer(message.schema)(message.body) : 0);
writer.writeByte(message.type); //type
if (message.schema && message.body) {
//BSON object contain already their size at the beginning
getBSONSerializer(message.schema)(message.body, writer);
}
}
return writer.buffer;
}
export function createRpcCompositeMessageSourceDest<T>(
id: number,
source: Uint8Array,
destination: Uint8Array,
type: number,
messages: RpcCreateMessageDef<any>[],
): Uint8Array {
let bodySize = 0;
for (const message of messages) {
bodySize += 4 + 1 + (message.schema && message.body ? getBSONSizer(message.schema)(message.body) : 0);
}
//<size> <version> <messageId> <routeType>[routeData] <composite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + (16 + 16) + 1 + 1 + bodySize;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(RpcMessageRouteType.sourceDest);
if (source.byteLength !== 16) throw new Error(`Source invalid byteLength of ${source.byteLength}`);
if (destination.byteLength !== 16) throw new Error(`Destination invalid byteLength of ${destination.byteLength}`);
writer.writeBuffer(source);
writer.writeBuffer(destination);
writer.writeByte(1); //composite=true
writer.writeByte(type);
for (const message of messages) {
writer.writeUint32(message.schema && message.body ? getBSONSizer(message.schema)(message.body) : 0);
writer.writeByte(message.type); //type
if (message.schema && message.body) {
//BSON object contain already their size at the beginning
getBSONSerializer(message.schema)(message.body, writer);
}
}
return writer.buffer;
}
export function createRpcMessage<T>(
id: number, type: number,
schema?: ClassSchema<T>, body?: T,
routeType: RpcMessageRouteType.client | RpcMessageRouteType.server = RpcMessageRouteType.client,
): Uint8Array {
if (schema) {
if (!schema.jit.bsonSizer) getBSONSizer(schema);
if (!schema.jit.bsonSerializer) getBSONSerializer(schema);
}
const bodySize = schema && body ? schema.jit.bsonSizer(body) : 0;
//<size> <version> <messageId> <routeType>[routeData] <composite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + 1 + 1 + bodySize;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(routeType);
writer.writeByte(0); //composite=false
writer.writeByte(type);
if (schema && body) schema.jit.bsonSerializer(body, writer);
return writer.buffer;
}
export function createRpcMessageForBody<T>(
id: number, type: number,
body: Uint8Array,
routeType: RpcMessageRouteType.client | RpcMessageRouteType.server = RpcMessageRouteType.client,
): Uint8Array {
const bodySize = body.byteLength;
//<size> <version> <messageId> <routeType>[routeData] <composite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + 1 + 1 + bodySize;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(routeType);
writer.writeByte(0); //composite=false
writer.writeByte(type);
writer.writeBuffer(body);
return writer.buffer;
}
export function createRpcMessagePeer<T>(
id: number, type: number,
source: Uint8Array,
peerId: string,
schema?: ClassSchema<T>, body?: T,
): Uint8Array {
const bodySize = schema && body ? getBSONSizer(schema)(body) : 0;
//<size> <version> <messageId> <routeType>[routeData] <composite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + (16 + peerId.length + 1) + 1 + 1 + bodySize;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(RpcMessageRouteType.peer);
if (source.byteLength !== 16) throw new Error(`Source invalid byteLength of ${source.byteLength}`);
writer.writeBuffer(source);
writer.writeAsciiString(peerId);
writer.writeNull();
writer.writeByte(0); //composite=false
writer.writeByte(type);
if (schema && body) getBSONSerializer(schema)(body, writer);
return writer.buffer;
}
export function createRpcMessageSourceDest<T>(
id: number, type: number,
source: Uint8Array,
destination: Uint8Array,
schema?: ClassSchema<T>, body?: T,
): Uint8Array {
const bodySize = schema && body ? getBSONSizer(schema)(body) : 0;
//<size> <version> <messageId> <routeType>[routeData] <composite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + (16 + 16) + 1 + 1 + bodySize;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(RpcMessageRouteType.sourceDest);
if (source.byteLength !== 16) throw new Error(`Source invalid byteLength of ${source.byteLength}`);
if (destination.byteLength !== 16) throw new Error(`Destination invalid byteLength of ${destination.byteLength}`);
writer.writeBuffer(source);
writer.writeBuffer(destination);
writer.writeByte(0); //composite=false
writer.writeByte(type);
if (schema && body) getBSONSerializer(schema)(body, writer);
return writer.buffer;
}
export function createRpcMessageSourceDestForBody<T>(
id: number, type: number,
source: Uint8Array,
destination: Uint8Array,
body: Uint8Array,
): Uint8Array {
//<size> <version> <messageId> <routeType>[routeData] <composite> <type> <body...>
const messageSize = 4 + 1 + 4 + 1 + (16 + 16) + 1 + 1 + body.byteLength;
const writer = new Writer(createBuffer(messageSize));
writer.writeUint32(messageSize);
writer.writeByte(1); //version
writer.writeUint32(id);
writer.writeByte(RpcMessageRouteType.sourceDest);
if (source.byteLength !== 16) throw new Error(`Source invalid byteLength of ${source.byteLength}`);
if (destination.byteLength !== 16) throw new Error(`Destination invalid byteLength of ${destination.byteLength}`);
writer.writeBuffer(source);
writer.writeBuffer(destination);
writer.writeByte(0); //composite=false
writer.writeByte(type);
writer.writeBuffer(body);
return writer.buffer;
}
export class RpcMessageReader {
protected chunks = new Map<number, { loaded: number, buffers: Uint8Array[] }>();
protected progress = new Map<number, SingleProgress>();
protected chunkAcks = new Map<number, Function>();
protected bufferReader = new RpcBufferReader(this.gotMessage.bind(this));
constructor(
protected readonly onMessage: (response: RpcMessage) => void,
protected readonly onChunk?: (id: number) => void,
) {
}
public onChunkAck(id: number, callback: Function) {
this.chunkAcks.set(id, callback);
}
public registerProgress(id: number, progress: SingleProgress) {
this.progress.set(id, progress);
}
public feed(buffer: Uint8Array, bytes?: number) {
this.bufferReader.feed(buffer, bytes);
}
protected gotMessage(buffer: Uint8Array) {
const message = readRpcMessage(buffer);
// console.log('reader got', message.id, RpcTypes[message.type], message.bodySize, buffer.byteLength);
if (message.type === RpcTypes.ChunkAck) {
const ack = this.chunkAcks.get(message.id);
if (ack) ack();
} else if (message.type === RpcTypes.Chunk) {
const progress = this.progress.get(message.id);
const body = message.parseBody(rpcChunk);
let chunks = this.chunks.get(body.id);
if (!chunks) {
chunks = { buffers: [], loaded: 0 };
this.chunks.set(body.id, chunks);
}
chunks.buffers.push(body.v);
chunks.loaded += body.v.byteLength;
if (this.onChunk) this.onChunk(message.id);
if (progress) progress.set(body.total, chunks.loaded);
if (chunks.loaded === body.total) {
//we're done
this.progress.delete(message.id);
this.chunks.delete(body.id);
this.chunkAcks.delete(body.id);
let offset = 0;
const newBuffer = createBuffer(body.total);
for (const buffer of chunks.buffers) {
newBuffer.set(buffer, offset);
offset += buffer.byteLength;
}
this.onMessage(readRpcMessage(newBuffer));
}
} else {
const progress = this.progress.get(message.id);
if (progress) {
progress.set(buffer.byteLength, buffer.byteLength);
this.progress.delete(message.id);
}
this.onMessage(message);
}
}
}
export function readUint32LE(buffer: Uint8Array, offset: number = 0): number {
return buffer[offset] + (buffer[offset + 1] * 2 ** 8) + (buffer[offset + 2] * 2 ** 16) + (buffer[offset + 3] * 2 ** 24)
}
export class RpcBufferReader {
protected currentMessage?: Uint8Array;
protected currentMessageSize: number = 0;
constructor(
protected readonly onMessage: (response: Uint8Array) => void,
) {
}
public emptyBuffer(): boolean {
return this.currentMessage === undefined;
}
public feed(data: Uint8Array, bytes?: number) {
if (!data.byteLength) return;
if (!bytes) bytes = data.byteLength;
if (!this.currentMessage) {
if (data.byteLength < 4) {
//not enough data to read the header. Wait for next onData
return;
}
this.currentMessage = data.byteLength === bytes ? data : data.slice(0, bytes);
this.currentMessageSize = readUint32LE(data);
} else {
this.currentMessage = Buffer.concat([this.currentMessage, data.byteLength === bytes ? data : data.slice(0, bytes)]);
if (!this.currentMessageSize) {
if (this.currentMessage.byteLength < 4) {
//not enough data to read the header. Wait for next onData
return;
}
this.currentMessageSize = readUint32LE(this.currentMessage);
}
}
let currentSize = this.currentMessageSize;
let currentBuffer = this.currentMessage;
while (currentBuffer) {
if (currentSize > currentBuffer.byteLength) {
//important to save a copy, since the original buffer might change its content
this.currentMessage = new Uint8Array(currentBuffer);
this.currentMessageSize = currentSize;
//message not completely loaded, wait for next onData
return;
}
if (currentSize === currentBuffer.byteLength) {
//current buffer is exactly the message length
this.currentMessageSize = 0;
this.currentMessage = undefined;
this.onMessage(currentBuffer);
return;
}
if (currentSize < currentBuffer.byteLength) {
//we have more messages in this buffer. read what is necessary and hop to next loop iteration
const message = currentBuffer.slice(0, currentSize);
this.onMessage(message);
currentBuffer = currentBuffer.slice(currentSize);
if (currentBuffer.byteLength < 4) {
//not enough data to read the header. Wait for next onData
this.currentMessage = currentBuffer;
return;
}
const nextCurrentSize = readUint32LE(currentBuffer);
if (nextCurrentSize <= 0) throw new Error('message size wrong');
currentSize = nextCurrentSize;
//buffer and size has been set. consume this message in the next loop iteration
}
}
}
}
export interface EncodedError {
classType: string;
message: string;
stack: string;
properties?: { [name: string]: any };
}
export function rpcEncodeError(error: Error | string): EncodedError {
let classType = '';
let stack = '';
let properties: { [name: string]: any } | undefined;
if ('string' !== typeof error) {
const schema = getClassSchema(error['constructor'] as ClassType<typeof error>);
stack = error.stack || '';
if (schema.name) {
classType = schema.name;
if (schema.getPropertiesMap().size) {
properties = jsonSerializer.for(schema).serialize(error);
}
}
}
return {
classType,
properties,
stack,
message: 'string' === typeof error ? error : error.message,
}
}
export function rpcDecodeError(error: EncodedError): Error {
if (error.classType) {
const entity = getGlobalStore().RegisteredEntities[error.classType];
if (!entity) {
throw new Error(`Could not find an entity named ${error.classType} for an error thrown. ` +
`Make sure the class is loaded and correctly defined using @entity.name(${JSON.stringify(error.classType)})`);
}
const classType = getClassSchema(entity).classType! as ClassType<Error>;
if (error.properties) {
const e = jsonSerializer.for(getClassSchema(entity)).deserialize(error.properties) as Error;
e.stack = error.stack + '\nat ___SERVER___';
return e;
}
return new classType(error.message);
}
const e = new Error(error.message);
e.stack = error.stack + '\nat ___SERVER___';
return e;
} | the_stack |
import auth, { AuthType } from '../../Auth';
import { Logger } from '../../cli';
import Command, { CommandArgs, CommandError } from '../../Command';
import config from '../../config';
import request from '../../request';
import { SpoOperation } from '../spo/commands/site/SpoOperation';
import { ClientSvcResponse, ClientSvcResponseContents, ContextInfo, FormDigestInfo } from '../spo/spo';
const csomDefs = require('../../../csom.json');
export interface FormDigest {
formDigestValue: string;
formDigestExpiresAt: Date;
}
export default abstract class SpoCommand extends Command {
/**
* Defines list of options that contain URLs in spo commands. CLI will use
* this list to expand server-relative URLs specified in these options to
* absolute.
* If a command requires one of these options to contain a server-relative
* URL, it should override this method and remove the necessary property from
* the array before returning it.
*/
protected getNamesOfOptionsWithUrls(): string[] {
const namesOfOptionsWithUrls: string[] = [
'appCatalogUrl',
'siteUrl',
'webUrl',
'origin',
'url',
'imageUrl',
'actionUrl',
'logoUrl',
'libraryUrl',
'thumbnailUrl',
'targetUrl',
'newSiteUrl',
'previewImageUrl',
'NoAccessRedirectUrl',
'StartASiteFormUrl',
'OrgNewsSiteUrl',
'parentWebUrl',
'siteLogoUrl'
];
const excludedOptionsWithUrls: string[] | undefined = this.getExcludedOptionsWithUrls();
if (!excludedOptionsWithUrls) {
return namesOfOptionsWithUrls;
}
else {
return namesOfOptionsWithUrls.filter(o => excludedOptionsWithUrls.indexOf(o) < 0);
}
}
/**
* Array of names of options with URLs that should be excluded
* from processing. To be overriden in commands that require
* specific options to be a server-relative URL
*/
protected getExcludedOptionsWithUrls(): string[] | undefined {
return undefined;
}
protected getRequestDigest(siteUrl: string): Promise<FormDigestInfo> {
const requestOptions: any = {
url: `${siteUrl}/_api/contextinfo`,
headers: {
accept: 'application/json;odata=nometadata'
},
responseType: 'json'
};
return request.post(requestOptions);
}
public async processOptions(options: any): Promise<void> {
const namesOfOptionsWithUrls: string[] = this.getNamesOfOptionsWithUrls();
const optionNames = Object.getOwnPropertyNames(options);
for (const optionName of optionNames) {
if (namesOfOptionsWithUrls.indexOf(optionName) < 0) {
continue;
}
const optionValue: any = options[optionName];
if (typeof optionValue !== 'string' ||
!optionValue.startsWith('/')) {
continue;
}
await auth.restoreAuth();
if (!auth.service.spoUrl) {
throw new Error(`SharePoint URL is not available. Set SharePoint URL using the 'm365 spo set' command or use absolute URLs`);
}
options[optionName] = auth.service.spoUrl + optionValue;
}
}
public static isValidSharePointUrl(url: string): boolean | string {
if (!url) {
return false;
}
if (url.indexOf('https://') !== 0) {
return `${url} is not a valid SharePoint Online site URL`;
}
else {
return true;
}
}
public ensureFormDigest(siteUrl: string, logger: Logger, context: FormDigestInfo | undefined, debug: boolean): Promise<FormDigestInfo> {
return new Promise<FormDigestInfo>((resolve: (context: FormDigestInfo) => void, reject: (error: any) => void): void => {
if (this.isValidFormDigest(context)) {
if (debug) {
logger.logToStderr('Existing form digest still valid');
}
resolve(context as FormDigestInfo);
return;
}
this
.getRequestDigest(siteUrl)
.then((res: FormDigestInfo): void => {
const now: Date = new Date();
now.setSeconds(now.getSeconds() + res.FormDigestTimeoutSeconds - 5);
context = {
FormDigestValue: res.FormDigestValue,
FormDigestTimeoutSeconds: res.FormDigestTimeoutSeconds,
FormDigestExpiresAt: now,
WebFullUrl: res.WebFullUrl
};
resolve(context);
}, (error: any): void => {
reject(error);
});
});
}
private isValidFormDigest(contextInfo: FormDigestInfo | undefined): boolean {
if (!contextInfo) {
return false;
}
const now: Date = new Date();
if (contextInfo.FormDigestValue && now < contextInfo.FormDigestExpiresAt) {
return true;
}
return false;
}
protected waitUntilFinished(operationId: string, siteUrl: string, resolve: () => void, reject: (error: any) => void, logger: Logger, currentContext: FormDigestInfo, dots?: string): void {
this
.ensureFormDigest(siteUrl, logger, currentContext, this.debug)
.then((res: FormDigestInfo): Promise<string> => {
currentContext = res;
if (this.debug) {
logger.logToStderr(`Checking if operation ${operationId} completed...`);
}
if (!this.debug && this.verbose) {
dots += '.';
process.stdout.write(`\r${dots}`);
}
const requestOptions: any = {
url: `${siteUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': currentContext.FormDigestValue
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><Query Id="188" ObjectPathId="184"><Query SelectAllProperties="false"><Properties><Property Name="IsComplete" ScalarProperty="true" /><Property Name="PollingInterval" ScalarProperty="true" /></Properties></Query></Query></Actions><ObjectPaths><Identity Id="184" Name="${operationId.replace(/\\n/g, '
').replace(/"/g, '')}" /></ObjectPaths></Request>`
};
return request.post(requestOptions);
})
.then((res: string): void => {
const json: ClientSvcResponse = JSON.parse(res);
const response: ClientSvcResponseContents = json[0];
if (response.ErrorInfo) {
reject(response.ErrorInfo.ErrorMessage);
}
else {
const operation: SpoOperation = json[json.length - 1];
const isComplete: boolean = operation.IsComplete;
if (isComplete) {
if (!this.debug && this.verbose) {
process.stdout.write('\n');
}
resolve();
return;
}
setTimeout(() => {
this.waitUntilFinished(JSON.stringify(operation._ObjectIdentity_), siteUrl, resolve, reject, logger, currentContext, dots);
}, operation.PollingInterval);
}
});
}
protected waitUntilCopyJobFinished(copyJobInfo: any, siteUrl: string, pollingInterval: number, resolve: () => void, reject: (error: any) => void, logger: Logger, dots?: string): void {
const requestUrl: string = `${siteUrl}/_api/site/GetCopyJobProgress`;
const requestOptions: any = {
url: requestUrl,
headers: {
'accept': 'application/json;odata=nometadata'
},
data: { "copyJobInfo": copyJobInfo },
responseType: 'json'
};
if (!this.debug && this.verbose) {
dots += '.';
process.stdout.write(`\r${dots}`);
}
request
.post<{ JobState?: number, Logs: string[] }>(requestOptions)
.then((resp: { JobState?: number, Logs: string[] }): void => {
if (this.debug) {
logger.logToStderr('getCopyJobProgress response...');
logger.logToStderr(resp);
}
for (const item of resp.Logs) {
const log: { Event: string; Message: string } = JSON.parse(item);
// reject if progress error
if (log.Event === "JobError" || log.Event === "JobFatalError") {
return reject(log.Message);
}
}
// two possible scenarios
// job done = success promise returned
// job in progress = recursive call using setTimeout returned
if (resp.JobState === 0) {
// job done
if (this.verbose) {
process.stdout.write('\n');
}
resolve();
}
else {
setTimeout(() => {
this.waitUntilCopyJobFinished(copyJobInfo, siteUrl, pollingInterval, resolve, reject, logger, dots);
}, pollingInterval);
}
});
}
protected getSpoUrl(logger: Logger, debug: boolean): Promise<string> {
if (auth.service.spoUrl) {
if (debug) {
logger.logToStderr(`SPO URL previously retrieved ${auth.service.spoUrl}. Returning...`);
}
return Promise.resolve(auth.service.spoUrl);
}
return new Promise<string>((resolve: (spoUrl: string) => void, reject: (error: any) => void): void => {
if (debug) {
logger.logToStderr(`No SPO URL available. Retrieving from MS Graph...`);
}
const requestOptions: any = {
url: `https://graph.microsoft.com/v1.0/sites/root?$select=webUrl`,
headers: {
'accept': 'application/json;odata.metadata=none'
},
responseType: 'json'
};
request
.get<{ webUrl: string }>(requestOptions)
.then((res: { webUrl: string }): Promise<void> => {
auth.service.spoUrl = res.webUrl;
return auth.storeConnectionInfo();
})
.then((): void => {
resolve(auth.service.spoUrl as string);
}, (err: any): void => {
if (auth.service.spoUrl) {
resolve(auth.service.spoUrl);
}
else {
reject(err);
}
});
});
}
protected getSpoAdminUrl(logger: Logger, debug: boolean): Promise<string> {
return new Promise<string>((resolve: (spoAdminUrl: string) => void, reject: (error: any) => void): void => {
this
.getSpoUrl(logger, debug)
.then((spoUrl: string): void => {
resolve(spoUrl.replace(/(https:\/\/)([^\.]+)(.*)/, '$1$2-admin$3'));
}, (error: any): void => {
reject(error);
});
});
}
protected getTenantId(logger: Logger, debug: boolean): Promise<string> {
if (auth.service.tenantId) {
if (debug) {
logger.logToStderr(`SPO Tenant ID previously retrieved ${auth.service.tenantId}. Returning...`);
}
return Promise.resolve(auth.service.tenantId);
}
return new Promise<string>((resolve: (spoUrl: string) => void, reject: (error: any) => void): void => {
if (debug) {
logger.logToStderr(`No SPO Tenant ID available. Retrieving...`);
}
let spoAdminUrl: string = '';
this
.getSpoAdminUrl(logger, debug)
.then((_spoAdminUrl: string): Promise<ContextInfo> => {
spoAdminUrl = _spoAdminUrl;
return this.getRequestDigest(spoAdminUrl);
})
.then((contextInfo: ContextInfo): Promise<string> => {
const tenantInfoRequestOptions = {
url: `${spoAdminUrl}/_vti_bin/client.svc/ProcessQuery`,
headers: {
'X-RequestDigest': contextInfo.FormDigestValue,
accept: 'application/json;odata=nometadata'
},
data: `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="${config.applicationName}" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="4" ObjectPathId="3" /><Query Id="5" ObjectPathId="3"><Query SelectAllProperties="true"><Properties /></Query></Query></Actions><ObjectPaths><Constructor Id="3" TypeId="{268004ae-ef6b-4e9b-8425-127220d84719}" /></ObjectPaths></Request>`
};
return request.post(tenantInfoRequestOptions);
})
.then((res: string): Promise<void> => {
const json: string[] = JSON.parse(res);
auth.service.tenantId = (json[json.length - 1] as any)._ObjectIdentity_.replace('\n', '
');
return auth.storeConnectionInfo();
})
.then((): void => {
resolve(auth.service.tenantId as string);
}, (err: any): void => {
if (auth.service.tenantId) {
resolve(auth.service.tenantId);
}
else {
reject(err);
}
});
});
}
protected validateUnknownOptions(options: any, csomObject: string, csomPropertyType: 'get' | 'set'): string | boolean {
const unknownOptions: any = this.getUnknownOptions(options);
const optionNames: string[] = Object.getOwnPropertyNames(unknownOptions);
if (optionNames.length === 0) {
return true;
}
for (let i: number = 0; i < optionNames.length; i++) {
const optionName: string = optionNames[i];
const csomOptionType: string = csomDefs[csomObject][csomPropertyType][optionName];
if (!csomOptionType) {
return `${optionName} is not a valid ${csomObject} property`;
}
if (['Boolean', 'String', 'Int32'].indexOf(csomOptionType) < 0) {
return `Unknown properties of type ${csomOptionType} are not yet supported`;
}
}
return true;
}
/**
* Combines base and relative url considering any missing slashes
* @param baseUrl https://contoso.com
* @param relativeUrl sites/abc
*/
protected urlCombine(baseUrl: string, relativeUrl: string): string {
// remove last '/' of base if exists
if (baseUrl.lastIndexOf('/') === baseUrl.length - 1) {
baseUrl = baseUrl.substring(0, baseUrl.length - 1);
}
// remove '/' at 0
if (relativeUrl.charAt(0) === '/') {
relativeUrl = relativeUrl.substring(1, relativeUrl.length);
}
// remove last '/' of next if exists
if (relativeUrl.lastIndexOf('/') === relativeUrl.length - 1) {
relativeUrl = relativeUrl.substring(0, relativeUrl.length - 1);
}
return `${baseUrl}/${relativeUrl}`;
}
public action(logger: Logger, args: CommandArgs, cb: (err?: any) => void): void {
auth
.restoreAuth()
.then((): void => {
if (auth.service.connected && AuthType[auth.service.authType] === AuthType[AuthType.Secret]) {
cb(new CommandError(`SharePoint does not support authentication using client ID and secret. Please use a different login type to use SharePoint commands.`));
return;
}
super.action(logger, args, cb);
}, (error: any): void => {
cb(new CommandError(error));
});
}
} | the_stack |
import alt from '../alt';
import * as _ from 'lodash';
import { IDataSourcePlugin } from './plugins/DataSourcePlugin';
import DialogsActions from '../components/generic/Dialogs/DialogsActions';
import datasourcePluginsMappings from './plugins/PluginsMapping';
import VisibilityActions from '../actions/VisibilityActions';
import VisibilityStore from '../stores/VisibilityStore';
import * as formats from '../utils/data-formats';
const DataFormatTypes = formats.DataFormatTypes;
export interface IDataSource {
id: string;
config: any;
plugin: IDataSourcePlugin;
action: any;
store: any;
initialized: boolean;
}
export interface IDataSourceDictionary {
[key: string]: IDataSource;
}
export interface IExtrapolationResult {
dataSources: { [key: string]: IDataSource };
dependencies: { [key: string]: any };
}
export class DataSourceConnector {
private static dataSources: IDataSourceDictionary = {};
static createDataSource(dataSourceConfig: any, connections: IConnections) {
var config = dataSourceConfig || {};
if (!config.id || !config.type) {
throw new Error('Data source configuration must contain id and type');
}
// Dynamically load the plugin from the plugins directory
var path = datasourcePluginsMappings[config.type];
var PluginClass = require('./plugins/' + path);
var plugin: any = new PluginClass.default(config, connections);
// Creating actions class
var ActionClass = DataSourceConnector.createActionClass(plugin);
// Creating store class
var StoreClass = DataSourceConnector.createStoreClass(config, plugin, ActionClass);
DataSourceConnector.dataSources[config.id] = {
id: config.id,
config,
plugin,
action: ActionClass,
store: StoreClass,
initialized: false
};
return DataSourceConnector.dataSources[config.id];
}
static createDataSources(dsContainer: IDataSourceContainer, connections: IConnections) {
dsContainer.dataSources.forEach(source => {
var dataSource = DataSourceConnector.createDataSource(source, connections);
DataSourceConnector.connectDataSource(dataSource);
});
DataSourceConnector.initializeDataSources();
}
static refreshDs() {
let topLevelDataSources = _.filter(DataSourceConnector.dataSources, ds => !ds.config.dependencies);
topLevelDataSources.forEach(dataSource => {
dataSource.action.refresh.defer();
});
}
static initializeDataSources() {
// Call initialize methods
Object.keys(this.dataSources).forEach(sourceDSId => {
var sourceDS = this.dataSources[sourceDSId];
if (sourceDS.initialized) { return; }
if (typeof sourceDS.action['initialize'] === 'function') {
sourceDS.action.initialize.defer();
}
sourceDS.initialized = true;
});
}
static extrapolateDependencies(dependencies: IStringDictionary, args?: IDictionary): IExtrapolationResult {
var result: IExtrapolationResult = {
dataSources: {},
dependencies: {}
};
Object.keys(dependencies || {}).forEach(key => {
// Find relevant store
let dependency = dependencies[key] || '';
// Checking if this is a constant value
if (dependency.startsWith('::')) {
result.dependencies[key] = dependency.substr(2);
return;
}
// Checking if this is a config value
if (dependency.startsWith('connection:')) {
const connection = dependency.substr(dependency.indexOf(':') + 1);
if (Object.keys(DataSourceConnector.dataSources).length < 1) {
throw new Error('Connection error, couldn\'t find any data sources.');
}
// Selects first data source to get connections
const dataSource: IDataSource = DataSourceConnector.dataSources[
Object.keys(DataSourceConnector.dataSources)[0]];
if (!dataSource || !dataSource.plugin.hasOwnProperty('connections')) {
throw new Error('Tried to resolve connections reference path, but couldn\'t find any connections.');
}
const connections = dataSource.plugin['connections'];
const path = connection.split('.');
if (path.length !== 2) {
throw new Error('Expected connection reference dot path consisting of 2 components.');
}
if (!connections.hasOwnProperty(path[0]) || !connections[path[0]].hasOwnProperty(path[1])) {
throw new Error('Unable to resolve connection reference path:' + connection);
}
result.dependencies[key] = connections[path[0]][path[1]];
return;
}
let dependsUpon = dependency.split(':');
let dataSourceName = dependsUpon[0];
if (dataSourceName === 'args' && args) {
if (dependsUpon.length < 2) {
throw new Error('When padding arguments, you need to provide a specific argument name');
}
let valueName = dependsUpon[1];
result.dependencies[key] = args[valueName];
} else {
let dataSource = DataSourceConnector.dataSources[dataSourceName];
if (!dataSource) {
throw new Error(`Could not find data source for dependency ${dependency}.
If your want to use a constant value, write "value:some value"`);
}
let valueName = dependsUpon.length > 1 ? dependsUpon[1] : dataSource.plugin.defaultProperty;
var state = dataSource.store.getState();
result.dependencies[key] = state[valueName];
result.dataSources[dataSource.id] = dataSource;
}
});
// Checking to see if any of the dependencies control visibility
let visibilityFlags = {};
let updateVisibility = false;
Object.keys(result.dependencies).forEach(key => {
if (key === 'visible') {
visibilityFlags[dependencies[key]] = result.dependencies[key];
updateVisibility = true;
}
});
if (updateVisibility) {
(VisibilityActions.setFlags as any).defer(visibilityFlags);
}
return result;
}
static triggerAction(action: string, params: IStringDictionary, args: IDictionary) {
var actionLocation = action.split(':');
if (actionLocation.length !== 2 && actionLocation.length !== 3) {
throw new Error(`Action triggers should be in format of "dataSource:action", this is not met by ${action}`);
}
var dataSourceName = actionLocation[0];
var actionName = actionLocation[1];
var selectedValuesProperty = 'selectedValues';
if (actionLocation.length === 3) {
selectedValuesProperty = actionLocation[2];
args = { [selectedValuesProperty]: args };
}
if (dataSourceName === 'dialog') {
var extrapolation = DataSourceConnector.extrapolateDependencies(params, args);
DialogsActions.openDialog(actionName, extrapolation.dependencies);
} else {
var dataSource = DataSourceConnector.dataSources[dataSourceName];
if (!dataSource) {
throw new Error(`Data source ${dataSourceName} was not found`);
}
dataSource.action[actionName].call(dataSource.action, args);
}
}
static getDataSources(): IDataSourceDictionary {
return this.dataSources;
}
static getDataSource(name: string): IDataSource {
return this.dataSources[name];
}
static handleDataFormat(
format: string | formats.IDataFormat,
plugin: IDataSourcePlugin,
state: any,
dependencies: IDictionary) {
if (!format) { return null; }
const prevState = DataSourceConnector.dataSources[plugin._props.id].store.getState();
let result = {};
let formatName = (typeof format === 'string' ? format : format.type) || DataFormatTypes.none.toString();
if (formatName && typeof formats[formatName] === 'function') {
let additionalValues = formats[formatName](format, state, dependencies, plugin, prevState) || {};
Object.assign(result, additionalValues);
}
return result;
}
private static connectDataSource(sourceDS: IDataSource) {
// Connect sources and dependencies
sourceDS.store.listen((state) => {
Object.keys(this.dataSources).forEach(checkDSId => {
let checkDS = this.dataSources[checkDSId];
let dependencies = checkDS.plugin.getDependencies() || {};
let populatedDependencies = {};
let connected = _.find(_.keys(dependencies), dependencyKey => {
let dependencyValue = dependencies[dependencyKey] || '';
if (typeof dependencyValue === 'string' && dependencyValue.length > 0) {
if (dependencyValue === sourceDS.id) {
let defaultProperty = sourceDS.plugin.defaultProperty || 'value';
populatedDependencies[dependencyKey] = state[defaultProperty];
return true;
} else if (dependencyValue.startsWith(sourceDS.id + ':')) {
let property = dependencyValue.substr(sourceDS.id.length + 1);
populatedDependencies[dependencyKey] = _.get(state, property);
return true;
}
}
return false;
});
if (connected) {
// Todo: add check that all dependencies are met
checkDS.action.updateDependencies.defer(populatedDependencies);
}
});
// Checking visibility flags
let visibilityState = VisibilityStore.getState() || {};
let flags = visibilityState.flags || {};
let updatedFlags = {};
let shouldUpdate = false;
Object.keys(flags).forEach(visibilityKey => {
let keyParts = visibilityKey.split(':');
if (keyParts[0] === sourceDS.id) {
updatedFlags[visibilityKey] = sourceDS.store.getState()[keyParts[1]];
shouldUpdate = true;
}
});
if (shouldUpdate) {
(VisibilityActions.setFlags as any).defer(updatedFlags);
}
});
}
private static createActionClass(plugin: IDataSourcePlugin): any {
class NewActionClass {
constructor() { }
}
plugin.getActions().forEach(action => {
if (typeof plugin[action] === 'function') {
// This method will be called with an action is dispatched
NewActionClass.prototype[action] = function (...args: Array<any>) {
// Collecting depedencies from all relevant stores
var extrapolation;
if (args.length === 1) {
extrapolation = DataSourceConnector.extrapolateDependencies(plugin.getDependencies(), args[0]);
} else {
extrapolation = DataSourceConnector.extrapolateDependencies(plugin.getDependencies());
}
// Calling action with arguments
let result = plugin[action].call(this, extrapolation.dependencies, ...args) || {};
// Checking is result is a dispatcher or a direct value
if (typeof result === 'function') {
return (dispatch) => {
result(function (obj: any) {
obj = obj || {};
let fullResult = DataSourceConnector.callibrateResult(obj, plugin, extrapolation.dependencies);
dispatch(fullResult);
});
};
} else {
let fullResult = DataSourceConnector.callibrateResult(result, plugin, extrapolation.dependencies);
return fullResult;
}
};
} else {
// Adding generic actions that are directly proxied to the store
alt.addActions(action, <any> NewActionClass);
}
});
// Binding the class to Alt and the plugin
var ActionClass = alt.createActions(<any> NewActionClass);
plugin.bind(ActionClass);
return ActionClass;
}
private static createStoreClass(config: any, plugin: any, ActionClass: any): any {
var bindings = [];
plugin.getActions().forEach(action => {
bindings.push(ActionClass[action]);
});
class NewStoreClass {
constructor() {
(<any> this).bindListeners({ updateState: bindings });
}
updateState(newData: any) {
(<any> this).setState(newData);
}
}
var StoreClass = alt.createStore(NewStoreClass as any, config.id + '-Store');
return StoreClass;
}
private static callibrateResult(result: any, plugin: IDataSourcePlugin, dependencies: IDictionary): any {
let defaultProperty = plugin.defaultProperty || 'value';
// In case result is not an object, push result into an object
if (typeof result !== 'object') {
var resultObj = {};
resultObj[defaultProperty] = result;
result = resultObj;
}
// Callibrate calculated values
const calculated = plugin._props.calculated;
let state = DataSourceConnector.dataSources[plugin._props.id].store.getState();
state = _.extend(state, result);
if (typeof calculated === 'function') {
let additionalValues = calculated(state, dependencies) || {};
Object.assign(result, additionalValues);
}
if (Array.isArray(calculated)) {
calculated.forEach(calc => {
let additionalValues = calc(state, dependencies) || {};
Object.assign(result, additionalValues);
});
}
state = _.extend(state, result);
let format = plugin.getFormat();
let formatExtract = DataSourceConnector.handleDataFormat(format, plugin, state, dependencies);
if (formatExtract) {
Object.assign(result, formatExtract);
}
return result;
}
} | the_stack |
import * as asyncFs from "@ts-common/fs"
import * as jsonParser from "@ts-common/json-parser"
import { getFilePosition } from "@ts-common/source-map"
import * as child_process from "child_process"
import * as fs from "fs"
import JSON_Pointer from "json-pointer"
import * as jsonRefs from "json-refs"
import * as os from "os"
import * as path from "path"
import * as sourceMap from "source-map"
import * as util from "util"
import { log } from "../util/logging"
import { ResolveSwagger } from "../util/resolveSwagger"
import { pathToJsonPointer } from "../util/utils"
const _ = require("lodash")
const exec = util.promisify(child_process.exec)
export type Options = {
readonly consoleLogLevel?: unknown
readonly logFilepath?: unknown
}
export type ProcessedFile = {
readonly fileName: string
readonly map: sourceMap.BasicSourceMapConsumer | sourceMap.IndexedSourceMapConsumer
readonly resolvedFileName: string
readonly resolvedJson: any
}
export type ChangeProperties = {
readonly location?: string
readonly path?: string
readonly ref?: string
}
export type Message = {
readonly id: string
readonly code: string
readonly docUrl: string
readonly message: string
readonly mode: string
readonly type: string
readonly new: ChangeProperties
readonly old: ChangeProperties
}
export type Messages = ReadonlyArray<Message>
const updateChangeProperties = (change: ChangeProperties, pf: ProcessedFile): ChangeProperties => {
if (change.location) {
let position
let jsonPointer
if (change.path != undefined) {
try {
jsonPointer = pathToJsonPointer(change.path)
const jsonValue = JSON_Pointer.get(pf.resolvedJson, jsonPointer)
position = getFilePosition(jsonValue)
} catch (e) {
console.log(e.message)
}
}
if (!position || !Object.keys(position).length) {
return { ...change, ref: "", location: "" }
}
const originalPosition = pf.map.originalPositionFor(position)
if (!originalPosition || !Object.keys(originalPosition).length) {
return { ...change, ref: "", location: "" }
}
const name = originalPosition.name as string
const namePath = name ? name.split("\n")[0] : ""
const parsedPath = namePath ? (JSON.parse(namePath) as string[]) : ""
const ref = parsedPath ? `${originalPosition.source}${jsonRefs.pathToPtr(parsedPath, true)}` : ""
const location = `${originalPosition.source}:${originalPosition.line}:${(originalPosition.column as number) + 1}`
return { ...change, ref, location }
} else {
return {}
}
}
/**
* @class
* Open API Diff class.
*/
export class OpenApiDiff {
/**
* Constructs OpenApiDiff based on provided options.
*
* @param {object} options The configuration options.
*
* @param {boolean} [options.json] A boolean flag indicating whether output format of the messages is json.
*
* @param {boolean} [options.matchApiVersion] A boolean flag indicating whether to consider api-version while comparing.
*/
constructor(private options: Options) {
log.silly(`Initializing OpenApiDiff class`)
if (this.options === null || this.options === undefined) {
this.options = {}
}
if (typeof this.options !== "object") {
throw new Error('options must be of type "object".')
}
log.debug(`Initialized OpenApiDiff class with options = ${util.inspect(this.options, { depth: null })}`)
}
/**
* Compares old and new specifications.
*
* @param {string} oldSwagger Path to the old specification file.
*
* @param {string} newSwagger Path to the new specification file.
*
* @param {string} oldTag Tag name used for AutoRest with the old specification file.
*
* @param {string} newTag Tag name used for AutoRest with the new specification file.
*
*/
public async compare(oldSwagger: string, newSwagger: string, oldTag?: string, newTag?: string) {
log.silly(`compare is being called`)
const results = []
results[0] = await this.processViaAutoRest(oldSwagger, "old", oldTag)
results[1] = await this.processViaAutoRest(newSwagger, "new", newTag)
return this.processViaOpenApiDiff(results[0], results[1])
}
/**
* Gets path to the dotnet executable.
*
* @returns {string} Path to the dotnet executable.
*/
public dotNetPath(): string {
log.silly(`dotNetPath is being called`)
// Assume that dotnet is in the PATH
return "dotnet"
}
/**
* Gets path to the autorest application.
*
* @returns {string} Path to the autorest app.js file.
*/
public autoRestPath(): string {
log.silly(`autoRestPath is being called`)
// When oad is installed globally
{
const result = path.join(__dirname, "..", "..", "..", "node_modules", "autorest", "dist", "app.js")
if (fs.existsSync(result)) {
log.silly(`Found autoRest:${result} `)
return `node ${result}`
}
}
// When oad is installed locally
{
const result = path.join(__dirname, "..", "..", "..", "..", "..", "autorest", "dist", "app.js")
if (fs.existsSync(result)) {
log.silly(`Found autoRest:${result} `)
return `node ${result}`
}
}
// Try to find autorest in `node-modules`
{
const result = path.resolve("node_modules/.bin/autorest")
if (fs.existsSync(result)) {
log.silly(`Found autoRest:${result} `)
return result
}
}
// Assume that autorest is in the path
return "autorest"
}
/**
* Gets path to the OpenApiDiff.dll.
*
* @returns {string} Path to the OpenApiDiff.dll.
*/
public openApiDiffDllPath(): string {
log.silly(`openApiDiffDllPath is being called`)
return path.join(__dirname, "..", "..", "..", "dlls", "OpenApiDiff.dll")
}
/**
* Processes the provided specification via autorest.
*
* @param {string} swaggerPath Path to the specification file.
*
* @param {string} outputFileName Name of the output file to which autorest outputs swagger-doc.
*
* @param {string} tagName Name of the tag in the specification file.
*
*/
public async processViaAutoRest(swaggerPath: string, outputFileName: string, tagName?: string): Promise<ProcessedFile> {
log.silly(`processViaAutoRest is being called`)
if (swaggerPath === null || swaggerPath === undefined || typeof swaggerPath.valueOf() !== "string" || !swaggerPath.trim().length) {
throw new Error('swaggerPath is a required parameter of type "string" and it cannot be an empty string.')
}
if (
outputFileName === null ||
outputFileName === undefined ||
typeof outputFileName.valueOf() !== "string" ||
!outputFileName.trim().length
) {
throw new Error('outputFile is a required parameter of type "string" and it cannot be an empty string.')
}
log.debug(`swaggerPath = "${swaggerPath}"`)
log.debug(`outputFileName = "${outputFileName}"`)
if (!fs.existsSync(swaggerPath)) {
throw new Error(`File "${swaggerPath}" not found.`)
}
const outputFolder = os.tmpdir()
const outputFilePath = path.join(outputFolder, `${outputFileName}.json`)
const outputMapFilePath = path.join(outputFolder, `${outputFileName}.map`)
const autoRestCmd = tagName
? `${this.autoRestPath()} ${swaggerPath} --tag=${tagName} --output-artifact=swagger-document.json` +
` --output-artifact=swagger-document.map --output-file=${outputFileName} --output-folder=${outputFolder}`
: `${this.autoRestPath()} --input-file=${swaggerPath} --output-artifact=swagger-document.json` +
` --output-artifact=swagger-document.map --output-file=${outputFileName} --output-folder=${outputFolder}`
log.debug(`Executing: "${autoRestCmd}"`)
const { stderr } = await exec(autoRestCmd, {
encoding: "utf8",
maxBuffer: 1024 * 1024 * 64,
env: { ...process.env, NODE_OPTIONS: "--max-old-space-size=8192" }
})
if (stderr) {
throw new Error(stderr)
}
const resolveSwagger = new ResolveSwagger(outputFilePath)
const resolvedJson = resolveSwagger.resolve()
const resolvedPath: string = resolveSwagger.getResolvedPath()
if (!resolvedJson) {
throw new Error("resolve failed!")
}
const buffer = await asyncFs.readFile(outputMapFilePath)
const map = await new sourceMap.SourceMapConsumer(buffer.toString())
log.debug(`outputFilePath: "${outputFilePath}"`)
return {
fileName: outputFilePath,
map,
resolvedFileName: resolvedPath,
resolvedJson
}
}
/**
* Processes the provided specifications via OpenApiDiff tool.
*
* @param {string} oldSwagger Path to the old specification file.
*
* @param {string} newSwagger Path to the new specification file.
*
*/
public async processViaOpenApiDiff(oldSwaggerFile: ProcessedFile, newSwaggerFile: ProcessedFile) {
log.silly(`processViaOpenApiDiff is being called`)
const oldSwagger = oldSwaggerFile.resolvedFileName
const newSwagger = newSwaggerFile.resolvedFileName
if (oldSwagger === null || oldSwagger === undefined || typeof oldSwagger.valueOf() !== "string" || !oldSwagger.trim().length) {
throw new Error('oldSwagger is a required parameter of type "string" and it cannot be an empty string.')
}
if (newSwagger === null || newSwagger === undefined || typeof newSwagger.valueOf() !== "string" || !newSwagger.trim().length) {
throw new Error('newSwagger is a required parameter of type "string" and it cannot be an empty string.')
}
log.debug(`oldSwagger = "${oldSwagger}"`)
log.debug(`newSwagger = "${newSwagger}"`)
if (!fs.existsSync(oldSwagger)) {
throw new Error(`File "${oldSwagger}" not found.`)
}
if (!fs.existsSync(newSwagger)) {
throw new Error(`File "${newSwagger}" not found.`)
}
const cmd = `${this.dotNetPath()} ${this.openApiDiffDllPath()} -o ${oldSwagger} -n ${newSwagger}`
log.debug(`Executing: "${cmd}"`)
const { stdout } = await exec(cmd, { encoding: "utf8", maxBuffer: 1024 * 1024 * 64 })
const resultJson = JSON.parse(stdout) as Messages
const updatedJson = resultJson.map(message => ({
...message,
new: updateChangeProperties(message.new, newSwaggerFile),
old: updateChangeProperties(message.old, oldSwaggerFile)
}))
const uniqueJson = _.uniqWith(updatedJson, _.isEqual)
return JSON.stringify(uniqueJson)
}
} | the_stack |
import {parse} from '../../gen/runtime/manifest-parser.js';
import {assert} from '../../platform/chai-web.js';
import {Flags} from '../flags.js';
describe('manifest parser', () => {
it('parses an empty manifest', () => {
parse('');
});
it('parses a trivial recipe', () => {
parse(`recipe Recipe &tag1 &tag2`);
});
it('parses with indentation', () => {
parse(`
recipe Recipe`);
});
it('fails to parse non-standard indentation (horizontal tab)', () => {
// Note: This is to protect against confusing whitespace issues caused by
// mixed tabs and spaces.
assert.throws(() => {
parse('\trecipe Recipe');
}, 'Expected space but "\\t" found.');
});
it('fails to parse non-standard indentation (vertical tab)', () => {
// Note: This is to protect against confusing whitespace issues caused by
// mixed tabs and spaces.
assert.throws(() => {
parse('\vrecipe Recipe');
}, 'Expected space but "\\x0B" found.');
});
it('fails to parse non-standard indentation (non-breaking space)', () => {
// Note: This is to protect against confusing whitespace issues caused by
// mixed tabs and spaces.
assert.throws(() => {
parse('\xA0recipe Recipe');
}, 'Expected space but "\xA0" found.');
});
it('parses recipes that map handles', () => {
parse(`
recipe Thing
map #someTag
map 'some-id' #someTag`);
});
it('parses recipes that creates handles with ttls', () => {
parse(`
recipe Thing
h0: create #myTag @ttl('20d')
h1: create 'my-id' #anotherTag @ttl('1h')
h2: create @ttl ( '30m' )`);
});
it('parses recipes with a synthetic join handles', () => {
parse(`
recipe
people: map #folks
places: map #locations
pairs: join (people, places)`);
});
it('parses recipe handles with capabilities', () => {
parse(`
recipe Thing
h0: create @persistent
h1: create 'my-id' @tiedToRuntime
h2: create #mytag @tiedToArc`);
});
it('parses schema annotations', () => {
parse(`
schema Abcd
foo: &MyFoo @aFoo
`);
});
it('parses particle schema annotations', () => {
parse(`
particle Foo
a: reads B {
foo: &MyFoo @aFoo
}
`);
});
it('parses recipes with particles', () => {
parse(`
recipe Recipe
SomeParticle`);
});
it('parses recipes that connect particles to handles', () => {
parse(`
recipe Recipe
SomeParticle
a: writes #something
b: reads #somethingElse
#someOtherParticle`);
});
it('parses trivial particles', () => {
parse(`
particle SomeParticle`);
});
it('parses recipes that name handles and particles', () => {
parse(`
recipe Recipe
SomeParticle as thing
anotherThing: map #thing`);
});
it('parses manifests with comments', () => {
parse(`
// comment
recipe // comment
// comment
// comment
A//comment
// comment
// comment
B //comment
`);
});
describe('parses block comments', () => {
it('parses recipes with a single block comment', () => {
parse(`
recipe
X: writes /*comment here*/ Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash`);
});
it('parses recipes with a single block comment with an extra star', () => {
parse(`
recipe
X: writes /*comment here**/ Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash`);
});
it('fails to parse recipes with unfinished block comments', () => {
assert.throws(() => {
parse(`
recipe
X: writes /*comment here Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash`);
}, 'Unfinished block comment');
});
it('fails to parse recipes with unfinished nested block comments', () => {
assert.throws(() => {
parse(`
recipe
X: writes /*comment /*here*/ Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash`);
}, 'Unfinished block comment');
});
it('parses recipes with block comments', () => {
parse(`
recipe
X: writes /*comment here*/ Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash /* block
comment here
*/
a: b
a.a: b.b
X.a #tag: reads a.y
/* trailing block comment
* here
*/`);
});
it('parses recipes with nested block comments', () => {
parse(`
recipe
X: writes /*comment /*here*/*/ Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash /* block
/*comment*/ with inner /*'comments'*/ here
*/
a: b
a.a: b.b
X.a #tag: reads a.y
/* trailing block comment
* /*here/ */
*/`);
});
});
it('parses recipes with recipe level connections', () => {
parse(`
recipe
X: writes Y
X.a: writes Y.a
&foo.bar: writes &far.#bash #fash
a: b
a.a: b.b
X.a #tag: reads a.y`);
});
it('parses manifests with stores', () => {
parse(`
schema Person
lastName: Text
firstName: Text
description \`person\`
plural \`people\`
value \`\${firstName} \${lastName}\`
store Store0 of [Person] in 'people.json'
description \`my store\`
store Store1 of Person 'some-id' @7 in 'person.json'
store Store2 of BigCollection<Person> in 'population.json'`);
});
it('fails to parse a particle handle with an unknown capability/direction', () => {
assert.throws(() => {
parse(`
particle MyParticle
foo: read MyThing`);
},
/Expected a direction \(reads, writes.*\) but "read" found\./,
'this parse should have failed, unknown capabilities/directions should not be accepted!'
);
});
it('fails to parse a recipe connection with an unknown capability/direction', () => {
assert.throws(() => {
parse(`
recipe MyParticle
foo: read bar`);
},
/Expected a direction \(reads, writes.*\) but "read" found\./,
'this parse should have failed, unknown capabilities/directions should not be accepted!'
);
});
it('fails to parse an argument list that use a reserved word as an identifier', () => {
assert.throws(() => {
parse(`
particle MyParticle
consumes: reads MyThing
output: writes? BigCollection<MyThing>`);
},
/Expected/,
'this parse should have failed, identifiers should not be reserved words!'
);
});
it('allows identifiers to start with reserved words', () => {
parse(`
particle MyParticle
mapped: reads MyThing
import_export: writes? BigCollection<MyThing>`);
});
it('allows reserved words for schema field names', () => {
// Test with a non-word char following the token
parse(`
schema Reserved
schema: Text // comment`);
// Test with end-of-input following the token
parse(`
schema Reserved
map: URL`);
});
it('allows reserved words for inline schema field names', () => {
parse(`
particle Foo
a: reads A {handle: Text}
b: writes B {import: Boolean, particle: Number}`);
});
it('disallows reserved words for handle names', () => {
assert.throws(() => {
parse(`
particle Foo
reads: reads A {handle: Text}
in: writes B {import: Boolean, particle: Number}`);
}, `Expected an identifier (but found reserved word 'reads')`);
});
it('fails to parse an unterminated identifier', () => {
assert.throws(() => {
parse(`import 'foo`);
}, 'Expected');
});
it('fails to parse an identifier containing a new line', () => {
assert.throws(() => {
parse(`
import 'foo
'`);
},
/Identifiers must be a single line \(possibly missing a quote mark " or '\)/,
'this parse should have failed, identifiers should not be multiline!'
);
});
it('fails to parse a nonsense argument list', () => {
assert.throws(() => {
parse(`
particle AParticle
Nonsense()`);
},
/N/,
'this parse should have failed, no nonsense!'
);
});
it('parses particles with optional handles', () => {
parse(`
particle MyParticle
mandatory: reads MyThing
optional1: reads? MyThing
optional2: writes? [MyThing]
optional3: writes? BigCollection<MyThing>`);
});
it('parses manifests with search', () => {
parse(`
recipe
search \`hello World!\`
`);
});
it('parses manifests with search and tokens', () => {
parse(`
recipe
search \`Hello dear world\`
tokens \`hello\` \`World\` // \`dear\`
`);
});
it('parses manifests particle verbs', () => {
parse(`
particle SomeParticle
energy: reads Energy
height: writes Height
modality dom`);
});
it('parses recipe with particle verbs', () => {
parse(`
recipe
&jump
reads energy
writes height`);
});
it('parses recipe with particle verb shorthand', () => {
parse(`
recipe
&jump
reads energy
reads height`);
});
it('parses inline schemas', () => {
parse(`
particle Foo
mySchema: reads MySchema {value: Text}
`);
parse(`
particle Foo
mySchema: reads [MySchema {value: Text}]
`);
parse(`
particle Foo
anonSchema: reads [* {value: Text, num: Number}]
`);
parse(`
particle Foo
union: reads * {value: (Text or Number)}
`);
parse(`
particle Foo
optionalType: reads * {value}
`);
});
it('parses inline schemas with any name', () => {
parse(`
particle Foo
anonSchema: reads [* {value: Text, num: Number}]
`);
parse(`
particle Foo
union: reads * {value: (Text or Number)}
`);
parse(`
particle Foo
optionalType: reads * {value}
`);
});
it('parses inline schemas with a trailing comma', () => {
parse(`
particle Foo
input: reads [{value: Text, num: Number,}]
`);
parse(`
particle Foo
input: reads [{
value: Text,
num: Number,
}]
`);
});
it('parses inline schemas with no name', () => {
parse(`
particle Foo
anonSchema: reads [{value: Text, num: Number}]
`);
parse(`
particle Foo
union: reads {value: (Text or Number)}
`);
parse(`
particle Foo
optionalType: reads {value}
`);
});
it('parses a schema with a bytes field', () => {
parse(`
schema Avatar
name: Text
profileImage: Bytes
`);
});
it('parses a schema with a reference field', () => {
parse(`
schema Product
review: &Review
`);
});
it('parses a schema with a referenced inline schema', () => {
parse(`
schema Product
review: &Review {reviewText: Text}
`);
});
it('parses an inline schema with a reference to a schema', () => {
parse(`
particle Foo
inReview: reads Product {review: &Review}
`);
});
it('parses an inline schema with a collection of references to schemas', () => {
parse(`
particle Foo
inResult: reads Product {review: [&Review]}
`);
});
it('parses an inline schema with a referenced inline schema', () => {
parse(`
particle Foo
inReview: reads Product {review: &Review {reviewText: Text} }
`);
});
it('parses an inline schema with a collection of references to inline schemas', () => {
parse(`
particle Foo
productReviews: reads Product {review: [&Review {reviewText: Text}]}
`);
});
it('parses an inline schema with a collection of references to inline schemas (with sugar)', () => {
parse(`
particle Foo
productReviews: reads Product {review: [&Review {reviewText: Text}]}
`);
});
it('parses a schema with kotlin types', () => {
parse(`
schema KotlinThings
aByte: Byte
aShort: Short
anInt: Int
aLong: Long
aChar: Char
aFloat: Float
aDouble: Double
`);
});
it('parses an inline schema with kotlin types', () => {
parse(`
particle Foo
kotlinThings: reads KotlinThings {aByte: Byte, aShort: Short, anInt: Int, aLong: Long, aChar: Char, aFloat: Float, aDouble: Double}
`);
});
it('parses a schema with a nested schema', () => {
parse(`
schema ContainsNested
fieldBefore: Double
nestedField: inline * {someNums: List<Number>, aString: Text}
fieldAfter: List<Long>
`);
});
it('parses an inline schema with a nested schema', () => {
parse(`
particle Foo
containsNested: reads ContainsNested {
fieldBefore: Double,
nestedField: inline Thing {someNums: List<Number>, aString: Text},
fieldAfter: Long
}
`);
});
it('parses a schema with a list of nested schemas', () => {
parse(`
schema ContainsNested
fieldBefore: Double
nestedField: List<inline * {someNums: List<Number>, aString: Text}>
fieldAfter: List<Long>
`);
});
it('parses an inline schema with a list of nested schemas', () => {
parse(`
particle Foo
containsNested: reads ContainsNested {
fieldBefore: Double,
nestedField: List<inline Thing {someNums: List<Number>, aString: Text}>,
fieldAfter: Long
}
`);
});
it('parses an schema that inlines another schema', () => {
parse(`
schema GetsNested
num: Number
schema ContainsExternalNested
nestyMcNestFace: inline GetsNested
text: Text
`);
});
it('parses a schema with ordered list types', () => {
parse(`
schema OrderedLists
someNums: List<Number>
someLongs: List<Long>
someStrings: List<Text>
someReferences: List<&{}>
someUnions: List<(Number or Text)>
`);
});
it('parses an inline schema with ordered list types', () => {
parse(`
particle Foo
orderedThings: reads OrderedLists {someNums: List<Number>, someLongs: List<Long>, someStrings: List<Text>, someReferences: List<&{}>, someUnions: List<(Number or Text)>}
`);
});
it('parses typenames with reserved type names as a prefix (Boolean)', () => {
parse(`
particle Foo
inRef: reads Booleanlike
`);
});
it('fails to parse reserved type names (Boolean)', () => {
assert.throws(() => {
parse(`
particle Foo
inRef: reads Boolean
`);
}, 'Expected an upper case identifier but "Boolean" found.');
});
it('fails to parse reserved type names (URL)', () => {
assert.throws(() => {
parse(`
particle Foo
outRef: writes URL
`);
}, 'Expected an upper case identifier but "URL" found.');
});
it('parses reference types', () => {
parse(`
particle Foo
inRef: reads &Foo
outRef: writes &Bar
`);
});
it('fails to parse an empty tuple', () => {
assert.throws(() => {
parse(`
particle Foo
data: reads ()
`);
});
});
it('parses tuple with one type', () => {
parse(`
particle Foo
data: reads (Foo)
`);
});
it('parses tuple with two types', () => {
parse(`
particle Foo
data: writes ([Foo], &Bar {name: Text})
`);
});
it('fails to parse a tuple without separator between elements', () => {
assert.throws(() => {
parse(`
particle Foo
data: reads (Foo{}Bar{})
`);
});
});
it('parses tuple with indented types and comments', () => {
parse(`
particle Foo
data: reads (
Foo, // First type
&Bar {name: Text}, // Second type
[Baz {photo: URL}] // Third type
)
`);
});
it('parses tuple with indented types and trailing comma', () => {
parse(`
particle Foo
data: reads (
&Foo,
&Bar,
)
`);
});
it('parses type variables without constraints', () => {
parse(`
particle Foo
data: reads ~a
`);
});
it('parses type variables with a constraint', () => {
parse(`
particle Foo
data: reads ~a with {name: Text}
`);
});
it('parses type variables with multiple constraints', () => {
parse(`
particle Foo
data: reads ~a with {name: Text, age: Number}
`);
});
it('parses max type variables without constraints', () => {
parse(`
particle Foo
data: reads ~a with {*}
`);
});
it('parses max type variables with a constraint', () => {
parse(`
particle Foo
data: reads ~a with {name: Text, *}
`);
});
it('parses max type variables with multiple constraints', () => {
parse(`
particle Foo
data: reads ~a with {name: Text, age: Number, *}
`);
});
it('parses max type variables with oddly-ordered constraints', () => {
parse(`
particle Foo
data: reads ~a with {name: Text, *, age: Number}
`);
parse(`
particle Foo
data: reads ~a with {*, age: Number}
`);
});
it('parses max type variables with multiple `*`s', () => {
parse(`
particle Foo
data: reads ~a with {name: Text, *, *}
`);
assert.throws(() => {
parse(`
particle Foo
data: reads ~a with {name: Text, * *}
`);
});
assert.throws(() => {
parse(`
particle Foo
data: reads ~a with {* *}
`);
});
});
it('parses refinement types in a schema', Flags.withFieldRefinementsAllowed(async () => {
parse(`
schema Foo
num: Number [num > 10]
`);
}));
it('parses refinement types in a particle', Flags.withFieldRefinementsAllowed(async () => {
parse(`
particle Foo
input: reads Something {value: Text [ (square - 5) < 11 and (square * square > 5) or square == 0] }
`);
parse(`
particle Foo
input: reads Something {value: Number [value > 0], price: Number [price > 0]} [value > 10 and price < 5]
`);
parse(`
particle Foo
input: reads Something {value: Number, price: Number} [value > 10 and price < 5]
`);
parse(`
particle Foo
input: reads Something {value: Text [value == 'abc']}
`);
}));
it('parses multi-line refinements', Flags.withFieldRefinementsAllowed(async () => {
parse(`
particle Foo
input: reads Something {
value: Text [
(square - 5) < 11
and (square * square > 5)
or square == 0
]
}
`);
}));
it('tests the refinement syntax tree', Flags.withFieldRefinementsAllowed(async () => {
const manifestAst = parse(`
particle Foo
input: reads Something {value: Text [ a < b and d > 2*2+1 ] }
`);
const particle = manifestAst[0];
const handle = particle.args[0];
const htype = handle.type;
assert.deepEqual(htype.kind, 'schema-inline', 'Unexpected handle type.');
const refExpr = htype.fields[0].type.refinement.expression;
let root = refExpr;
assert.deepEqual(root.kind, 'binary-expression-node');
assert.deepEqual(root.operator, 'and');
root = refExpr.leftExpr;
assert.deepEqual(root.kind, 'binary-expression-node');
assert.deepEqual(root.operator, '<');
assert.deepEqual(root.leftExpr.value, 'a');
assert.deepEqual(root.rightExpr.value, 'b');
root = refExpr.rightExpr;
assert.deepEqual(root.kind, 'binary-expression-node');
assert.deepEqual(root.operator, '>');
assert.deepEqual(root.leftExpr.value, 'd');
root = refExpr.rightExpr.rightExpr;
assert.deepEqual(root.kind, 'binary-expression-node');
assert.deepEqual(root.operator, '+');
assert.deepEqual(root.rightExpr.value, 1);
root = refExpr.rightExpr.rightExpr.leftExpr;
assert.deepEqual(root.kind, 'binary-expression-node');
assert.deepEqual(root.operator, '*');
assert.deepEqual(root.leftExpr.value, 2);
assert.deepEqual(root.rightExpr.value, 2);
}));
it('does not parse invalid refinement expressions', () => {
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text [value <<>>>>> ]}
`);
}, `a valid refinement expression`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text [ [[ value *- 2 ]}
`);
}, `a valid refinement expression`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text [ value */ 2 ]}
`);
}, `a valid refinement expression`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text } [ value.x / 2 ]
`);
}, `Scope lookups are not currently supported in refinements, only in paxel expressions`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text } [ now(x) > 0 ]
`);
}, `Functions may have arguments only in paxel expressions`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text } [ average() > 0 ]
`);
}, `Function 'average' is only supported in paxel expressions.`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Text } [ (from p in q select p) > 0 ]
`);
}, `Paxel expressions are not allowed in refinements`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Number } [ value ?: 42 > 0 ]
`);
}, `If null operator '?:' is only allowed in paxel expressions`);
assert.throws(() => {
parse(`
particle Foo
input: reads Something {value: Number } [ value != null ]
`);
}, `Null literal is only allowed in paxel expressions`);
});
it('parses nested referenced inline schemas', () => {
parse(`
particle Foo
mySchema: reads MySchema {value: &OtherSchema {name: Text}}
`);
});
it('fails to parse nested (non-referenced) inline schemas', () => {
assert.throws(() => {
parse(`
particle Foo
mySchema: reads MySchema {value: OtherSchema {name: Text}}
`);
}, 'a schema type');
});
it('parses require section using local name', () => {
parse(`
recipe
require
handle as thing`);
});
it('parses require section using id', () => {
parse(`
recipe
require
handle 'an-id'`);
});
it('parses require section using local name and id', () => {
parse(`
recipe
require
handle as thing 'an-id'`);
});
it('parses require section using upperIdent', () => {
parse(`
recipe
require
handle Thing`);
});
it('parses require section with tags', () => {
parse(`
recipe
require
handle as thing Thing #tag1 #tag2`);
});
it('parses require section with handles, slots and particles', () => {
parse(`
recipe
require
handle as thing
thing2: slot
Particle
reads thing
consumes thing2
`);
});
it('parses handle creation using the handle keyword', () => {
parse(`
recipe
handle as h0
Particle
input: reads h0
`);
});
it('parses handle with type with prefix "Slot"', () => {
parse(`
particle P in './p.js'
s: reads Sloturnicus
`);
});
it('does not parse comment at start of manifest resource', () => {
let data;
assert.throws(() => {
const manifestAst = parse(`
import '../Pipes/PipeEntity.schema'
resource PipeEntityResource
start
//[{"type": "tv_show", "name": "star trek"}]
[{"type": "artist", "name": "in this moment"}]
store ExamplePipeEntity of PipeEntity 'ExamplePipeEntity' @0 in PipeEntityResource
`);
data = JSON.parse(manifestAst[1].data);
}, `Unexpected token / in JSON at position 0`);
assert.strictEqual(data, undefined);
});
it('does not parse comment inside manifest resource', () => {
let data;
assert.throws(() => {
const manifestAst = parse(`
import '../Pipes/PipeEntity.schema'
resource PipeEntityResource
start
[{"type": "artist", "name": "in this moment"}]
//[{"type": "tv_show", "name": "star trek"}]
store ExamplePipeEntity of PipeEntity 'ExamplePipeEntity' @0 in PipeEntityResource
`);
data = JSON.parse(manifestAst[1].data);
}, `Unexpected token / in JSON at position 47`);
assert.strictEqual(data, undefined);
});
it('ignores comments inside manifest resource', () => {
const manifestAst = parse(`
import '../Pipes/PipeEntity.schema'
resource PipeEntityResource
start
[{"type": "artist", "name": "in this moment"}]
//[{"type": "tv_show", "name": "star trek"}]
store ExamplePipeEntity of PipeEntity 'ExamplePipeEntity' @0 in PipeEntityResource
`);
assert.lengthOf(manifestAst, 3, 'Incorrectly parsed manifest');
assert.deepEqual(
JSON.stringify(JSON.parse(manifestAst[1].data)),
'[{"type":"artist","name":"in this moment"}]'
);
});
describe('particle expressions', () => {
it('parses identity expression', () => {
parse(`
particle Identity
input: reads Foo {x: Number}
output: writes Foo {x: Number} = input
`);
});
it('parses field lookup expression', () => {
parse(`
particle Unwrap
input: reads Foo {
bar: inline Bar {
x: Number
}
}
output: writes Bar {x: Number} = input.bar
`);
});
it('parses new entity expression', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = new Bar {y: foo.x}
`);
});
it('parses from expression', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in foo.x select p
`);
});
it('parses from expression with nested source', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in (from q in foo.x select q) select p
`);
});
it('parses nested from expression with nested source', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in (from q in blah select q) from q in foo.x select p
`);
});
it('parses from/where expression', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in foo.x where p + 1 < 10 select p
`);
});
it('parses from/select expression', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in foo.x select p + 1
`);
});
it('parses from/select expression with new', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in foo.x where p < 10 select new Bar {y: foo.x}
`);
});
it('parses from/select expression with let with constant', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] =
from f in foo
let y = 10
select new Bar {y: y}
`);
});
it('parses from/select expression with let with expression', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number, y: Number}]
bar: writes [Bar {y: Number}] =
from f in foo
let y = f.x * f.y + 42
select new Bar {y: y}
`);
});
it('parses from/select expression with let with function call', () => {
parse(`
particle Converter
foo: reads [Foo {x: List<Number>}]
bar: writes [Bar {y: Number}] =
from f in foo
let y = first(from x in f.x select x / 2)
select new Bar {y: y}
`);
});
it('parses from/select expression with let with paxel expression', () => {
parse(`
particle Converter
foo: reads [Foo {x: List<Number>}]
bar: writes [Bar {y: Number}] =
from f in foo
let y = (from x in f.x where x > 42 select x / 2)
select new Bar {y: first(y)}
`);
});
it('parses from/select expression with if null operator', () => {
parse(`
particle Converter
foo: reads Foo {x: List<inline X {xnum: Number}>}
bar: writes Bar {y: Number} = new Bar {
y: first(foo.x)?.xnum ?: 42
}
`);
});
it('parses multi-line paxel expression', () => {
parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] =
from p in (
from x in foo.x
where x / 5 > 2
and (
x * x <= 122
or x < -100
)
select x
)
where p < 10
let y = first(
from x in p.x
where x > 42
select x / 2
)
select new Bar {
y: foo.x + y
}
baz: reads Baz {z: Number}
`);
});
it('parses from/select expression with new and scope lookup', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = from p in foo.x where p.y < 10 select new Bar {y: foo.x}
`);
});
it('allows expressions in new entity selection', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = from p in foo.x select new Bar {y: p.num / 2}
`);
});
it('allows paxel expressions in new nested entity selection', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = from p in foo.x select new Bar {y: (from p in foo.z select first(p))/2}
`);
});
it('allows paxel expressions in new entity selection', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = from p in foo.x select new Bar {y: from p in foo.z select first(p)}
`);
});
it('allows function calls as qualifiers', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = from p in foo.x select new Bar {y: first(foo).x}
`);
});
it('parses safe scope lookup', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = new Bar {y: a.b?.c}
`);
});
it('parses safe scope lookup on function calls', () => {
parse(`
particle Converter
foo: reads Foo {x: List<inline Thing{z: Number}>}
bar: writes Bar {y: Number} = new Bar {y: first(foo.x)?.z}
`);
});
it('allows complex qualifiers in where condition', () => {
parse(`
particle Converter
foo: reads Foo {x: Number}
bar: writes Bar {y: Number} = from p in foo.x where first(foo).x < p.y select new Bar {y: foo.x}
`);
});
it('fails expression without starting from', () => {
assert.throws(() => parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = where p < 10 select new Bar {y: foo.x}
`), 'Paxel expressions must begin with \'from\'');
});
it('fails expression without ending select', () => {
assert.throws(() => parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] = from p in foo.x where p < 10
`), 'Paxel expressions must end with \'select\'');
});
it('fails expression with multiple select', () => {
assert.throws(() => parse(`
particle Converter
foo: reads [Foo {x: Number}]
bar: writes [Bar {y: Number}] =
from f in foo
where f.x < 10
select new Bar {y: x}
select new Bar {y: x}
`), 'Paxel expressions cannot have non-trailing \'select\'');
});
});
describe('inline data stores', () => {
// Store AST nodes have an entities field holding an array of objects formatted as:
// { kind: 'entity-inline', location: {...}, fields: {<name>: <descriptor>, ...}
function extractEntities(storeAst) {
return storeAst.entities.map(item => {
assert.strictEqual(item.kind, 'entity-inline');
assert.containsAllKeys(item, ['location', 'fields']);
return item.fields;
});
}
it('parses text fields', () => {
const manifestAst = parse(`
store A of [{txt: Text}] with {
{txt: ''},
{txt: 'test string'},
{txt: '\\'quotes\\''},
{txt: 'more \\\\ escaping \\' here'},
{txt: '\\tabs and \\newlines are translated'},
{txt: '\\other \\chars are\\ n\\ot'},
}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{txt: {kind: 'entity-value', value: ''}},
{txt: {kind: 'entity-value', value: 'test string'}},
{txt: {kind: 'entity-value', value: '\'quotes\''}},
{txt: {kind: 'entity-value', value: 'more \\ escaping \' here'}},
{txt: {kind: 'entity-value', value: '\tabs and \newlines are translated'}},
{txt: {kind: 'entity-value', value: 'other chars are not'}},
]);
});
it('parses url fields', () => {
const manifestAst = parse(`
store A of [{u: URL}] with {
{u: ''}, {u: 'http://www.foo.com/go?q=%27hi?=%25'},
}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{u: {kind: 'entity-value', value: ''}},
{u: {kind: 'entity-value', value: 'http://www.foo.com/go?q=%27hi?=%25'}},
]);
});
it('parses number fields', () => {
const manifestAst = parse(`
store A of [{num: Number}] with {
{num: 0},
{num: 0.8},
{num: 51},
{num: -6},
{num: -120.5}
}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{num: {kind: 'entity-value', value: 0}},
{num: {kind: 'entity-value', value: 0.8}},
{num: {kind: 'entity-value', value: 51}},
{num: {kind: 'entity-value', value: -6}},
{num: {kind: 'entity-value', value: -120.5}},
]);
});
it('parses boolean fields', () => {
const manifestAst = parse(`
store A of [{flg: Boolean}] with { {flg: true}, {flg: false} }
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{flg: {kind: 'entity-value', value: true}},
{flg: {kind: 'entity-value', value: false}},
]);
});
it('parses bytes fields', () => {
const manifestAst = parse(`
store A of [{buf: Bytes}] with {
{buf: ||},
{buf: |0|},
{buf: |23,|},
{buf: |7, ff, 4d|},
{buf: |7, ff, 4d,|},
}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{buf: {kind: 'entity-value', value: new Uint8Array()}},
{buf: {kind: 'entity-value', value: new Uint8Array([0])}},
{buf: {kind: 'entity-value', value: new Uint8Array([0x23])}},
{buf: {kind: 'entity-value', value: new Uint8Array([0x07, 0xff, 0x4d])}},
{buf: {kind: 'entity-value', value: new Uint8Array([0x07, 0xff, 0x4d])}},
]);
});
it('parses reference fields', () => {
const manifestAst = parse(`
store A of {ref: &{z: Text}} with { {ref: <'id1', 'key1'>} }
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{ref: {kind: 'entity-value', value: {id: 'id1', entityStorageKey: 'key1'}}}
]);
});
it('parses collection fields', () => {
const manifestAst = parse(`
store S0 of [{col: [Text]}] with {
{col: []},
{col: ['a', 'b\\'c']},
}
store S1 of [{col: [Number]}] with {
{col: [12]},
{col: [-5, 23.7, 0, ]},
}
store S2 of {col: [Boolean]} with {
{col: [true, true, false]}
}
store S3 of {col: [Bytes]} with {
{col: [|a2|, |0, 50|, ||]}
}
store S4 of {col: [&{n: Number}]} with {
{col: [<'i0', 'k0'>, <'i1', 'k1'>]}
}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{col: {kind: 'entity-collection', value: []}},
{col: {kind: 'entity-collection', value: ['a', 'b\'c']}},
]);
assert.deepStrictEqual(extractEntities(manifestAst[1]), [
{col: {kind: 'entity-collection', value: [12]}},
{col: {kind: 'entity-collection', value: [-5, 23.7, 0]}},
]);
assert.deepStrictEqual(extractEntities(manifestAst[2]), [
{col: {kind: 'entity-collection', value: [true, true, false]}},
]);
assert.deepStrictEqual(extractEntities(manifestAst[3]), [
{col: {kind: 'entity-collection', value: [
new Uint8Array([0xa2]),
new Uint8Array([0, 0x50]),
new Uint8Array(),
]}},
]);
assert.deepStrictEqual(extractEntities(manifestAst[4]), [
{col: {kind: 'entity-collection', value: [
{id: 'i0', entityStorageKey: 'k0'},
{id: 'i1', entityStorageKey: 'k1'},
]}},
]);
});
it('parses tuple fields', () => {
const manifestAst = parse(`
store A of [{t: (Text, Number, Boolean, Bytes)}] with {
{t: ('a\\tb', -7.9, false, |7e, 46,|)},
{t: ('', 0, true, ||)}
}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{t: {kind: 'entity-tuple', value: [
'a\tb', -7.9, false, new Uint8Array([0x7e, 0x46])
]}},
{t: {kind: 'entity-tuple', value: [
'', 0, true, new Uint8Array()
]}},
]);
});
it('parses standard components of store expressions', () => {
const manifestAst = parse(`
store S0 of {n: Number} with { {n: 1} }
store S1 of {t: Text} 'id'!!'orig' @3 #tag with
{
{t: 'a'}
}
description \`inline store\`
claim is foo
`);
assert.deepInclude(manifestAst[0], {
kind: 'store',
name: 'S0',
id: null,
originalId: null,
version: null,
tags: null,
source: 'inline',
origin: 'inline',
storageKey: null,
description: null,
claims: [],
});
delete manifestAst[1].claims[0].location;
assert.deepInclude(manifestAst[1], {
kind: 'store',
name: 'S1',
id: 'id',
originalId: 'orig',
version: '3',
tags: ['tag'],
source: 'inline',
origin: 'inline',
storageKey: null,
description: 'inline store',
claims: [{kind: 'manifest-storage-claim', tags: ['foo'], fieldPath: []}],
});
});
it('parses complex schemas with variable spacing and comments', () => {
const manifestAst = parse(`
store A of [{n: Number, c: [Text], t: (Boolean, Bytes), r: &{z: URL}}] with { // comment
{n:4.5,c:['abc'],t:(true,|0|),r:<'i1','k1'>},
{
n:
0.0,//comment
c: [ '\\'',
'\\t' ,'',] , t: ( FALSE , | 22,
d3 ,
|),
// full line comment
r: < 'i2' ,
'k2' >}}
`);
assert.deepStrictEqual(extractEntities(manifestAst[0]), [
{
n: {kind: 'entity-value', value: 4.5},
c: {kind: 'entity-collection', value: ['abc']},
t: {kind: 'entity-tuple', value: [true, new Uint8Array([0])]},
r: {kind: 'entity-value', value: {id: 'i1', entityStorageKey: 'k1'}},
},
{
n: {kind: 'entity-value', value: 0},
c: {kind: 'entity-collection', value: ['\'', '\t', '']},
t: {kind: 'entity-tuple', value: [false, new Uint8Array([0x22, 0xd3])]},
r: {kind: 'entity-value', value: {id: 'i2', entityStorageKey: 'k2'}},
}
]);
});
it('requires consistent value types for collection fields', () => {
const msg = 'Collection fields for inline entities must have a consistent value type';
assert.throws(() => { parse(`
store A of {txt: [Text]} with { {txt: ['aa', true, 'bb']} }`);
}, msg);
assert.throws(() => { parse(`
store A of {num: [Number]} with { {num: [5, 'x']} }`);
}, msg);
assert.throws(() => { parse(`
store A of {flg: [Boolean]} with { {flg: [true, |83|]} }`);
}, msg);
assert.throws(() => { parse(`
store A of {z: [Bytes]} with { {z: [|5|, |0, aa|, <'id', 'key'>, |4d|]} }`);
}, msg);
});
it('requires the id and storage key to be present in references', () => {
const msg = 'Reference fields for inline entities must have both an id and a storage key';
assert.throws(() => { parse(`
store A of {ref: &{t: Text}} with { {ref: <'', 'key'>} }`);
}, msg);
assert.throws(() => { parse(`
store A of {ref: &{t: Text}} with { {ref: <'id', ''>} }`);
}, msg);
});
});
}); | the_stack |
import bowser from "bowser";
import Database from "../services/Database";
import OneSignalApiShared from "../OneSignalApiShared";
import Environment from "../Environment";
import Event from "../Event";
import Log from "../libraries/Log";
import { ServiceWorkerActiveState } from "../helpers/ServiceWorkerHelper";
import SdkEnvironment from "../managers/SdkEnvironment";
import ProxyFrameHost from "../modules/frames/ProxyFrameHost";
import { NotificationPermission } from "../models/NotificationPermission";
import { RawPushSubscription } from "../models/RawPushSubscription";
import { SubscriptionStateKind } from "../models/SubscriptionStateKind";
import { WindowEnvironmentKind } from "../models/WindowEnvironmentKind";
import { Subscription } from "../models/Subscription";
import { UnsubscriptionStrategy } from "../models/UnsubscriptionStrategy";
import { PushDeviceRecord } from "../models/PushDeviceRecord";
import { SubscriptionStrategyKind } from "../models/SubscriptionStrategyKind";
import { IntegrationKind } from "../models/IntegrationKind";
import { InvalidStateError, InvalidStateReason } from "../errors/InvalidStateError";
import PushPermissionNotGrantedError from "../errors/PushPermissionNotGrantedError";
import { PushPermissionNotGrantedErrorReason } from "../errors/PushPermissionNotGrantedError";
import { SdkInitError, SdkInitErrorKind } from "../errors/SdkInitError";
import SubscriptionError from "../errors/SubscriptionError";
import { SubscriptionErrorReason } from "../errors/SubscriptionError";
import ServiceWorkerRegistrationError from "../errors/ServiceWorkerRegistrationError";
import NotImplementedError from "../errors/NotImplementedError";
import { PermissionUtils } from "../utils/PermissionUtils";
import { base64ToUint8Array } from "../utils/Encoding";
import { ContextSWInterface } from '../models/ContextSW';
export interface SubscriptionManagerConfig {
safariWebId?: string;
appId: string;
/**
* The VAPID public key to use for Chrome-like browsers, including Opera and Yandex browser.
*/
vapidPublicKey: string;
/**
* A globally shared VAPID public key to use for the Firefox browser, which does not use VAPID for authentication but for application identification and uses a single
*/
onesignalVapidPublicKey: string;
}
export type SubscriptionStateServiceWorkerNotIntalled =
SubscriptionStateKind.ServiceWorkerStatus403 |
SubscriptionStateKind.ServiceWorkerStatus404;
export class SubscriptionManager {
private context: ContextSWInterface;
private config: SubscriptionManagerConfig;
constructor(context: ContextSWInterface, config: SubscriptionManagerConfig) {
this.context = context;
this.config = config;
}
static isSafari(): boolean {
return Environment.isSafari();
}
/**
* Subscribes for a web push subscription.
*
* This method is aware of different subscription environments like subscribing from a webpage,
* service worker, or OneSignal HTTP popup and will select the correct method. This is intended to
* be the single public API for obtaining a raw web push subscription (i.e. what the browser
* returns from a successful subscription).
*/
public async subscribe(subscriptionStrategy: SubscriptionStrategyKind): Promise<RawPushSubscription> {
const env = SdkEnvironment.getWindowEnv();
switch (env) {
case WindowEnvironmentKind.CustomIframe:
case WindowEnvironmentKind.Unknown:
case WindowEnvironmentKind.OneSignalProxyFrame:
throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);
}
let rawPushSubscription: RawPushSubscription;
switch (env) {
case WindowEnvironmentKind.ServiceWorker:
rawPushSubscription = await this.subscribeFcmFromWorker(subscriptionStrategy);
break;
case WindowEnvironmentKind.Host:
case WindowEnvironmentKind.OneSignalSubscriptionModal:
case WindowEnvironmentKind.OneSignalSubscriptionPopup:
/*
Check our notification permission before subscribing.
- If notifications are blocked, we can't subscribe.
- If notifications are granted, the user should be completely resubscribed.
- If notifications permissions are untouched, the user will be prompted and then
subscribed.
Subscribing is only possible on the top-level frame, so there's no permission ambiguity
here.
*/
if ((await OneSignal.privateGetNotificationPermission()) === NotificationPermission.Denied)
throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Blocked);
if (SubscriptionManager.isSafari()) {
rawPushSubscription = await this.subscribeSafari();
/* Now that permissions have been granted, install the service worker */
Log.info("Installing SW on Safari");
try {
await this.context.serviceWorkerManager.installWorker();
Log.info("SW on Safari successfully installed");
} catch(e) {
Log.error("SW on Safari failed to install.");
}
} else {
rawPushSubscription = await this.subscribeFcmFromPage(subscriptionStrategy);
}
break;
default:
throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);
}
return rawPushSubscription;
}
/**
* Creates a device record from the provided raw push subscription and forwards this device record
* to OneSignal to create or update the device ID.
*
* @param rawPushSubscription The raw push subscription obtained from calling subscribe(). This
* can be null, in which case OneSignal's device record is set to unsubscribed.
*
* @param subscriptionState Describes whether the device record is subscribed, unsubscribed, or in
* another state. By default, this is set from the availability of rawPushSubscription (exists:
* Subscribed, null: Unsubscribed). Other use cases may result in creation of a device record that
* warrants a special subscription state. For example, a device ID can be retrieved by providing
* an identifier, and a new device record will be created if the identifier didn't exist. These
* records are marked with a special subscription state for tracking purposes.
*/
public async registerSubscription(
pushSubscription: RawPushSubscription,
subscriptionState?: SubscriptionStateKind,
): Promise<Subscription> {
/*
This may be called after the RawPushSubscription has been serialized across a postMessage
frame. This means it will only have object properties and none of the functions. We have to
recreate the RawPushSubscription.
Keep in mind pushSubscription can be null in cases where resubscription isn't possible
(blocked permission).
*/
if (pushSubscription) {
pushSubscription = RawPushSubscription.deserialize(pushSubscription);
}
const deviceRecord: PushDeviceRecord = PushDeviceRecord.createFromPushSubscription(
this.config.appId,
pushSubscription,
subscriptionState
);
let newDeviceId: string | undefined = undefined;
if (await this.isAlreadyRegisteredWithOneSignal()) {
await this.context.updateManager.sendPushDeviceRecordUpdate(deviceRecord);
} else {
newDeviceId = await this.context.updateManager.sendPlayerCreate(deviceRecord);
if (newDeviceId) {
await this.associateSubscriptionWithEmail(newDeviceId);
}
}
const subscription = await Database.getSubscription();
subscription.deviceId = newDeviceId;
subscription.optedOut = false;
if (pushSubscription) {
if (SubscriptionManager.isSafari()) {
subscription.subscriptionToken = pushSubscription.safariDeviceToken;
} else {
subscription.subscriptionToken = pushSubscription.w3cEndpoint ? pushSubscription.w3cEndpoint.toString() : null;
}
} else {
subscription.subscriptionToken = null;
}
await Database.setSubscription(subscription);
if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker) {
Event.trigger(OneSignal.EVENTS.REGISTERED);
}
if (typeof OneSignal !== "undefined") {
OneSignal._sessionInitAlreadyRunning = false;
}
return subscription;
}
/**
* Used before subscribing for push, we request notification permissions
* before installing the service worker to prevent non-subscribers from
* querying our server for an updated service worker every 24 hours.
*/
private static async requestPresubscribeNotificationPermission(): Promise<NotificationPermission> {
return await SubscriptionManager.requestNotificationPermission();
}
public async unsubscribe(strategy: UnsubscriptionStrategy) {
if (strategy === UnsubscriptionStrategy.DestroySubscription) {
throw new NotImplementedError();
} else if (strategy === UnsubscriptionStrategy.MarkUnsubscribed) {
if (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.ServiceWorker) {
const { deviceId } = await Database.getSubscription();
await OneSignalApiShared.updatePlayer(this.context.appConfig.appId, deviceId, {
notification_types: SubscriptionStateKind.MutedByApi
});
await Database.put('Options', { key: 'optedOut', value: true });
} else {
throw new NotImplementedError();
}
} else {
throw new NotImplementedError();
}
}
/**
* Calls Notification.requestPermission(), but returns a Promise instead of
* accepting a callback like the actual Notification.requestPermission();
*
* window.Notification.requestPermission: The callback was deprecated since Gecko 46 in favor of a Promise
*/
public static async requestNotificationPermission(): Promise<NotificationPermission> {
const results = await window.Notification.requestPermission();
// TODO: Clean up our custom NotificationPermission enum
// in favor of TS union type NotificationPermission instead of converting
return NotificationPermission[results];
}
/**
* Called after registering a subscription with OneSignal to associate this subscription with an
* email record if one exists.
*/
public async associateSubscriptionWithEmail(newDeviceId: string) {
const emailProfile = await Database.getEmailProfile();
if (!emailProfile.subscriptionId) {
return;
}
// Update the push device record with a reference to the new email ID and email address
await OneSignalApiShared.updatePlayer(
this.config.appId,
newDeviceId,
{
parent_player_id: emailProfile.subscriptionId,
email: emailProfile.identifier
}
);
}
public async isAlreadyRegisteredWithOneSignal(): Promise<boolean> {
const { deviceId } = await Database.getSubscription();
return !!deviceId;
}
private subscribeSafariPromptPermission(): Promise<string | null> {
return new Promise<string>(resolve => {
window.safari.pushNotification.requestPermission(
`${SdkEnvironment.getOneSignalApiUrl().toString()}/safari`,
this.config.safariWebId,
{
app_id: this.config.appId
},
response => {
if ((response as any).deviceToken) {
resolve((response as any).deviceToken.toLowerCase());
} else {
resolve(null);
}
}
);
});
}
private async subscribeSafari(): Promise<RawPushSubscription> {
const pushSubscriptionDetails = new RawPushSubscription();
if (!this.config.safariWebId) {
throw new SdkInitError(SdkInitErrorKind.MissingSafariWebId);
}
const { deviceToken: existingDeviceToken } = window.safari.pushNotification.permission(this.config.safariWebId);
pushSubscriptionDetails.existingSafariDeviceToken = existingDeviceToken;
if (!existingDeviceToken) {
/*
We're about to show the Safari native permission request. It can fail for a number of
reasons, e.g.:
- Setup-related reasons when developers just starting to get set up
- Address bar URL doesn't match safari certificate allowed origins (case-sensitive)
- Safari web ID doesn't match provided web ID
- Browsing in a Safari private window
- Bad icon DPI
but shouldn't fail for sites that have already gotten Safari working.
We'll show the permissionPromptDisplay event if the Safari user isn't already subscribed,
otherwise an already subscribed Safari user would not see the permission request again.
*/
Event.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);
}
const deviceToken = await this.subscribeSafariPromptPermission();
PermissionUtils.triggerNotificationPermissionChanged();
if (deviceToken) {
pushSubscriptionDetails.setFromSafariSubscription(deviceToken);
} else {
throw new SubscriptionError(SubscriptionErrorReason.InvalidSafariSetup);
}
return pushSubscriptionDetails;
}
private async subscribeFcmFromPage(
subscriptionStrategy: SubscriptionStrategyKind
): Promise<RawPushSubscription> {
/*
Before installing the service worker, request notification permissions. If
the visitor doesn't grant permissions, this saves bandwidth bleeding from
an unused install service worker periodically fetching an updated version
from our CDN.
*/
/*
Trigger the permissionPromptDisplay event to the best of our knowledge.
*/
if (
SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker &&
Notification.permission === NotificationPermission.Default
) {
await Event.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);
const permission = await SubscriptionManager.requestPresubscribeNotificationPermission();
/*
Notification permission changes are already broadcast by the page's
notificationpermissionchange handler. This means that allowing or
denying the permission prompt will cause double events. However, the
native event handler does not broadcast an event for dismissing the
prompt, because going from "default" permissions to "default"
permissions isn't a change. We specifically broadcast "default" to "default" changes.
*/
if (permission === NotificationPermission.Default)
await PermissionUtils.triggerNotificationPermissionChanged(true);
// If the user did not grant push permissions, throw and exit
switch (permission) {
case NotificationPermission.Default:
Log.debug('Exiting subscription and not registering worker because the permission was dismissed.');
OneSignal._sessionInitAlreadyRunning = false;
OneSignal._isRegisteringForPush = false;
throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Dismissed);
case NotificationPermission.Denied:
Log.debug('Exiting subscription and not registering worker because the permission was blocked.');
OneSignal._sessionInitAlreadyRunning = false;
OneSignal._isRegisteringForPush = false;
throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Blocked);
}
}
/* Now that permissions have been granted, install the service worker */
try {
await this.context.serviceWorkerManager.installWorker();
} catch(err) {
if (err instanceof ServiceWorkerRegistrationError) {
if (err.status === 403) {
await this.context.subscriptionManager.registerFailedSubscription(
SubscriptionStateKind.ServiceWorkerStatus403,
this.context);
} else if (err.status === 404) {
await this.context.subscriptionManager.registerFailedSubscription(
SubscriptionStateKind.ServiceWorkerStatus404,
this.context);
}
}
throw err;
}
Log.debug('[Subscription Manager] Getting OneSignal service Worker...');
const workerRegistration = await this.context.serviceWorkerManager.getRegistration();
if (!workerRegistration) {
throw new Error("OneSignal service worker not found!");
}
Log.debug('[Subscription Manager] Service worker is ready to continue subscribing.');
return await this.subscribeWithVapidKey(workerRegistration.pushManager, subscriptionStrategy);
}
public async subscribeFcmFromWorker(
subscriptionStrategy: SubscriptionStrategyKind
): Promise<RawPushSubscription> {
/*
We're running inside of the service worker.
Check to make sure our registration is activated, otherwise we can't
subscribe for push.
HACK: Firefox doesn't set self.registration.active in the service worker
context. From a non-service worker context, like
navigator.serviceWorker.getRegistration().active, the property actually is
set, but it's just not set within the service worker context.
Because of this, we're not able to check for this property on Firefox.
*/
const swRegistration = (<ServiceWorkerGlobalScope><any>self).registration;
if (!swRegistration.active && !bowser.firefox) {
throw new InvalidStateError(InvalidStateReason.ServiceWorkerNotActivated);
/*
Or should we wait for the service worker to be ready?
await new Promise(resolve => self.onactivate = resolve);
*/
}
/*
Check to make sure push permissions have been granted.
*/
const pushPermission = await swRegistration.pushManager.permissionState({ userVisibleOnly: true });
if (pushPermission === 'denied') {
throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Blocked);
} else if (pushPermission === 'prompt') {
throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Default);
}
return await this.subscribeWithVapidKey(swRegistration.pushManager, subscriptionStrategy);
}
/**
* Returns the correct VAPID key to use for subscription based on the browser type.
*
* If the VAPID key isn't present, undefined is returned instead of null.
*/
public getVapidKeyForBrowser(): ArrayBuffer | undefined {
// Specifically return undefined instead of null if the key isn't available
let key = undefined;
if (bowser.firefox) {
/*
Firefox uses VAPID for application identification instead of
authentication, and so all apps share an identification key.
*/
key = this.config.onesignalVapidPublicKey;
} else {
/*
Chrome and Chrome-like browsers including Opera and Yandex use VAPID for
authentication, and so each app uses a uniquely generated key.
*/
key = this.config.vapidPublicKey;
}
if (key) {
return <ArrayBuffer>base64ToUint8Array(key).buffer;
} else {
return undefined;
}
}
/**
* Uses the browser's PushManager interface to actually subscribe for a web push subscription.
*
* @param pushManager An instance of the browser's push manager, either from the page or from the
* service worker.
*
* @param subscriptionStrategy Given an existing push subscription, describes whether the existing
* push subscription is resubscribed as-is leaving it unchanged, or unsubscribed to make room for
* a new push subscription.
*/
public async subscribeWithVapidKey(
pushManager: PushManager,
subscriptionStrategy: SubscriptionStrategyKind
): Promise<RawPushSubscription> {
/*
Always try subscribing using VAPID by providing an applicationServerKey, except for cases
where the user is already subscribed, handled below.
*/
const existingPushSubscription = await pushManager.getSubscription();
/* Depending on the subscription strategy, handle existing subscription in various ways */
switch (subscriptionStrategy) {
case SubscriptionStrategyKind.ResubscribeExisting:
if (!existingPushSubscription)
break;
if (existingPushSubscription.options) {
Log.debug("[Subscription Manager] An existing push subscription exists and it's options is not null.");
}
else {
Log.debug('[Subscription Manager] An existing push subscription exists and options is null. ' +
'Unsubscribing from push first now.');
/*
NOTE: Only applies to rare edge case of migrating from senderId to a VAPID subscription
There isn't a great solution if PushSubscriptionOptions (supported on Chrome 54+) isn't
supported.
We want to subscribe the user, but we don't know whether the user was subscribed via
GCM's manifest.json or FCM's VAPID.
This bug (https://bugs.chromium.org/p/chromium/issues/detail?id=692577) shows that a
mismatched sender ID error is possible if you subscribe via FCM's VAPID while the user
was originally subscribed via GCM's manifest.json (fails silently).
Because of this, we should unsubscribe the user from push first and then resubscribe
them.
*/
/* We're unsubscribing, so we want to store the created at timestamp */
await SubscriptionManager.doPushUnsubscribe(existingPushSubscription);
}
break;
case SubscriptionStrategyKind.SubscribeNew:
/* Since we want a new subscription every time with this strategy, just unsubscribe. */
if (existingPushSubscription) {
await SubscriptionManager.doPushUnsubscribe(existingPushSubscription);
}
break;
}
// Actually subscribe the user to push
const [newPushSubscription, isNewSubscription] =
await SubscriptionManager.doPushSubscribe(pushManager, this.getVapidKeyForBrowser());
// Update saved create and expired times
await SubscriptionManager.updateSubscriptionTime(isNewSubscription, newPushSubscription.expirationTime);
// Create our own custom object from the browser's native PushSubscription object
const pushSubscriptionDetails = RawPushSubscription.setFromW3cSubscription(newPushSubscription);
if (existingPushSubscription) {
pushSubscriptionDetails.existingW3cPushSubscription =
RawPushSubscription.setFromW3cSubscription(existingPushSubscription);
}
return pushSubscriptionDetails;
}
private static async updateSubscriptionTime(updateCreatedAt: boolean, expirationTime: number | null): Promise<void> {
const bundle = await Database.getSubscription();
if (updateCreatedAt) {
bundle.createdAt = new Date().getTime();
}
bundle.expirationTime = expirationTime;
await Database.setSubscription(bundle);
}
private static async doPushUnsubscribe(pushSubscription: PushSubscription): Promise<boolean> {
Log.debug('[Subscription Manager] Unsubscribing existing push subscription.');
const result = await pushSubscription.unsubscribe();
Log.debug(`[Subscription Manager] Unsubscribing existing push subscription result: ${result}`);
return result;
}
// Subscribes the ServiceWorker for a pushToken.
// If there is an error doing so unsubscribe from existing and try again
// - This handles subscribing to new server VAPID key if it has changed.
// return type - [PushSubscription, createdNewPushSubscription(boolean)]
private static async doPushSubscribe(
pushManager: PushManager,
applicationServerKey: ArrayBuffer | undefined)
:Promise<[PushSubscription, boolean]> {
if (!applicationServerKey) {
throw new Error("Missing required 'applicationServerKey' to subscribe for push notifications!");
}
const subscriptionOptions: PushSubscriptionOptionsInit = {
userVisibleOnly: true,
applicationServerKey: applicationServerKey
};
Log.debug('[Subscription Manager] Subscribing to web push with these options:', subscriptionOptions);
try {
const existingSubscription = await pushManager.getSubscription();
return [await pushManager.subscribe(subscriptionOptions), !existingSubscription];
} catch (e) {
if (e.name == "InvalidStateError") {
// This exception is thrown if the key for the existing applicationServerKey is different,
// so we must unregister first.
// In Chrome, e.message contains will be the following in this case for reference;
// Registration failed - A subscription with a different applicationServerKey (or gcm_sender_id) already exists;
// to change the applicationServerKey, unsubscribe then resubscribe.
Log.warn("[Subscription Manager] Couldn't re-subscribe due to applicationServerKey changing, " +
"unsubscribe and attempting to subscribe with new key.", e);
const subscription = await pushManager.getSubscription();
if (subscription) {
await SubscriptionManager.doPushUnsubscribe(subscription);
}
return [await pushManager.subscribe(subscriptionOptions), true];
}
else
throw e; // If some other error, bubble the exception up
}
}
public async isSubscriptionExpiring(): Promise<boolean> {
const integrationKind = await SdkEnvironment.getIntegration();
const windowEnv = SdkEnvironment.getWindowEnv();
switch (integrationKind) {
case IntegrationKind.Secure:
return await this.isSubscriptionExpiringForSecureIntegration();
case IntegrationKind.SecureProxy:
if (windowEnv === WindowEnvironmentKind.Host) {
const proxyFrameHost: ProxyFrameHost = OneSignal.proxyFrameHost;
if (!proxyFrameHost) {
throw new InvalidStateError(InvalidStateReason.NoProxyFrame);
} else {
return await proxyFrameHost.runCommand<boolean>(
OneSignal.POSTMAM_COMMANDS.SUBSCRIPTION_EXPIRATION_STATE
);
}
} else {
return await this.isSubscriptionExpiringForSecureIntegration();
}
case IntegrationKind.InsecureProxy:
/* If we're in an insecure frame context, check the stored expiration since we can't access
the actual push subscription. */
const { expirationTime } = await Database.getSubscription();
if (!expirationTime) {
/* If an existing subscription does not have a stored expiration time, do not
treat it as expired. The subscription may have been created before this feature was added,
or the browser may not assign any expiration time. */
return false;
}
/* The current time (in UTC) is past the expiration time (also in UTC) */
return new Date().getTime() >= expirationTime;
}
}
private async isSubscriptionExpiringForSecureIntegration(): Promise<boolean> {
const serviceWorkerState = await this.context.serviceWorkerManager.getActiveState();
if (!(
serviceWorkerState === ServiceWorkerActiveState.WorkerA ||
serviceWorkerState === ServiceWorkerActiveState.WorkerB)) {
/* If the service worker isn't activated, there's no subscription to look for */
return false;
}
const serviceWorkerRegistration = await this.context.serviceWorkerManager.getRegistration();
if (!serviceWorkerRegistration)
return false;
// It's possible to get here in Safari 11.1+ version
// since they released support for service workers but not push api.
if (!serviceWorkerRegistration.pushManager)
return false;
const pushSubscription = await serviceWorkerRegistration.pushManager.getSubscription();
// Not subscribed to web push
if (!pushSubscription)
return false;
// No push subscription expiration time
if (!pushSubscription.expirationTime)
return false;
let { createdAt: subscriptionCreatedAt } = await Database.getSubscription();
if (!subscriptionCreatedAt) {
/* If we don't have a record of when the subscription was created, set it into the future to
guarantee expiration and obtain a new subscription */
const ONE_YEAR = 1000 * 60 * 60 * 24 * 365;
subscriptionCreatedAt = new Date().getTime() + ONE_YEAR;
}
const midpointExpirationTime =
subscriptionCreatedAt + ((pushSubscription.expirationTime - subscriptionCreatedAt) / 2);
return !!pushSubscription.expirationTime && (
/* The current time (in UTC) is past the expiration time (also in UTC) */
new Date().getTime() >= pushSubscription.expirationTime ||
new Date().getTime() >= midpointExpirationTime
);
}
/**
* Returns an object describing the user's actual push subscription state and opt-out status.
*/
public async getSubscriptionState(): Promise<PushSubscriptionState> {
/* Safari should always return Secure because HTTP doesn't apply on Safari */
if (SubscriptionManager.isSafari()) {
return this.getSubscriptionStateForSecure();
}
const windowEnv = SdkEnvironment.getWindowEnv();
switch (windowEnv) {
case WindowEnvironmentKind.ServiceWorker:
const pushSubscription = await (<ServiceWorkerGlobalScope><any>self).registration.pushManager.getSubscription();
const { optedOut } = await Database.getSubscription();
return {
subscribed: !!pushSubscription,
optedOut: !!optedOut
};
default:
/* Regular browser window environments */
const integration = await SdkEnvironment.getIntegration();
switch (integration) {
case IntegrationKind.Secure:
return this.getSubscriptionStateForSecure();
case IntegrationKind.SecureProxy:
switch (windowEnv) {
case WindowEnvironmentKind.OneSignalProxyFrame:
case WindowEnvironmentKind.OneSignalSubscriptionPopup:
case WindowEnvironmentKind.OneSignalSubscriptionModal:
return this.getSubscriptionStateForSecure();
default:
/* Re-run this command in the proxy frame */
const proxyFrameHost: ProxyFrameHost = OneSignal.proxyFrameHost;
const pushSubscriptionState = await proxyFrameHost.runCommand<PushSubscriptionState>(
OneSignal.POSTMAM_COMMANDS.GET_SUBSCRIPTION_STATE
);
return pushSubscriptionState;
}
case IntegrationKind.InsecureProxy:
return await this.getSubscriptionStateForInsecure();
default:
throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);
}
}
}
private async getSubscriptionStateForSecure(): Promise<PushSubscriptionState> {
const { deviceId, optedOut } = await Database.getSubscription();
if (SubscriptionManager.isSafari()) {
const subscriptionState: SafariRemoteNotificationPermission =
window.safari.pushNotification.permission(this.config.safariWebId);
const isSubscribedToSafari = !!(
subscriptionState.permission === "granted" &&
subscriptionState.deviceToken &&
deviceId
);
return {
subscribed: isSubscribedToSafari,
optedOut: !!optedOut,
};
}
const workerState = await this.context.serviceWorkerManager.getActiveState();
const workerRegistration = await this.context.serviceWorkerManager.getRegistration();
const notificationPermission =
await this.context.permissionManager.getNotificationPermission(this.context.appConfig.safariWebId);
const isWorkerActive = (
workerState === ServiceWorkerActiveState.WorkerA ||
workerState === ServiceWorkerActiveState.WorkerB
);
if (!workerRegistration) {
/* You can't be subscribed without a service worker registration */
return {
subscribed: false,
optedOut: !!optedOut,
};
}
/*
* Removing pushSubscription from this method due to inconsistent behavior between browsers.
* Doesn't matter for re-subscribing, worker is present and active.
* Previous implementation for reference:
* const pushSubscription = await workerRegistration.pushManager.getSubscription();
* const isPushEnabled = !!(
* pushSubscription &&
* deviceId &&
* notificationPermission === NotificationPermission.Granted &&
* isWorkerActive
* );
*/
const isPushEnabled = !!(
deviceId &&
notificationPermission === NotificationPermission.Granted &&
isWorkerActive
);
return {
subscribed: isPushEnabled,
optedOut: !!optedOut,
};
}
private async getSubscriptionStateForInsecure(): Promise<PushSubscriptionState> {
/* For HTTP, we need to rely on stored values; we never have access to the actual data */
const { deviceId, subscriptionToken, optedOut } = await Database.getSubscription();
const notificationPermission =
await this.context.permissionManager.getNotificationPermission(this.context.appConfig.safariWebId);
const isPushEnabled = !!(
deviceId &&
subscriptionToken &&
notificationPermission === NotificationPermission.Granted
);
return {
subscribed: isPushEnabled,
optedOut: !!optedOut,
};
}
/**
* Broadcasting to the server the fact user tried to subscribe but there was an error during service worker registration.
* Do it only once for the first page view.
* @param subscriptionState Describes what went wrong with the service worker installation.
*/
public async registerFailedSubscription(
subscriptionState: SubscriptionStateServiceWorkerNotIntalled,
context: ContextSWInterface) {
if (context.pageViewManager.isFirstPageView()) {
context.subscriptionManager.registerSubscription(new RawPushSubscription(), subscriptionState);
context.pageViewManager.incrementPageViewCount();
}
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Configures the specified Policy Definition at the specified Scope. Also, Policy Set Definitions are supported.
*
* !> **Note:** The `azure.policy.Assignment` resource has been deprecated in favour of the `azure.management.GroupPolicyAssignment`, `azure.core.ResourcePolicyAssignment`, `azure.core.ResourceGroupPolicyAssignment` and `azure.core.SubscriptionPolicyAssignment` resources and will be removed in v3.0 of the Azure Provider.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleDefinition = new azure.policy.Definition("exampleDefinition", {
* policyType: "Custom",
* mode: "All",
* displayName: "my-policy-definition",
* policyRule: ` {
* "if": {
* "not": {
* "field": "location",
* "in": "[parameters('allowedLocations')]"
* }
* },
* "then": {
* "effect": "audit"
* }
* }
* `,
* parameters: ` {
* "allowedLocations": {
* "type": "Array",
* "metadata": {
* "description": "The list of allowed locations for resources.",
* "displayName": "Allowed locations",
* "strongType": "location"
* }
* }
* }
* `,
* });
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAssignment = new azure.policy.Assignment("exampleAssignment", {
* scope: exampleResourceGroup.id,
* policyDefinitionId: exampleDefinition.id,
* description: "Policy Assignment created via an Acceptance Test",
* displayName: "My Example Policy Assignment",
* metadata: ` {
* "category": "General"
* }
* `,
* parameters: `{
* "allowedLocations": {
* "value": [ "West Europe" ]
* }
* }
* `,
* });
* ```
*
* ## Import
*
* Policy Assignments can be imported using the `policy name`, e.g.
*
* ```sh
* $ pulumi import azure:policy/assignment:Assignment assignment1 /subscriptions/00000000-0000-0000-000000000000/providers/Microsoft.Authorization/policyAssignments/assignment1
* ```
*/
export class Assignment extends pulumi.CustomResource {
/**
* Get an existing Assignment 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?: AssignmentState, opts?: pulumi.CustomResourceOptions): Assignment {
return new Assignment(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:policy/assignment:Assignment';
/**
* Returns true if the given object is an instance of Assignment. 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 Assignment {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Assignment.__pulumiType;
}
/**
* A description to use for this Policy Assignment. Changing this forces a new resource to be created.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* A friendly display name to use for this Policy Assignment. Changing this forces a new resource to be created.
*/
public readonly displayName!: pulumi.Output<string | undefined>;
/**
* Can be set to 'true' or 'false' to control whether the assignment is enforced (true) or not (false). Default is 'true'.
*/
public readonly enforcementMode!: pulumi.Output<boolean | undefined>;
/**
* An `identity` block as defined below.
*/
public readonly identity!: pulumi.Output<outputs.policy.AssignmentIdentity>;
/**
* The Azure location where this policy assignment should exist. This is required when an Identity is assigned. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* The metadata for the policy assignment. This is a JSON string representing additional metadata that should be stored with the policy assignment.
*/
public readonly metadata!: pulumi.Output<string>;
/**
* The name of the Policy Assignment. Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* A list of the Policy Assignment's excluded scopes. The list must contain Resource IDs (such as Subscriptions e.g. `/subscriptions/00000000-0000-0000-000000000000` or Resource Groups e.g.`/subscriptions/00000000-0000-0000-000000000000/resourceGroups/myResourceGroup`).
*/
public readonly notScopes!: pulumi.Output<string[] | undefined>;
/**
* Parameters for the policy definition. This field is a JSON string that maps to the Parameters field from the Policy Definition. Changing this forces a new resource to be created.
*/
public readonly parameters!: pulumi.Output<string | undefined>;
/**
* The ID of the Policy Definition to be applied at the specified Scope.
*/
public readonly policyDefinitionId!: pulumi.Output<string>;
/**
* The Scope at which the Policy Assignment should be applied, which must be a Resource ID (such as Subscription e.g. `/subscriptions/00000000-0000-0000-000000000000` or a Resource Group e.g.`/subscriptions/00000000-0000-0000-000000000000/resourceGroups/myResourceGroup`). Changing this forces a new resource to be created.
*/
public readonly scope!: pulumi.Output<string>;
/**
* Create a Assignment 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: AssignmentArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: AssignmentArgs | AssignmentState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as AssignmentState | undefined;
inputs["description"] = state ? state.description : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["enforcementMode"] = state ? state.enforcementMode : undefined;
inputs["identity"] = state ? state.identity : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["metadata"] = state ? state.metadata : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["notScopes"] = state ? state.notScopes : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["policyDefinitionId"] = state ? state.policyDefinitionId : undefined;
inputs["scope"] = state ? state.scope : undefined;
} else {
const args = argsOrState as AssignmentArgs | undefined;
if ((!args || args.policyDefinitionId === undefined) && !opts.urn) {
throw new Error("Missing required property 'policyDefinitionId'");
}
if ((!args || args.scope === undefined) && !opts.urn) {
throw new Error("Missing required property 'scope'");
}
inputs["description"] = args ? args.description : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["enforcementMode"] = args ? args.enforcementMode : undefined;
inputs["identity"] = args ? args.identity : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["metadata"] = args ? args.metadata : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["notScopes"] = args ? args.notScopes : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["policyDefinitionId"] = args ? args.policyDefinitionId : undefined;
inputs["scope"] = args ? args.scope : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Assignment.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Assignment resources.
*/
export interface AssignmentState {
/**
* A description to use for this Policy Assignment. Changing this forces a new resource to be created.
*/
description?: pulumi.Input<string>;
/**
* A friendly display name to use for this Policy Assignment. Changing this forces a new resource to be created.
*/
displayName?: pulumi.Input<string>;
/**
* Can be set to 'true' or 'false' to control whether the assignment is enforced (true) or not (false). Default is 'true'.
*/
enforcementMode?: pulumi.Input<boolean>;
/**
* An `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.policy.AssignmentIdentity>;
/**
* The Azure location where this policy assignment should exist. This is required when an Identity is assigned. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* The metadata for the policy assignment. This is a JSON string representing additional metadata that should be stored with the policy assignment.
*/
metadata?: pulumi.Input<string>;
/**
* The name of the Policy Assignment. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A list of the Policy Assignment's excluded scopes. The list must contain Resource IDs (such as Subscriptions e.g. `/subscriptions/00000000-0000-0000-000000000000` or Resource Groups e.g.`/subscriptions/00000000-0000-0000-000000000000/resourceGroups/myResourceGroup`).
*/
notScopes?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Parameters for the policy definition. This field is a JSON string that maps to the Parameters field from the Policy Definition. Changing this forces a new resource to be created.
*/
parameters?: pulumi.Input<string>;
/**
* The ID of the Policy Definition to be applied at the specified Scope.
*/
policyDefinitionId?: pulumi.Input<string>;
/**
* The Scope at which the Policy Assignment should be applied, which must be a Resource ID (such as Subscription e.g. `/subscriptions/00000000-0000-0000-000000000000` or a Resource Group e.g.`/subscriptions/00000000-0000-0000-000000000000/resourceGroups/myResourceGroup`). Changing this forces a new resource to be created.
*/
scope?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Assignment resource.
*/
export interface AssignmentArgs {
/**
* A description to use for this Policy Assignment. Changing this forces a new resource to be created.
*/
description?: pulumi.Input<string>;
/**
* A friendly display name to use for this Policy Assignment. Changing this forces a new resource to be created.
*/
displayName?: pulumi.Input<string>;
/**
* Can be set to 'true' or 'false' to control whether the assignment is enforced (true) or not (false). Default is 'true'.
*/
enforcementMode?: pulumi.Input<boolean>;
/**
* An `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.policy.AssignmentIdentity>;
/**
* The Azure location where this policy assignment should exist. This is required when an Identity is assigned. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* The metadata for the policy assignment. This is a JSON string representing additional metadata that should be stored with the policy assignment.
*/
metadata?: pulumi.Input<string>;
/**
* The name of the Policy Assignment. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A list of the Policy Assignment's excluded scopes. The list must contain Resource IDs (such as Subscriptions e.g. `/subscriptions/00000000-0000-0000-000000000000` or Resource Groups e.g.`/subscriptions/00000000-0000-0000-000000000000/resourceGroups/myResourceGroup`).
*/
notScopes?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Parameters for the policy definition. This field is a JSON string that maps to the Parameters field from the Policy Definition. Changing this forces a new resource to be created.
*/
parameters?: pulumi.Input<string>;
/**
* The ID of the Policy Definition to be applied at the specified Scope.
*/
policyDefinitionId: pulumi.Input<string>;
/**
* The Scope at which the Policy Assignment should be applied, which must be a Resource ID (such as Subscription e.g. `/subscriptions/00000000-0000-0000-000000000000` or a Resource Group e.g.`/subscriptions/00000000-0000-0000-000000000000/resourceGroups/myResourceGroup`). Changing this forces a new resource to be created.
*/
scope: pulumi.Input<string>;
} | the_stack |
import {
Component,
ElementRef,
EventEmitter,
Input,
NgZone,
OnInit,
Output,
ViewChild,
} from '@angular/core';
import { JsplumbBridge } from '../../services/jsplumb-bridge.service';
import { PipelinePositioningService } from '../../services/pipeline-positioning.service';
import { PipelineValidationService } from '../../services/pipeline-validation.service';
import { JsplumbService } from '../../services/jsplumb.service';
import { ShepherdService } from '../../../services/tour/shepherd.service';
import { PipelineElementConfig, PipelineElementUnion } from '../../model/editor.model';
import { ObjectProvider } from '../../services/object-provider.service';
import { PanelType } from '../../../core-ui/dialog/base-dialog/base-dialog.model';
import { SavePipelineComponent } from '../../dialog/save-pipeline/save-pipeline.component';
import { DialogService } from '../../../core-ui/dialog/base-dialog/base-dialog.service';
import { ConfirmDialogComponent } from '../../../core-ui/dialog/confirm-dialog/confirm-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { EditorService } from '../../services/editor.service';
import { PipelineService } from '../../../platform-services/apis/pipeline.service';
import { JsplumbFactoryService } from '../../services/jsplumb-factory.service';
import Panzoom, { PanzoomObject } from '@panzoom/panzoom';
import { PipelineElementDraggedService } from '../../services/pipeline-element-dragged.service';
import { PipelineComponent } from '../pipeline/pipeline.component';
import { PipelineCanvasMetadata } from '../../../core-model/gen/streampipes-model';
import { forkJoin } from 'rxjs';
import { PipelineCanvasMetadataService } from '../../../platform-services/apis/pipeline-canvas-metadata.service';
import { PipelineElementDiscoveryComponent } from '../../dialog/pipeline-element-discovery/pipeline-element-discovery.component';
@Component({
selector: 'pipeline-assembly',
templateUrl: './pipeline-assembly.component.html',
styleUrls: ['./pipeline-assembly.component.scss']
})
export class PipelineAssemblyComponent implements OnInit {
@Input()
rawPipelineModel: PipelineElementConfig[];
@Input()
currentModifiedPipelineId: any;
@Input()
allElements: PipelineElementUnion[];
@Output()
pipelineCanvasMaximizedEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();
JsplumbBridge: JsplumbBridge;
pipelineCanvasMaximized = false;
currentMouseOverElement: any;
currentZoomLevel: any;
preview: any;
selectMode: any;
currentPipelineName: any;
currentPipelineDescription: any;
pipelineValid = false;
pipelineCacheRunning = false;
pipelineCached = false;
pipelineCanvasMetadata: PipelineCanvasMetadata = new PipelineCanvasMetadata();
pipelineCanvasMetadataAvailable = false;
config: any = {};
@ViewChild('outerCanvas') pipelineCanvas: ElementRef;
@ViewChild('pipelineComponent')
pipelineComponent: PipelineComponent;
panzoom: PanzoomObject;
constructor(private JsPlumbFactoryService: JsplumbFactoryService,
private PipelinePositioningService: PipelinePositioningService,
private ObjectProvider: ObjectProvider,
public EditorService: EditorService,
public PipelineValidationService: PipelineValidationService,
private PipelineService: PipelineService,
private JsplumbService: JsplumbService,
private ShepherdService: ShepherdService,
private dialogService: DialogService,
private dialog: MatDialog,
private ngZone: NgZone,
private pipelineElementDraggedService: PipelineElementDraggedService,
private pipelineCanvasMetadataService: PipelineCanvasMetadataService) {
this.selectMode = true;
this.currentZoomLevel = 1;
}
ngOnInit(): void {
this.JsplumbBridge = this.JsPlumbFactoryService.getJsplumbBridge(false);
if (this.currentModifiedPipelineId) {
this.displayPipelineById();
} else {
this.checkAndDisplayCachedPipeline();
}
this.pipelineElementDraggedService.pipelineElementMovedSubject.subscribe(position => {
const offsetHeight = this.pipelineCanvas.nativeElement.offsetHeight;
const offsetWidth = this.pipelineCanvas.nativeElement.offsetWidth;
const currentPan = this.panzoom.getPan();
let xOffset = 0;
let yOffset = 0;
if ((position.y + currentPan.y) > (offsetHeight - 100)) {
yOffset = -10;
}
if ((position.x + currentPan.x) > (offsetWidth - 100)) {
xOffset = -10;
}
if (xOffset < 0 || yOffset < 0) {
this.pan(xOffset, yOffset);
}
});
}
ngAfterViewInit() {
const elem = document.getElementById('assembly');
this.panzoom = Panzoom(elem, {
maxScale: 5,
excludeClass: 'jtk-draggable',
canvas: true,
contain: 'outside'
});
}
autoLayout() {
this.PipelinePositioningService.layoutGraph('#assembly', 'span[id^=\'jsplumb\']', 110, false);
this.JsplumbBridge.repaintEverything();
}
toggleSelectMode() {
}
zoomOut() {
this.doZoom(true);
}
zoomIn() {
this.doZoom(false);
}
doZoom(zoomOut) {
zoomOut ? this.panzoom.zoomOut() : this.panzoom.zoomIn();
this.currentZoomLevel = this.panzoom.getScale();
this.JsplumbBridge.setZoom(this.currentZoomLevel);
this.JsplumbBridge.repaintEverything();
}
showClearAssemblyConfirmDialog(event: any) {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '500px',
data: {
'title': 'Do you really want to delete the current pipeline?',
'subtitle': 'This cannot be undone.',
'cancelTitle': 'No',
'okTitle': 'Yes',
'confirmAndCancel': true
},
});
dialogRef.afterClosed().subscribe(ev => {
if (ev) {
if (this.currentModifiedPipelineId) {
this.currentModifiedPipelineId = undefined;
}
this.clearAssembly();
this.EditorService.makePipelineAssemblyEmpty(true);
}
});
}
/**
* clears the Assembly of all elements
*/
clearAssembly() {
// $('#assembly').children().not('#clear, #submit').remove();
this.JsplumbBridge.deleteEveryEndpoint();
this.rawPipelineModel = [];
this.currentZoomLevel = 1;
this.JsplumbBridge.setZoom(this.currentZoomLevel);
this.JsplumbBridge.repaintEverything();
const removePipelineFromCache = this.EditorService.removePipelineFromCache();
const removeCanvasMetadataFromCache = this.EditorService.removeCanvasMetadataFromCache();
forkJoin([removePipelineFromCache, removeCanvasMetadataFromCache]).subscribe(msg => {
this.pipelineCached = false;
this.pipelineCacheRunning = false;
});
}
/**
* Sends the pipeline to the server
*/
submit() {
const pipeline = this.ObjectProvider.makeFinalPipeline(this.rawPipelineModel);
this.PipelinePositioningService.collectPipelineElementPositions(this.pipelineCanvasMetadata, this.rawPipelineModel);
pipeline.name = this.currentPipelineName;
pipeline.description = this.currentPipelineDescription;
if (this.currentModifiedPipelineId) {
pipeline._id = this.currentModifiedPipelineId;
}
this.dialogService.open(SavePipelineComponent, {
panelType: PanelType.SLIDE_IN_PANEL,
title: 'Save pipeline',
data: {
'pipeline': pipeline,
'currentModifiedPipelineId': this.currentModifiedPipelineId,
'pipelineCanvasMetadata': this.pipelineCanvasMetadata
}
});
}
checkAndDisplayCachedPipeline() {
const cachedPipeline = this.EditorService.getCachedPipeline();
const cachedCanvasMetadata = this.EditorService.getCachedPipelineCanvasMetadata();
forkJoin([cachedPipeline, cachedCanvasMetadata]).subscribe(results => {
if (results[0] && results[0].length > 0) {
this.rawPipelineModel = results[0] as PipelineElementConfig[];
this.handleCanvasMetadataResponse(results[1]);
}
});
}
displayPipelineById() {
const pipelineRequest = this.PipelineService.getPipelineById(this.currentModifiedPipelineId);
const canvasRequest = this.pipelineCanvasMetadataService.getPipelineCanvasMetadata(this.currentModifiedPipelineId);
pipelineRequest.subscribe(pipelineResp => {
const pipeline = pipelineResp;
this.currentPipelineName = pipeline.name;
this.currentPipelineDescription = pipeline.description;
this.rawPipelineModel = this.JsplumbService.makeRawPipeline(pipeline, false);
canvasRequest.subscribe(canvasResp => {
this.handleCanvasMetadataResponse(canvasResp);
}, error => {
this.handleCanvasMetadataResponse(undefined);
});
});
}
handleCanvasMetadataResponse(canvasMetadata: PipelineCanvasMetadata) {
if (canvasMetadata) {
this.pipelineCanvasMetadata = canvasMetadata;
this.pipelineCanvasMetadataAvailable = true;
} else {
this.pipelineCanvasMetadataAvailable = false;
this.pipelineCanvasMetadata = new PipelineCanvasMetadata();
}
this.displayPipelineInEditor(!this.pipelineCanvasMetadataAvailable, this.pipelineCanvasMetadata);
}
displayPipelineInEditor(autoLayout,
pipelineCanvasMetadata?: PipelineCanvasMetadata) {
setTimeout(() => {
this.PipelinePositioningService.displayPipeline(this.rawPipelineModel, '#assembly', false, autoLayout, pipelineCanvasMetadata);
this.EditorService.makePipelineAssemblyEmpty(false);
this.ngZone.run(() => {
this.pipelineValid = this.PipelineValidationService
.isValidPipeline(this.rawPipelineModel.filter(pe => !(pe.settings.disabled)), false);
});
});
}
isPipelineAssemblyEmpty() {
return this.rawPipelineModel.length === 0 || this.rawPipelineModel.every(pe => pe.settings.disabled);
}
toggleCanvasMaximized() {
this.pipelineCanvasMaximized = !(this.pipelineCanvasMaximized);
this.pipelineCanvasMaximizedEmitter.emit(this.pipelineCanvasMaximized);
}
panLeft() {
this.pan(100, 0);
}
panRight() {
this.pan(-100, 0);
}
panUp() {
this.pan(0, 100);
}
panDown() {
this.pan(0, -100);
}
panHome() {
this.panAbsolute(0, 0);
}
pan(xOffset: number, yOffset: number) {
const currentPan = this.panzoom.getPan();
const panX = Math.min(0, currentPan.x + xOffset);
const panY = Math.min(0, currentPan.y + yOffset);
this.panzoom.pan(panX, panY);
}
panAbsolute(x: number, y: number) {
this.panzoom.pan(x, y);
}
triggerPipelinePreview() {
this.pipelineComponent.initiatePipelineElementPreview();
}
openDiscoverDialog() {
this.dialogService.open(PipelineElementDiscoveryComponent, {
panelType: PanelType.SLIDE_IN_PANEL,
title: 'Discover pipeline elements',
width: '50vw',
data: {
'currentElements': this.allElements,
'rawPipelineModel': this.rawPipelineModel
}
});
}
} | the_stack |
import RnObject from '../../core/RnObject';
import {AlphaMode, AlphaModeEnum} from '../../definitions/AlphaMode';
import AbstractMaterialNode from './AbstractMaterialNode';
import {
ShaderSemanticsEnum,
ShaderSemanticsInfo,
ShaderSemantics,
ShaderSemanticsIndex,
getShaderPropertyFunc,
} from '../../definitions/ShaderSemantics';
import {CompositionType} from '../../definitions/CompositionType';
import MathClassUtil from '../../math/MathClassUtil';
import {ComponentType} from '../../definitions/ComponentType';
import CGAPIResourceRepository from '../../renderer/CGAPIResourceRepository';
import AbstractTexture from '../../textures/AbstractTexture';
import MemoryManager from '../../core/MemoryManager';
import {BufferUse} from '../../definitions/BufferUse';
import Config from '../../core/Config';
import BufferView from '../../memory/BufferView';
import Accessor from '../../memory/Accessor';
import {ShaderType} from '../../definitions/ShaderType';
import {
Index,
CGAPIResourceHandle,
Count,
IndexOf16Bytes,
} from '../../../types/CommonTypes';
import DataUtil from '../../misc/DataUtil';
import GlobalDataRepository from '../../core/GlobalDataRepository';
import System from '../../system/System';
import {ProcessApproach} from '../../definitions/ProcessApproach';
import ShaderityUtility from './ShaderityUtility';
import {BoneDataType} from '../../definitions/BoneDataType';
import {ShaderVariableUpdateInterval} from '../../definitions/ShaderVariableUpdateInterval';
import WebGLContextWrapper from '../../../webgl/WebGLContextWrapper';
type MaterialTypeName = string;
type ShaderVariable = {
value: any;
info: ShaderSemanticsInfo;
};
/**
* The material class.
* This class has one or more material nodes.
*/
export default class Material extends RnObject {
private __materialNodes: AbstractMaterialNode[] = [];
private __fields: Map<ShaderSemanticsIndex, ShaderVariable> = new Map();
private __fieldsForNonSystem: Map<ShaderSemanticsIndex, ShaderVariable> =
new Map();
private static __soloDatumFields: Map<
MaterialTypeName,
Map<ShaderSemanticsIndex, ShaderVariable>
> = new Map();
private __fieldsInfo: Map<ShaderSemanticsIndex, ShaderSemanticsInfo> =
new Map();
public _shaderProgramUid: CGAPIResourceHandle =
CGAPIResourceRepository.InvalidCGAPIResourceUid;
private __alphaMode = AlphaMode.Opaque;
private static __shaderHashMap: Map<number, CGAPIResourceHandle> = new Map();
private static __shaderStringMap: Map<string, CGAPIResourceHandle> =
new Map();
private static __materials: Material[] = [];
private static __instancesByTypes: Map<MaterialTypeName, Material> =
new Map();
private __materialTid: Index;
private static __materialTidCount = -1;
private static __materialTids: Map<MaterialTypeName, Index> = new Map();
private static __materialInstanceCountOfType: Map<MaterialTypeName, Count> =
new Map();
private __materialSid: Index = -1;
private static __materialTypes: Map<
MaterialTypeName,
AbstractMaterialNode[]
> = new Map();
private static __maxInstances: Map<MaterialTypeName, number> = new Map();
private __materialTypeName: MaterialTypeName;
private static __bufferViews: Map<MaterialTypeName, BufferView> = new Map();
private static __accessors: Map<
MaterialTypeName,
Map<ShaderSemanticsIndex, Accessor>
> = new Map();
public cullFace = true; // If true, enable gl.CULL_FACE
public cullFrontFaceCCW = true;
private __blendEquationMode = 32774; // gl.FUNC_ADD
private __blendEquationModeAlpha = 32774; // gl.FUNC_ADD
private __blendFuncSrcFactor = 770; // gl.SRC_ALPHA
private __blendFuncDstFactor = 771; // gl.ONE_MINUS_SRC_ALPHA
private __blendFuncAlphaSrcFactor = 1; // gl.ONE
private __blendFuncAlphaDstFactor = 1; // gl.ONE
private __alphaToCoverage = false;
private constructor(
materialTid: Index,
materialTypeName: string,
materialNodes: AbstractMaterialNode[]
) {
super();
this.__materialNodes = materialNodes;
this.__materialTid = materialTid;
this.__materialTypeName = materialTypeName;
Material.__materials.push(this);
Material.__instancesByTypes.set(materialTypeName, this);
this.tryToSetUniqueName(materialTypeName, true);
this.initialize();
}
get materialTypeName() {
return this.__materialTypeName;
}
/**
* Gets materialTID.
*/
get materialTID() {
return this.__materialTid;
}
get fieldsInfoArray() {
return Array.from(this.__fieldsInfo.values());
}
/**
* Creates an instance of this Material class.
* @param materialTypeName The material type to create.
* @param materialNodes_ The material nodes to add to the created material.
*/
static createMaterial(
materialTypeName: string,
materialNodes_?: AbstractMaterialNode[]
) {
let materialNodes = materialNodes_;
if (!materialNodes) {
materialNodes = Material.__materialTypes.get(materialTypeName)!;
}
return new Material(
Material.__materialTids.get(materialTypeName)!,
materialTypeName,
materialNodes
);
}
static isRegisteredMaterialType(materialTypeName: string) {
return Material.__materialTypes.has(materialTypeName);
}
static _calcAlignedByteLength(semanticInfo: ShaderSemanticsInfo) {
const compositionNumber =
semanticInfo.compositionType.getNumberOfComponents();
const componentSizeInByte = semanticInfo.componentType.getSizeInBytes();
const semanticInfoByte = compositionNumber * componentSizeInByte;
let alignedByteLength = semanticInfoByte;
if (alignedByteLength % 16 !== 0) {
alignedByteLength = semanticInfoByte + 16 - (semanticInfoByte % 16);
}
if (CompositionType.isArray(semanticInfo.compositionType)) {
const maxArrayLength = semanticInfo.maxIndex;
if (maxArrayLength != null) {
alignedByteLength *= maxArrayLength;
} else {
console.error('semanticInfo has invalid maxIndex!');
alignedByteLength *= 100;
}
}
return alignedByteLength;
}
private static __allocateBufferView(
materialTypeName: string,
materialNodes: AbstractMaterialNode[]
) {
let totalByteLength = 0;
const alignedByteLengthAndSemanticInfoArray = [];
for (const materialNode of materialNodes) {
for (const semanticInfo of materialNode._semanticsInfoArray) {
const alignedByteLength = Material._calcAlignedByteLength(semanticInfo);
let dataCount = 1;
if (!semanticInfo.soloDatum) {
dataCount = Material.__maxInstances.get(materialTypeName)!;
}
totalByteLength += alignedByteLength * dataCount;
alignedByteLengthAndSemanticInfoArray.push({
alignedByte: alignedByteLength,
semanticInfo: semanticInfo,
});
}
}
if (!this.__accessors.has(materialTypeName)) {
this.__accessors.set(materialTypeName, new Map());
}
const buffer = MemoryManager.getInstance().createOrGetBuffer(
BufferUse.GPUInstanceData
);
let bufferView;
if (this.__bufferViews.has(materialTypeName)) {
bufferView = this.__bufferViews.get(materialTypeName);
} else {
bufferView = buffer.takeBufferView({
byteLengthToNeed: totalByteLength,
byteStride: 0,
});
this.__bufferViews.set(materialTypeName, bufferView);
}
for (let i = 0; i < alignedByteLengthAndSemanticInfoArray.length; i++) {
const alignedByte = alignedByteLengthAndSemanticInfoArray[i].alignedByte;
const semanticInfo =
alignedByteLengthAndSemanticInfoArray[i].semanticInfo;
let count = 1;
if (!semanticInfo.soloDatum) {
count = Material.__maxInstances.get(materialTypeName)!;
}
let maxArrayLength = semanticInfo.maxIndex;
if (
CompositionType.isArray(semanticInfo.compositionType) &&
maxArrayLength == null
) {
maxArrayLength = 100;
}
const accessor = bufferView!.takeAccessor({
compositionType: semanticInfo.compositionType,
componentType: ComponentType.Float,
count: count,
byteStride: alignedByte,
arrayLength: maxArrayLength,
});
const propertyIndex = this._getPropertyIndex(semanticInfo);
if (semanticInfo.soloDatum) {
const typedArray = accessor.takeOne() as Float32Array;
let map = this.__soloDatumFields.get(materialTypeName);
if (map == null) {
map = new Map();
this.__soloDatumFields.set(materialTypeName, map);
}
map.set(this._getPropertyIndex(semanticInfo), {
info: semanticInfo,
value: MathClassUtil.initWithFloat32Array(
semanticInfo.initialValue,
semanticInfo.initialValue,
typedArray,
semanticInfo.compositionType
),
});
} else {
const properties = this.__accessors.get(materialTypeName)!;
properties.set(propertyIndex, accessor);
}
}
return bufferView;
}
/**
* Registers the material type.
* @param materialTypeName The type name of the material.
* @param materialNodes The material nodes to register.
* @param maxInstancesNumber The maximum number to create the material instances.
*/
static registerMaterial(
materialTypeName: string,
materialNodes: AbstractMaterialNode[],
maxInstanceNumber: number = Config.maxMaterialInstanceForEachType
) {
if (!Material.__materialTypes.has(materialTypeName)) {
Material.__materialTypes.set(materialTypeName, materialNodes);
const materialTid = ++Material.__materialTidCount;
Material.__materialTids.set(materialTypeName, materialTid);
Material.__maxInstances.set(materialTypeName, maxInstanceNumber);
Material.__allocateBufferView(materialTypeName, materialNodes);
Material.__materialInstanceCountOfType.set(materialTypeName, 0);
return true;
} else {
console.info(`${materialTypeName} is already registered.`);
return false;
}
}
static forceRegisterMaterial(
materialTypeName: string,
materialNodes: AbstractMaterialNode[],
maxInstanceNumber: number = Config.maxMaterialInstanceForEachType
) {
Material.__materialTypes.set(materialTypeName, materialNodes);
const materialTid = ++Material.__materialTidCount;
Material.__materialTids.set(materialTypeName, materialTid);
Material.__maxInstances.set(materialTypeName, maxInstanceNumber);
Material.__allocateBufferView(materialTypeName, materialNodes);
Material.__materialInstanceCountOfType.set(materialTypeName, 0);
return true;
}
static getAllMaterials() {
return Material.__materials;
}
setMaterialNodes(materialNodes: AbstractMaterialNode[]) {
this.__materialNodes = materialNodes;
}
get materialSID() {
return this.__materialSid;
}
get isSkinning() {
return this.__materialNodes[0].isSkinning;
}
get isMorphing() {
return this.__materialNodes[0].isMorphing;
}
get isLighting() {
return this.__materialNodes[0].isLighting;
}
/**
* @private
*/
static _getPropertyIndex(semanticInfo: ShaderSemanticsInfo) {
let propertyIndex = semanticInfo.semantic.index;
if (semanticInfo.index != null) {
propertyIndex += semanticInfo.index;
propertyIndex *= -1;
}
return propertyIndex;
}
/**
* @private
*/
static _getPropertyIndex2(
shaderSemantic: ShaderSemanticsEnum,
index?: Index
) {
let propertyIndex = shaderSemantic.index;
if (index != null) {
propertyIndex += index;
propertyIndex *= -1;
}
return propertyIndex;
}
initialize() {
let countOfThisType = Material.__materialInstanceCountOfType.get(
this.__materialTypeName
) as number;
this.__materialSid = countOfThisType++;
Material.__materialInstanceCountOfType.set(
this.__materialTypeName,
countOfThisType
);
this.__materialNodes.forEach(materialNode => {
const semanticsInfoArray = materialNode._semanticsInfoArray;
const accessorMap = Material.__accessors.get(this.__materialTypeName);
semanticsInfoArray.forEach(semanticsInfo => {
const propertyIndex = Material._getPropertyIndex(semanticsInfo);
this.__fieldsInfo.set(propertyIndex, semanticsInfo);
if (!semanticsInfo.soloDatum) {
const accessor = accessorMap!.get(propertyIndex) as Accessor;
const typedArray = accessor.takeOne() as Float32Array;
const shaderVariable = {
info: semanticsInfo,
value: MathClassUtil.initWithFloat32Array(
semanticsInfo.initialValue,
semanticsInfo.initialValue,
typedArray,
semanticsInfo.compositionType
),
};
this.__fields.set(propertyIndex, shaderVariable);
if (!semanticsInfo.isSystem) {
this.__fieldsForNonSystem.set(propertyIndex, shaderVariable);
}
}
});
});
}
setParameter(shaderSemantic: ShaderSemanticsEnum, value: any, index?: Index) {
const propertyIndex = Material._getPropertyIndex2(shaderSemantic, index);
const info = this.__fieldsInfo.get(propertyIndex);
if (info != null) {
let valueObj: ShaderVariable | undefined;
if (info.soloDatum) {
valueObj = Material.__soloDatumFields
.get(this.__materialTypeName)!
.get(propertyIndex);
} else {
valueObj = this.__fields.get(propertyIndex);
}
MathClassUtil._setForce(valueObj!.value, value);
}
}
setTextureParameter(
shaderSemantic: ShaderSemanticsEnum,
value: AbstractTexture
): void {
if (this.__fieldsInfo.has(shaderSemantic.index)) {
const array = this.__fields.get(shaderSemantic.index)!;
const shaderVariable = {
value: [array.value[0], value],
info: array.info,
};
this.__fields.set(shaderSemantic.index, shaderVariable);
if (!array.info.isSystem) {
this.__fieldsForNonSystem.set(shaderSemantic.index, shaderVariable);
}
if (
shaderSemantic === ShaderSemantics.DiffuseColorTexture ||
shaderSemantic === ShaderSemantics.BaseColorTexture
) {
if (value.isTransparent) {
this.alphaMode = AlphaMode.Translucent;
}
}
}
}
getParameter(shaderSemantic: ShaderSemanticsEnum): any {
const info = this.__fieldsInfo.get(shaderSemantic.index);
if (info != null) {
if (info.soloDatum) {
return Material.__soloDatumFields
.get(this.__materialTypeName)!
.get(shaderSemantic.index)?.value;
} else {
return this.__fields.get(shaderSemantic.index)?.value;
}
}
return void 0;
}
setUniformLocations(
shaderProgramUid: CGAPIResourceHandle,
isUniformOnlyMode: boolean
) {
const webglResourceRepository =
CGAPIResourceRepository.getWebGLResourceRepository();
const map: Map<string, ShaderSemanticsInfo> = new Map();
let array: ShaderSemanticsInfo[] = [];
this.__materialNodes.forEach(materialNode => {
const semanticsInfoArray = materialNode._semanticsInfoArray;
array = array.concat(semanticsInfoArray);
});
webglResourceRepository.setupUniformLocations(
shaderProgramUid,
array,
isUniformOnlyMode
);
}
/**
* @private
*/
_setParametersForGPU({
material,
shaderProgram,
firstTime,
args,
}: {
material: Material;
shaderProgram: WebGLProgram;
firstTime: boolean;
args?: any;
}) {
this.__materialNodes.forEach(materialNode => {
if (materialNode.setParametersForGPU) {
materialNode.setParametersForGPU({
material,
shaderProgram,
firstTime,
args,
});
}
});
const webglResourceRepository =
CGAPIResourceRepository.getWebGLResourceRepository();
if (args.setUniform) {
this.__fieldsForNonSystem.forEach(value => {
const info = value.info;
if (
firstTime ||
info.updateInterval !== ShaderVariableUpdateInterval.FirstTimeOnly
) {
webglResourceRepository.setUniformValue(
shaderProgram,
info.semantic.str,
firstTime,
value.value,
info.index
);
} else {
if (
info.compositionType === CompositionType.Texture2D ||
info.compositionType === CompositionType.TextureCube
) {
webglResourceRepository.bindTexture(info, value.value);
}
}
});
} else {
this.__fieldsForNonSystem.forEach(value => {
const info = value.info;
if (
info.compositionType === CompositionType.Texture2D ||
info.compositionType === CompositionType.TextureCube
) {
if (
firstTime ||
info.updateInterval !== ShaderVariableUpdateInterval.FirstTimeOnly
) {
webglResourceRepository.setUniformValue(
shaderProgram,
info.semantic.str,
firstTime,
value.value,
info.index
);
} else {
webglResourceRepository.bindTexture(info, value.value);
}
}
});
}
this.setSoloDatumParametersForGPU({shaderProgram, firstTime, args});
}
setSoloDatumParametersForGPU({
shaderProgram,
firstTime,
args,
}: {
shaderProgram: WebGLProgram;
firstTime: boolean;
args?: any;
}) {
const webglResourceRepository =
CGAPIResourceRepository.getWebGLResourceRepository();
const materialTypeName = this.__materialTypeName;
const map = Material.__soloDatumFields.get(materialTypeName);
if (map == null) return;
map.forEach((value, key) => {
const info = value.info;
if (
args.setUniform ||
info.compositionType === CompositionType.Texture2D ||
info.compositionType === CompositionType.TextureCube
) {
if (!info.isSystem) {
if (
firstTime ||
info.updateInterval !== ShaderVariableUpdateInterval.FirstTimeOnly
) {
webglResourceRepository.setUniformValue(
shaderProgram,
info.semantic.str,
firstTime,
value.value,
info.index
);
} else {
webglResourceRepository.bindTexture(info, value.value);
}
}
}
});
}
private __setupGlobalShaderDefinition() {
let definitions = '';
const webglResourceRepository =
CGAPIResourceRepository.getWebGLResourceRepository();
const glw =
webglResourceRepository.currentWebGLContextWrapper as WebGLContextWrapper;
if (glw.isWebGL2) {
definitions += '#version 300 es\n#define GLSL_ES3\n';
if (Config.isUboEnabled) {
definitions += '#define RN_IS_UBO_ENABLED\n';
}
}
definitions += `#define RN_MATERIAL_TYPE_NAME ${this.__materialTypeName}\n`;
if (
ProcessApproach.isFastestApproach(System.getInstance().processApproach)
) {
definitions += '#define RN_IS_FASTEST_MODE\n';
}
if (glw.webgl1ExtSTL) {
definitions += '#define WEBGL1_EXT_SHADER_TEXTURE_LOD\n';
}
if (glw.webgl1ExtDRV) {
definitions += '#define WEBGL1_EXT_STANDARD_DERIVATIVES\n';
}
if (glw.isWebGL2 || glw.webgl1ExtDRV) {
definitions += '#define RN_IS_SUPPORTING_STANDARD_DERIVATIVES\n';
}
if (Config.boneDataType === BoneDataType.Mat44x1) {
definitions += '#define RN_BONE_DATA_TYPE_Mat44x1\n';
} else if (Config.boneDataType === BoneDataType.Vec4x2) {
definitions += '#define RN_BONE_DATA_TYPE_VEC4X2\n';
} else if (Config.boneDataType === BoneDataType.Vec4x2Old) {
definitions += '#define RN_BONE_DATA_TYPE_VEC4X2_OLD\n';
} else if (Config.boneDataType === BoneDataType.Vec4x1) {
definitions += '#define RN_BONE_DATA_TYPE_VEC4X1\n';
}
return definitions;
}
createProgramAsSingleOperation(
vertexShaderMethodDefinitions_uniform: string,
propertySetter: getShaderPropertyFunc,
isWebGL2: boolean
) {
const webglResourceRepository =
CGAPIResourceRepository.getWebGLResourceRepository();
const materialNode = this.__materialNodes[0];
const glslShader = materialNode.shader;
const {vertexPropertiesStr, pixelPropertiesStr} = this._getProperties(
propertySetter,
isWebGL2
);
const definitions = materialNode.definitions;
// Shader Construction
let vertexShader = this.__setupGlobalShaderDefinition();
let pixelShader = this.__setupGlobalShaderDefinition();
let vertexShaderBody = '';
let pixelShaderBody = '';
vertexShaderBody = ShaderityUtility.getInstance().getVertexShaderBody(
materialNode.vertexShaderityObject!,
{
getters: vertexPropertiesStr,
definitions: definitions,
dataUBODefinition:
webglResourceRepository.getGlslDataUBODefinitionString(),
dataUBOVec4Size: webglResourceRepository.getGlslDataUBOVec4SizeString(),
matricesGetters: vertexShaderMethodDefinitions_uniform,
}
);
pixelShaderBody = ShaderityUtility.getInstance().getPixelShaderBody(
materialNode.pixelShaderityObject!,
{
getters: pixelPropertiesStr,
definitions: definitions,
dataUBODefinition:
webglResourceRepository.getGlslDataUBODefinitionString(),
dataUBOVec4Size: webglResourceRepository.getGlslDataUBOVec4SizeString(),
}
);
vertexShader += vertexShaderBody.replace(/#version\s+300\s+es/, '');
pixelShader += pixelShaderBody.replace(/#version\s+300\s+es/, '');
let attributeNames;
let attributeSemantics;
if (materialNode.vertexShaderityObject != null) {
const reflection = ShaderityUtility.getInstance().getReflection(
materialNode.vertexShaderityObject
);
attributeNames = reflection.names;
attributeSemantics = reflection.semantics;
} else {
attributeNames = glslShader!.attributeNames;
attributeSemantics = glslShader!.attributeSemantics;
}
let vertexAttributesBinding = '\n// Vertex Attributes Binding Info\n';
for (let i = 0; i < attributeNames.length; i++) {
vertexAttributesBinding += `// ${attributeNames[i]}: ${attributeSemantics[i].str} \n`;
}
vertexShader += vertexAttributesBinding;
const wholeShaderText = vertexShader + pixelShader;
// Cache
let shaderProgramUid = Material.__shaderStringMap.get(wholeShaderText);
if (shaderProgramUid) {
this._shaderProgramUid = shaderProgramUid;
return shaderProgramUid;
}
const hash = DataUtil.toCRC32(wholeShaderText);
shaderProgramUid = Material.__shaderHashMap.get(hash);
if (shaderProgramUid) {
this._shaderProgramUid = shaderProgramUid;
return this._shaderProgramUid;
} else {
this._shaderProgramUid = webglResourceRepository.createShaderProgram({
materialTypeName: this.__materialTypeName,
vertexShaderStr: vertexShader,
fragmentShaderStr: pixelShader,
attributeNames: attributeNames,
attributeSemantics: attributeSemantics,
});
Material.__shaderStringMap.set(wholeShaderText, this._shaderProgramUid);
Material.__shaderHashMap.set(hash, this._shaderProgramUid);
return this._shaderProgramUid;
}
}
/**
* @private
* @param propertySetter
*/
_getProperties(propertySetter: getShaderPropertyFunc, isWebGL2: boolean) {
let vertexPropertiesStr = '';
let pixelPropertiesStr = '';
this.__fieldsInfo.forEach((value, propertyIndex: Index) => {
const info = this.__fieldsInfo.get(propertyIndex);
if (
info!.stage === ShaderType.VertexShader ||
info!.stage === ShaderType.VertexAndPixelShader
) {
vertexPropertiesStr += propertySetter(
this.__materialTypeName,
info!,
propertyIndex,
false,
isWebGL2
);
}
if (
info!.stage === ShaderType.PixelShader ||
info!.stage === ShaderType.VertexAndPixelShader
) {
pixelPropertiesStr += propertySetter(
this.__materialTypeName,
info!,
propertyIndex,
false,
isWebGL2
);
}
});
const globalDataRepository = GlobalDataRepository.getInstance();
[vertexPropertiesStr, pixelPropertiesStr] =
globalDataRepository.addPropertiesStr(
vertexPropertiesStr,
pixelPropertiesStr,
propertySetter,
isWebGL2
);
return {vertexPropertiesStr, pixelPropertiesStr};
}
createProgram(
vertexShaderMethodDefinitions_uniform: string,
propertySetter: getShaderPropertyFunc,
isWebGL2: boolean
) {
return this.createProgramAsSingleOperation(
vertexShaderMethodDefinitions_uniform,
propertySetter,
isWebGL2
);
}
isBlend() {
if (
this.alphaMode === AlphaMode.Translucent ||
this.alphaMode === AlphaMode.Additive
) {
return true;
} else {
return false;
}
}
static getLocationOffsetOfMemberOfMaterial(
materialTypeName: string,
propertyIndex: Index
): IndexOf16Bytes {
const material = Material.__instancesByTypes.get(materialTypeName)!;
const info = material.__fieldsInfo.get(propertyIndex)!;
if (info.soloDatum) {
const value = Material.__soloDatumFields
.get(material.__materialTypeName)!
.get(propertyIndex);
return (value!.value._v as Float32Array).byteOffset / 4 / 4;
} else {
const properties = this.__accessors.get(materialTypeName);
const accessor = properties!.get(propertyIndex);
return accessor!.byteOffsetInBuffer / 4 / 4;
}
}
static getAccessorOfMemberOfMaterial(
materialTypeName: string,
propertyIndex: Index
) {
const material = Material.__instancesByTypes.get(materialTypeName)!;
const info = material.__fieldsInfo.get(propertyIndex)!;
if (info.soloDatum) {
return void 0;
} else {
const properties = this.__accessors.get(materialTypeName);
const accessor = properties!.get(propertyIndex);
return accessor;
}
}
get alphaMode() {
return this.__alphaMode;
}
set alphaMode(mode: AlphaModeEnum) {
this.__alphaMode = mode;
}
/**
* Change the blendEquations
* This method works only if this alphaMode is the translucent
* @param blendEquationMode the argument of gl.blendEquation of the first argument of gl.blendEquationSeparate such as gl.FUNC_ADD
* @param blendEquationModeAlpha the second argument of gl.blendEquationSeparate
*/
setBlendEquationMode(
blendEquationMode: number,
blendEquationModeAlpha?: number
) {
this.__blendEquationMode = blendEquationMode;
this.__blendEquationModeAlpha = blendEquationModeAlpha ?? blendEquationMode;
}
/**
* Change the blendFuncSeparateFactors
* This method works only if this alphaMode is the translucent
*/
setBlendFuncSeparateFactor(
blendFuncSrcFactor: number,
blendFuncDstFactor: number,
blendFuncAlphaSrcFactor: number,
blendFuncAlphaDstFactor: number
) {
this.__blendFuncSrcFactor = blendFuncSrcFactor;
this.__blendFuncDstFactor = blendFuncDstFactor;
this.__blendFuncAlphaSrcFactor = blendFuncAlphaSrcFactor;
this.__blendFuncAlphaDstFactor = blendFuncAlphaDstFactor;
}
/**
* Change the blendFuncFactors
* This method works only if this alphaMode is the translucent
*/
setBlendFuncFactor(blendFuncSrcFactor: number, blendFuncDstFactor: number) {
this.__blendFuncSrcFactor = blendFuncSrcFactor;
this.__blendFuncDstFactor = blendFuncDstFactor;
this.__blendFuncAlphaSrcFactor = blendFuncSrcFactor;
this.__blendFuncAlphaDstFactor = blendFuncDstFactor;
}
get blendEquationMode() {
return this.__blendEquationMode;
}
get blendEquationModeAlpha() {
return this.__blendEquationModeAlpha;
}
get blendFuncSrcFactor() {
return this.__blendFuncSrcFactor;
}
get blendFuncDstFactor() {
return this.__blendFuncDstFactor;
}
get blendFuncAlphaSrcFactor() {
return this.__blendFuncAlphaSrcFactor;
}
get blendFuncAlphaDstFactor() {
return this.__blendFuncAlphaDstFactor;
}
isEmptyMaterial(): boolean {
if (this.__materialNodes.length === 0) {
return true;
} else {
return false;
}
}
getShaderSemanticInfoFromName(name: string) {
for (const materialNode of this.__materialNodes) {
return materialNode.getShaderSemanticInfoFromName(name);
}
return void 0;
}
/**
* NOTE: To apply the alphaToCoverage, the output alpha value must not be fixed to constant value.
* However, some shaders in the Rhodonite fixes the output alpha value to 1 by setAlphaIfNotInAlphaBlendMode.
* So we need to improve the shader to use the alphaToCoverage.
* @param alphaToCoverage apply alphaToCoverage to this material or not
*/
set alphaToCoverage(alphaToCoverage: boolean) {
if (alphaToCoverage && this.alphaMode === AlphaMode.Translucent) {
console.warn(
'If you set alphaToCoverage = true on a material whose AlphaMode is Translucent, you may get drawing problems.'
);
}
this.__alphaToCoverage = alphaToCoverage;
}
get alphaToCoverage() {
return this.__alphaToCoverage;
}
} | the_stack |
import options from '../util/options';
import common from '../util/common';
import Vec2 from '../common/Vec2';
import BroadPhase from '../collision/BroadPhase';
import Solver, { ContactImpulse, TimeStep } from './Solver';
import Body, { BodyDef } from './Body';
import Joint from './Joint';
import Contact from './Contact';
import AABB, { RayCastInput, RayCastOutput } from "../collision/AABB";
import Fixture, { FixtureProxy } from "./Fixture";
import Manifold from "../collision/Manifold";
const _ASSERT = typeof ASSERT === 'undefined' ? false : ASSERT;
/**
* @prop gravity [{ x : 0, y : 0}]
* @prop allowSleep [true]
* @prop warmStarting [true]
* @prop continuousPhysics [true]
* @prop subStepping [false]
* @prop blockSolve [true]
* @prop velocityIterations [8] For the velocity constraint solver.
* @prop positionIterations [3] For the position constraint solver.
*/
export interface WorldDef {
gravity?: Vec2;
allowSleep?: boolean;
warmStarting?: boolean;
continuousPhysics?: boolean;
subStepping?: boolean;
blockSolve?: boolean;
velocityIterations?: number;
positionIterations?: number;
}
const WorldDefDefault: WorldDef = {
gravity : Vec2.zero(),
allowSleep : true,
warmStarting : true,
continuousPhysics : true,
subStepping : false,
blockSolve : true,
velocityIterations : 8,
positionIterations : 3
};
/**
* Callback function for ray casts, see {@link World.rayCast}.
*
* Called for each fixture found in the query. You control how the ray cast
* proceeds by returning a float: return -1: ignore this fixture and continue
* return 0: terminate the ray cast return fraction: clip the ray to this point
* return 1: don't clip the ray and continue
*
* @param fixture The fixture hit by the ray
* @param point The point of initial intersection
* @param normal The normal vector at the point of intersection
* @param fraction
*
* @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue
*/
export type WorldRayCastCallback = (fixture: Fixture, point: Vec2, normal: Vec2, fraction: number) => number;
/**
* Called for each fixture found in the query AABB. It may return `false` to terminate the query.
*/
export type WorldAABBQueryCallback = (fixture: Fixture) => boolean;
export default class World {
/** @internal */ m_solver: Solver;
/** @internal */ m_broadPhase: BroadPhase;
/** @internal */ m_contactList: Contact | null;
/** @internal */ m_contactCount: number;
/** @internal */ m_bodyList: Body | null;
/** @internal */ m_bodyCount: number;
/** @internal */ m_jointList: Joint | null;
/** @internal */ m_jointCount: number;
/** @internal */ m_stepComplete: boolean;
/** @internal */ m_allowSleep: boolean;
/** @internal */ m_gravity: Vec2;
/** @internal */ m_clearForces: boolean;
/** @internal */ m_newFixture: boolean;
/** @internal */ m_locked: boolean;
/** @internal */ m_warmStarting: boolean;
/** @internal */ m_continuousPhysics: boolean;
/** @internal */ m_subStepping: boolean;
/** @internal */ m_blockSolve: boolean;
/** @internal */ m_velocityIterations: number;
/** @internal */ m_positionIterations: number;
/** @internal */ m_t: number;
// TODO
/** @internal */ _listeners: {
[key: string]: any[]
};
/**
* @param def World definition or gravity vector.
*/
constructor(def?: WorldDef | Vec2 | null) {
if (!(this instanceof World)) {
return new World(def);
}
if (def && Vec2.isValid(def)) {
def = { gravity: def as Vec2 };
}
def = options(def, WorldDefDefault) as WorldDef;
this.m_solver = new Solver(this);
this.m_broadPhase = new BroadPhase();
this.m_contactList = null;
this.m_contactCount = 0;
this.m_bodyList = null;
this.m_bodyCount = 0;
this.m_jointList = null;
this.m_jointCount = 0;
this.m_stepComplete = true;
this.m_allowSleep = def.allowSleep;
this.m_gravity = Vec2.clone(def.gravity);
this.m_clearForces = true;
this.m_newFixture = false;
this.m_locked = false;
// These are for debugging the solver.
this.m_warmStarting = def.warmStarting;
this.m_continuousPhysics = def.continuousPhysics;
this.m_subStepping = def.subStepping;
this.m_blockSolve = def.blockSolve;
this.m_velocityIterations = def.velocityIterations;
this.m_positionIterations = def.positionIterations;
this.m_t = 0;
}
/** @internal */
_serialize(): object {
const bodies = [];
const joints = [];
for (let b = this.getBodyList(); b; b = b.getNext()) {
bodies.push(b);
}
for (let j = this.getJointList(); j; j = j.getNext()) {
// @ts-ignore
if (typeof j._serialize === 'function') {
joints.push(j);
}
}
return {
gravity: this.m_gravity,
bodies,
joints,
};
}
/** @internal */
static _deserialize(data: any, context: any, restore: any): World {
if (!data) {
return new World();
}
const world = new World(data.gravity);
if (data.bodies) {
for (let i = data.bodies.length - 1; i >= 0; i -= 1) {
world._addBody(restore(Body, data.bodies[i], world));
}
}
if (data.joints) {
for (let i = data.joints.length - 1; i >= 0; i--) {
world.createJoint(restore(Joint, data.joints[i], world));
}
}
return world;
}
/**
* Get the world body list. With the returned body, use Body.getNext to get the
* next body in the world list. A null body indicates the end of the list.
*
* @return the head of the world body list.
*/
getBodyList(): Body | null {
return this.m_bodyList;
}
/**
* Get the world joint list. With the returned joint, use Joint.getNext to get
* the next joint in the world list. A null joint indicates the end of the list.
*
* @return the head of the world joint list.
*/
getJointList(): Joint | null {
return this.m_jointList;
}
/**
* Get the world contact list. With the returned contact, use Contact.getNext to
* get the next contact in the world list. A null contact indicates the end of
* the list.
*
* Warning: contacts are created and destroyed in the middle of a time step.
* Use ContactListener to avoid missing contacts.
*
* @return the head of the world contact list.
*/
getContactList(): Contact | null {
return this.m_contactList;
}
getBodyCount(): number {
return this.m_bodyCount;
}
getJointCount(): number {
return this.m_jointCount;
}
/**
* Get the number of contacts (each may have 0 or more contact points).
*/
getContactCount(): number {
return this.m_contactCount;
}
/**
* Change the global gravity vector.
*/
setGravity(gravity: Vec2): void {
this.m_gravity = gravity;
}
/**
* Get the global gravity vector.
*/
getGravity(): Vec2 {
return this.m_gravity;
}
/**
* Is the world locked (in the middle of a time step).
*/
isLocked(): boolean {
return this.m_locked;
}
/**
* Enable/disable sleep.
*/
setAllowSleeping(flag: boolean): void {
if (flag == this.m_allowSleep) {
return;
}
this.m_allowSleep = flag;
if (this.m_allowSleep == false) {
for (let b = this.m_bodyList; b; b = b.m_next) {
b.setAwake(true);
}
}
}
getAllowSleeping(): boolean {
return this.m_allowSleep;
}
/**
* Enable/disable warm starting. For testing.
*/
setWarmStarting(flag: boolean): void {
this.m_warmStarting = flag;
}
getWarmStarting(): boolean {
return this.m_warmStarting;
}
/**
* Enable/disable continuous physics. For testing.
*/
setContinuousPhysics(flag: boolean): void {
this.m_continuousPhysics = flag;
}
getContinuousPhysics(): boolean {
return this.m_continuousPhysics;
}
/**
* Enable/disable single stepped continuous physics. For testing.
*/
setSubStepping(flag: boolean): void {
this.m_subStepping = flag;
}
getSubStepping(): boolean {
return this.m_subStepping;
}
/**
* Set flag to control automatic clearing of forces after each time step.
*/
setAutoClearForces(flag: boolean): void {
this.m_clearForces = flag;
}
/**
* Get the flag that controls automatic clearing of forces after each time step.
*/
getAutoClearForces(): boolean {
return this.m_clearForces;
}
/**
* Manually clear the force buffer on all bodies. By default, forces are cleared
* automatically after each call to step. The default behavior is modified by
* calling setAutoClearForces. The purpose of this function is to support
* sub-stepping. Sub-stepping is often used to maintain a fixed sized time step
* under a variable frame-rate. When you perform sub-stepping you will disable
* auto clearing of forces and instead call clearForces after all sub-steps are
* complete in one pass of your game loop.
*
* See {@link World.setAutoClearForces}
*/
clearForces(): void {
for (let body = this.m_bodyList; body; body = body.getNext()) {
body.m_force.setZero();
body.m_torque = 0.0;
}
}
/**
* Query the world for all fixtures that potentially overlap the provided AABB.
*
* @param aabb The query box.
* @param callback Called for each fixture found in the query AABB. It may return `false` to terminate the query.
*/
queryAABB(aabb: AABB, callback: WorldAABBQueryCallback): void {
_ASSERT && common.assert(typeof callback === 'function');
const broadPhase = this.m_broadPhase;
this.m_broadPhase.query(aabb, function(proxyId: number): boolean { // TODO GC
const proxy = broadPhase.getUserData(proxyId);
return callback(proxy.fixture);
});
}
/**
* Ray-cast the world for all fixtures in the path of the ray. Your callback
* controls whether you get the closest point, any point, or n-points. The
* ray-cast ignores shapes that contain the starting point.
*
* @param point1 The ray starting point
* @param point2 The ray ending point
* @param callback A user implemented callback function.
*/
rayCast(point1: Vec2, point2: Vec2, callback: WorldRayCastCallback): void {
_ASSERT && common.assert(typeof callback === 'function');
const broadPhase = this.m_broadPhase;
this.m_broadPhase.rayCast({
maxFraction : 1.0,
p1 : point1,
p2 : point2
}, function(input: RayCastInput, proxyId: number): number { // TODO GC
const proxy = broadPhase.getUserData(proxyId);
const fixture = proxy.fixture;
const index = proxy.childIndex;
// @ts-ignore
const output: RayCastOutput = {}; // TODO GC
const hit = fixture.rayCast(output, input, index);
if (hit) {
const fraction = output.fraction;
const point = Vec2.add(Vec2.mul((1.0 - fraction), input.p1), Vec2.mul(fraction, input.p2));
return callback(fixture, point, output.normal, fraction);
}
return input.maxFraction;
});
}
/**
* Get the number of broad-phase proxies.
*/
getProxyCount(): number {
return this.m_broadPhase.getProxyCount();
}
/**
* Get the height of broad-phase dynamic tree.
*/
getTreeHeight(): number {
return this.m_broadPhase.getTreeHeight();
}
/**
* Get the balance of broad-phase dynamic tree.
*/
getTreeBalance(): number {
return this.m_broadPhase.getTreeBalance();
}
/**
* Get the quality metric of broad-phase dynamic tree. The smaller the better.
* The minimum is 1.
*/
getTreeQuality(): number {
return this.m_broadPhase.getTreeQuality();
}
/**
* Shift the world origin. Useful for large worlds. The body shift formula is:
* position -= newOrigin
*
* @param newOrigin The new origin with respect to the old origin
*/
shiftOrigin(newOrigin: Vec2): void {
_ASSERT && common.assert(this.m_locked == false);
if (this.m_locked) {
return;
}
for (let b = this.m_bodyList; b; b = b.m_next) {
b.m_xf.p.sub(newOrigin);
b.m_sweep.c0.sub(newOrigin);
b.m_sweep.c.sub(newOrigin);
}
for (let j = this.m_jointList; j; j = j.m_next) {
j.shiftOrigin(newOrigin);
}
this.m_broadPhase.shiftOrigin(newOrigin);
}
/**
* @internal Used for deserialize.
*/
_addBody(body: Body): void {
_ASSERT && common.assert(this.isLocked() === false);
if (this.isLocked()) {
return;
}
// Add to world doubly linked list.
body.m_prev = null;
body.m_next = this.m_bodyList;
if (this.m_bodyList) {
this.m_bodyList.m_prev = body;
}
this.m_bodyList = body;
++this.m_bodyCount;
}
/**
* Create a rigid body given a definition. No reference to the definition is
* retained.
*
* Warning: This function is locked during callbacks.
*/
createBody(def?: BodyDef): Body;
createBody(position: Vec2, angle?: number): Body;
// tslint:disable-next-line:typedef
createBody(arg1?, arg2?) {
_ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return null;
}
let def: BodyDef = {};
if (!arg1) {
} else if (Vec2.isValid(arg1)) {
def = { position : arg1, angle: arg2 };
} else if (typeof arg1 === 'object') {
def = arg1;
}
const body = new Body(this, def);
this._addBody(body);
return body;
}
createDynamicBody(def?: BodyDef): Body;
createDynamicBody(position: Vec2, angle?: number): Body;
// tslint:disable-next-line:typedef
createDynamicBody(arg1?, arg2?) {
let def: BodyDef = {};
if (!arg1) {
} else if (Vec2.isValid(arg1)) {
def = { position : arg1, angle: arg2 };
} else if (typeof arg1 === 'object') {
def = arg1;
}
def.type = 'dynamic';
return this.createBody(def);
}
createKinematicBody(def?: BodyDef): Body;
createKinematicBody(position: Vec2, angle?: number): Body;
// tslint:disable-next-line:typedef
createKinematicBody(arg1?, arg2?) {
let def: BodyDef = {};
if (!arg1) {
} else if (Vec2.isValid(arg1)) {
def = { position : arg1, angle: arg2 };
} else if (typeof arg1 === 'object') {
def = arg1;
}
def.type = 'kinematic';
return this.createBody(def);
}
/**
* Destroy a rigid body given a definition. No reference to the definition is
* retained.
*
* Warning: This automatically deletes all associated shapes and joints.
*
* Warning: This function is locked during callbacks.
*/
destroyBody(b: Body): boolean {
_ASSERT && common.assert(this.m_bodyCount > 0);
_ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return;
}
if (b.m_destroyed) {
return false;
}
// Delete the attached joints.
let je = b.m_jointList;
while (je) {
const je0 = je;
je = je.next;
this.publish('remove-joint', je0.joint);
this.destroyJoint(je0.joint);
b.m_jointList = je;
}
b.m_jointList = null;
// Delete the attached contacts.
let ce = b.m_contactList;
while (ce) {
const ce0 = ce;
ce = ce.next;
this.destroyContact(ce0.contact);
b.m_contactList = ce;
}
b.m_contactList = null;
// Delete the attached fixtures. This destroys broad-phase proxies.
let f = b.m_fixtureList;
while (f) {
const f0 = f;
f = f.m_next;
this.publish('remove-fixture', f0);
f0.destroyProxies(this.m_broadPhase);
b.m_fixtureList = f;
}
b.m_fixtureList = null;
// Remove world body list.
if (b.m_prev) {
b.m_prev.m_next = b.m_next;
}
if (b.m_next) {
b.m_next.m_prev = b.m_prev;
}
if (b == this.m_bodyList) {
this.m_bodyList = b.m_next;
}
b.m_destroyed = true;
--this.m_bodyCount;
this.publish('remove-body', b);
return true;
}
/**
* Create a joint to constrain bodies together. No reference to the definition
* is retained. This may cause the connected bodies to cease colliding.
*
* Warning: This function is locked during callbacks.
*/
createJoint<T extends Joint>(joint: T): T | null {
_ASSERT && common.assert(!!joint.m_bodyA);
_ASSERT && common.assert(!!joint.m_bodyB);
_ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return null;
}
// Connect to the world list.
joint.m_prev = null;
joint.m_next = this.m_jointList;
if (this.m_jointList) {
this.m_jointList.m_prev = joint;
}
this.m_jointList = joint;
++this.m_jointCount;
// Connect to the bodies' doubly linked lists.
joint.m_edgeA.joint = joint;
joint.m_edgeA.other = joint.m_bodyB;
joint.m_edgeA.prev = null;
joint.m_edgeA.next = joint.m_bodyA.m_jointList;
if (joint.m_bodyA.m_jointList)
joint.m_bodyA.m_jointList.prev = joint.m_edgeA;
joint.m_bodyA.m_jointList = joint.m_edgeA;
joint.m_edgeB.joint = joint;
joint.m_edgeB.other = joint.m_bodyA;
joint.m_edgeB.prev = null;
joint.m_edgeB.next = joint.m_bodyB.m_jointList;
if (joint.m_bodyB.m_jointList)
joint.m_bodyB.m_jointList.prev = joint.m_edgeB;
joint.m_bodyB.m_jointList = joint.m_edgeB;
// If the joint prevents collisions, then flag any contacts for filtering.
if (joint.m_collideConnected == false) {
for (let edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) {
if (edge.other == joint.m_bodyA) {
// Flag the contact for filtering at the next time step (where either
// body is awake).
edge.contact.flagForFiltering();
}
}
}
// Note: creating a joint doesn't wake the bodies.
return joint;
}
/**
* Destroy a joint. This may cause the connected bodies to begin colliding.
* Warning: This function is locked during callbacks.
*/
destroyJoint(joint: Joint): void {
_ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return;
}
// Remove from the doubly linked list.
if (joint.m_prev) {
joint.m_prev.m_next = joint.m_next;
}
if (joint.m_next) {
joint.m_next.m_prev = joint.m_prev;
}
if (joint == this.m_jointList) {
this.m_jointList = joint.m_next;
}
// Disconnect from bodies.
const bodyA = joint.m_bodyA;
const bodyB = joint.m_bodyB;
// Wake up connected bodies.
bodyA.setAwake(true);
bodyB.setAwake(true);
// Remove from body 1.
if (joint.m_edgeA.prev) {
joint.m_edgeA.prev.next = joint.m_edgeA.next;
}
if (joint.m_edgeA.next) {
joint.m_edgeA.next.prev = joint.m_edgeA.prev;
}
if (joint.m_edgeA == bodyA.m_jointList) {
bodyA.m_jointList = joint.m_edgeA.next;
}
joint.m_edgeA.prev = null;
joint.m_edgeA.next = null;
// Remove from body 2
if (joint.m_edgeB.prev) {
joint.m_edgeB.prev.next = joint.m_edgeB.next;
}
if (joint.m_edgeB.next) {
joint.m_edgeB.next.prev = joint.m_edgeB.prev;
}
if (joint.m_edgeB == bodyB.m_jointList) {
bodyB.m_jointList = joint.m_edgeB.next;
}
joint.m_edgeB.prev = null;
joint.m_edgeB.next = null;
_ASSERT && common.assert(this.m_jointCount > 0);
--this.m_jointCount;
// If the joint prevents collisions, then flag any contacts for filtering.
if (joint.m_collideConnected == false) {
let edge = bodyB.getContactList();
while (edge) {
if (edge.other == bodyA) {
// Flag the contact for filtering at the next time step (where either
// body is awake).
edge.contact.flagForFiltering();
}
edge = edge.next;
}
}
this.publish('remove-joint', joint);
}
/** @internal */
s_step: TimeStep = new TimeStep(); // reuse
/**
* Take a time step. This performs collision detection, integration, and
* constraint solution.
*
* Broad-phase, narrow-phase, solve and solve time of impacts.
*
* @param timeStep Time step, this should not vary.
*/
step(timeStep: number, velocityIterations?: number, positionIterations?: number): void {
this.publish('pre-step', timeStep);
if ((velocityIterations | 0) !== velocityIterations) {
// TODO: remove this in future
velocityIterations = 0;
}
velocityIterations = velocityIterations || this.m_velocityIterations;
positionIterations = positionIterations || this.m_positionIterations;
// If new fixtures were added, we need to find the new contacts.
if (this.m_newFixture) {
this.findNewContacts();
this.m_newFixture = false;
}
this.m_locked = true;
this.s_step.reset(timeStep);
this.s_step.velocityIterations = velocityIterations;
this.s_step.positionIterations = positionIterations;
this.s_step.warmStarting = this.m_warmStarting;
this.s_step.blockSolve = this.m_blockSolve;
// Update contacts. This is where some contacts are destroyed.
this.updateContacts();
// Integrate velocities, solve velocity constraints, and integrate positions.
if (this.m_stepComplete && timeStep > 0.0) {
this.m_solver.solveWorld(this.s_step);
// Synchronize fixtures, check for out of range bodies.
for (let b = this.m_bodyList; b; b = b.getNext()) {
// If a body was not in an island then it did not move.
if (b.m_islandFlag == false) {
continue;
}
if (b.isStatic()) {
continue;
}
// Update fixtures (for broad-phase).
b.synchronizeFixtures();
}
// Look for new contacts.
this.findNewContacts();
}
// Handle TOI events.
if (this.m_continuousPhysics && timeStep > 0.0) {
this.m_solver.solveWorldTOI(this.s_step);
}
if (this.m_clearForces) {
this.clearForces();
}
this.m_locked = false;
this.publish('post-step', timeStep);
}
/**
* @internal
* Call this method to find new contacts.
*/
findNewContacts(): void {
this.m_broadPhase.updatePairs(this.createContact);
}
/**
* @internal
* Callback for broad-phase.
*/
createContact = (proxyA: FixtureProxy, proxyB: FixtureProxy): void => {
const fixtureA = proxyA.fixture;
const fixtureB = proxyB.fixture;
const indexA = proxyA.childIndex;
const indexB = proxyB.childIndex;
const bodyA = fixtureA.getBody();
const bodyB = fixtureB.getBody();
// Are the fixtures on the same body?
if (bodyA == bodyB) {
return;
}
// TODO_ERIN use a hash table to remove a potential bottleneck when both
// bodies have a lot of contacts.
// Does a contact already exist?
let edge = bodyB.getContactList(); // ContactEdge
while (edge) {
if (edge.other == bodyA) {
const fA = edge.contact.getFixtureA();
const fB = edge.contact.getFixtureB();
const iA = edge.contact.getChildIndexA();
const iB = edge.contact.getChildIndexB();
if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) {
// A contact already exists.
return;
}
if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) {
// A contact already exists.
return;
}
}
edge = edge.next;
}
if (bodyB.shouldCollide(bodyA) == false) {
return;
}
if (fixtureB.shouldCollide(fixtureA) == false) {
return;
}
// Call the factory.
const contact = Contact.create(fixtureA, indexA, fixtureB, indexB);
if (contact == null) {
return;
}
// Insert into the world.
contact.m_prev = null;
if (this.m_contactList != null) {
contact.m_next = this.m_contactList;
this.m_contactList.m_prev = contact;
}
this.m_contactList = contact;
++this.m_contactCount;
}
/**
* @internal
* Removes old non-overlapping contacts, applies filters and updates contacts.
*/
updateContacts(): void {
// Update awake contacts.
let c;
let next_c = this.m_contactList;
while (c = next_c) {
next_c = c.getNext();
const fixtureA = c.getFixtureA();
const fixtureB = c.getFixtureB();
const indexA = c.getChildIndexA();
const indexB = c.getChildIndexB();
const bodyA = fixtureA.getBody();
const bodyB = fixtureB.getBody();
// Is this contact flagged for filtering?
if (c.m_filterFlag) {
if (bodyB.shouldCollide(bodyA) == false) {
this.destroyContact(c);
continue;
}
if (fixtureB.shouldCollide(fixtureA) == false) {
this.destroyContact(c);
continue;
}
// Clear the filtering flag.
c.m_filterFlag = false;
}
const activeA = bodyA.isAwake() && !bodyA.isStatic();
const activeB = bodyB.isAwake() && !bodyB.isStatic();
// At least one body must be awake and it must be dynamic or kinematic.
if (activeA == false && activeB == false) {
continue;
}
const proxyIdA = fixtureA.m_proxies[indexA].proxyId;
const proxyIdB = fixtureB.m_proxies[indexB].proxyId;
const overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB);
// Here we destroy contacts that cease to overlap in the broad-phase.
if (overlap == false) {
this.destroyContact(c);
continue;
}
// The contact persists.
c.update(this);
}
}
/**
* @internal
*/
destroyContact(contact: Contact): void {
Contact.destroy(contact, this);
// Remove from the world.
if (contact.m_prev) {
contact.m_prev.m_next = contact.m_next;
}
if (contact.m_next) {
contact.m_next.m_prev = contact.m_prev;
}
if (contact == this.m_contactList) {
this.m_contactList = contact.m_next;
}
--this.m_contactCount;
}
/**
* Called when two fixtures begin to touch.
*
* Implement contact callbacks to get contact information. You can use these
* results for things like sounds and game logic. You can also get contact
* results by traversing the contact lists after the time step. However, you
* might miss some contacts because continuous physics leads to sub-stepping.
* Additionally you may receive multiple callbacks for the same contact in a
* single time step. You should strive to make your callbacks efficient because
* there may be many callbacks per time step.
*
* Warning: You cannot create/destroy world entities inside these callbacks.
*/
on(name: 'begin-contact', listener: (contact: Contact) => void): World;
/**
* Called when two fixtures cease to touch.
*
* Implement contact callbacks to get contact information. You can use these
* results for things like sounds and game logic. You can also get contact
* results by traversing the contact lists after the time step. However, you
* might miss some contacts because continuous physics leads to sub-stepping.
* Additionally you may receive multiple callbacks for the same contact in a
* single time step. You should strive to make your callbacks efficient because
* there may be many callbacks per time step.
*
* Warning: You cannot create/destroy world entities inside these callbacks.
*/
on(name: 'end-contact', listener: (contact: Contact) => void): World;
/**
* This is called after a contact is updated. This allows you to inspect a
* contact before it goes to the solver. If you are careful, you can modify the
* contact manifold (e.g. disable contact). A copy of the old manifold is
* provided so that you can detect changes. Note: this is called only for awake
* bodies. Note: this is called even when the number of contact points is zero.
* Note: this is not called for sensors. Note: if you set the number of contact
* points to zero, you will not get an endContact callback. However, you may get
* a beginContact callback the next step.
*
* Warning: You cannot create/destroy world entities inside these callbacks.
*/
on(name: 'pre-solve', listener: (contact: Contact, oldManifold: Manifold) => void): World;
/**
* This lets you inspect a contact after the solver is finished. This is useful
* for inspecting impulses. Note: the contact manifold does not include time of
* impact impulses, which can be arbitrarily large if the sub-step is small.
* Hence the impulse is provided explicitly in a separate data structure. Note:
* this is only called for contacts that are touching, solid, and awake.
*
* Warning: You cannot create/destroy world entities inside these callbacks.
*/
on(name: 'post-solve', listener: (contact: Contact, impulse: ContactImpulse) => void): World;
/** Listener is called whenever a body is removed. */
on(name: 'remove-body', listener: (body: Body) => void): World;
/** Listener is called whenever a joint is removed implicitly or explicitly. */
on(name: 'remove-joint', listener: (joint: Joint) => void): World;
/** Listener is called whenever a fixture is removed implicitly or explicitly. */
on(name: 'remove-fixture', listener: (fixture: Fixture) => void): World;
/**
* Register an event listener.
*/
// tslint:disable-next-line:typedef
on(name, listener) {
if (typeof name !== 'string' || typeof listener !== 'function') {
return this;
}
if (!this._listeners) {
this._listeners = {};
}
if (!this._listeners[name]) {
this._listeners[name] = [];
}
this._listeners[name].push(listener);
return this;
}
off(name: 'begin-contact', listener: (contact: Contact) => void): World;
off(name: 'end-contact', listener: (contact: Contact) => void): World;
off(name: 'pre-solve', listener: (contact: Contact, oldManifold: Manifold) => void): World;
off(name: 'post-solve', listener: (contact: Contact, impulse: ContactImpulse) => void): World;
off(name: 'remove-body', listener: (body: Body) => void): World;
off(name: 'remove-joint', listener: (joint: Joint) => void): World;
off(name: 'remove-fixture', listener: (fixture: Fixture) => void): World;
/**
* Remove an event listener.
*/
// tslint:disable-next-line:typedef
off(name, listener) {
if (typeof name !== 'string' || typeof listener !== 'function') {
return this;
}
const listeners = this._listeners && this._listeners[name];
if (!listeners || !listeners.length) {
return this;
}
const index = listeners.indexOf(listener);
if (index >= 0) {
listeners.splice(index, 1);
}
return this;
}
publish(name: string, arg1?: any, arg2?: any, arg3?: any): number {
const listeners = this._listeners && this._listeners[name];
if (!listeners || !listeners.length) {
return 0;
}
for (let l = 0; l < listeners.length; l++) {
listeners[l].call(this, arg1, arg2, arg3);
}
return listeners.length;
}
/**
* @internal
*/
beginContact(contact: Contact): void {
this.publish('begin-contact', contact);
}
/**
* @internal
*/
endContact(contact: Contact): void {
this.publish('end-contact', contact);
}
/**
* @internal
*/
preSolve(contact: Contact, oldManifold: Manifold): void {
this.publish('pre-solve', contact, oldManifold);
}
/**
* @internal
*/
postSolve(contact: Contact, impulse: ContactImpulse): void {
this.publish('post-solve', contact, impulse);
}
/**
* Joints and fixtures are destroyed when their associated body is destroyed.
* Register a destruction listener so that you may nullify references to these
* joints and shapes.
*
* `function(object)` is called when any joint or fixture is about to
* be destroyed due to the destruction of one of its attached or parent bodies.
*/
/**
* Register a contact filter to provide specific control over collision.
* Otherwise the default filter is used (defaultFilter). The listener is owned
* by you and must remain in scope.
*
* Moved to Fixture.
*/
} | the_stack |
"use strict";
// uuid: b88b17e7-5918-44f7-82f7-f0e80c242a82
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
// @TODO: implement inject plugins
import * as sysFs from "fs";
import * as sysPath from "path";
import * as sysProcess from "process";
import { spawn as sysSpawn } from "child_process";
import { OptsParser } from "../shared/opts-parser.js";
import { fsix } from "../shared/vendor/fsix.js";
import { VERSION } from "../shared/version.js";
import { Consts } from "../shared/lib/consts.js";
import { RelConsts } from "../shared/rel-consts.js";
import { HttpServerEx } from "../shared/vendor/http-server-ex.js";
// @doc-name Command Line
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* **ABeamer** command line utility is used to:
*
* - create projects:
* ```shell
* abeamer create
* ```
* - launch a live server:
* ```shell
* abeamer serve
* ```
* - render the project to disk:
* ```shell
* abeamer render
* ```
* - create gifs:
* ```shell
* abeamer gif
* ```
* - create movies:
* ```shell
* abeamer movie
* ```
* ---------------------
* ## Examples
*
* - Create a TypeScript/JavaScript project.
* ```shell
* abeamer create foo --width 720 --height 480 --fps 20
* ```
* ---------------------
* - Create a JavaScript project without TypeScript.
* ```shell
* abeamer create foo-js --width 384 --height 288 --fps 30 --no-typescript
* ```
* ---------------------
* - Start the live server on port 9000. The url is `http://localhost:9000/`.
* ```shell
* abeamer serve
* ```
* ---------------------
* - Start the live server with list directory option if search part of url is `?dir`.
* The url is `http://localhost:9000/?dir`.
* ```shell
* abeamer serve --list-dir
* ```
* ---------------------
* - Start the live server on port 8000. The url is `http://localhost:8000/`.
* ```shell
* abeamer serve --port 8000
* ```
* ---------------------
* - Generate the animations in file image sequences from the project in the current directory.
* ```shell
* abeamer render
* ```
* ---------------------
* - Same as above, but deletes the previous images and the project is on directory `foo`.
* ```shell
* abeamer render --dp foo
* ```
* ---------------------
* - Same as the first render, but it renders from a live server.
* Required if it's loading `.json` files or is teleporting.
* ```shell
* abeamer render --url http://localhost:9000/foo/index.html
* ```
* ---------------------
* - Generate only the `story.json` file, it doesn't generates the file image sequence.
* This should be used only for testing. Teleporting should be done from the web browser library,
* and the teleported story via Ajax to the cloud.
* ```shell
* abeamer render --url http://localhost:9000/foo/index.html --teleport
* ```
* ---------------------
* - Same as the first render command, but with verbose logging.
* ```shell
* abeamer render --ll 3 --dp foo
* ```
* ---------------------
* - Same as the first render command, but uses slimerjs as the server.
* NOTE: slimerjs is on alpha version!
* ```shell
* abeamer render --server slimerjs foo
* ```
* ---------------------
* - Same as the previous render command, but sets the server executable.
* ```shell
* abeamer render --server slimerjs --server-exec ./slimerjs-path/src/slimerjs-node foo
* ```
* ---------------------
* - Create an animated gif from the previous generated image sequence on `foo/story-frames/story.gif`.
* Requires that imagemagick `convert` to be on the search path, or set `IM_CONVERT_BIN=<absolute-path-to-executable>`.
* ```shell
* abeamer gif foo
* ```
* ---------------------
* - Create an animated gif from the previous generated image sequence on `hello.gif`.
* ```shell
* abeamer gif foo --gif hello.gif
* ```
* ---------------------
* - Create an animated gif without looping.
* ```shell
* abeamer gif foo --loop 1
* ```
* ---------------------
* - Create an animated gif with a 25% scale frame size of the PNG sequence frame size.
* ```shell
* abeamer gif --gif-pre --scale 25% foo
* ```
* ---------------------
* - Create a movie from the previous generated image sequence on `foo/story-frames/movie.mp4`.
* Requires that `ffmpeg` to be on the search path, or set `FFMPEG_BIN=<absolute-path-to-executable>`.
* ```shell
* abeamer movie foo
* ```
* ---------------------
* - Create the movie `foo/story.webm`.
* ```shell
* abeamer movie foo --movie foo/story.webm
* ```
* ---------------------
* - Create a movie from the previous generated image sequence using `foo/bkg-movie.mp4` as a background.
* ```shell
* abeamer movie foo/ --bkg-movie foo/bkg-movie.mp4
* ```
* ---------------------
* - Create the movie a 50% scale frame size of the PNG sequence frame size.
* ```shell
* abeamer movie foo --scale 50%
* ```
*/
namespace Cli {
// ------------------------------------------------------------------------
// Global Vars
// ------------------------------------------------------------------------
const DO_PRINT_USAGE = 0;
const DO_RUN_COMMAND = 1;
const DO_EXIT = 2;
const DEFAULT_PORT = 9000;
const CMD_CHECK = 'check';
const CMD_CREATE = 'create';
const CMD_SERVE = 'serve';
const CMD_RENDER = 'render';
const CMD_GIF = 'gif';
const CMD_MOVIE = 'movie';
const DEFAULT_GIF_NAME = 'story.gif';
const DEFAULT_MOVIE_NAME = 'story.mp4';
const DEFAULT_BACKGROUND = 'white';
const MANUAL_BACKGROUND = 'manual';
let logLevel = Consts.LL_ERROR;
let isVerbose = false;
let cmdName = '';
let cmdParam = '';
const outArgs: string[] = [];
const isWin = sysProcess.platform === 'win32';
const argOpts = OptsParser.argOpts;
argOpts['port'] = {
param: 'int', desc:
`port for serve command. default is ${DEFAULT_PORT}`,
};
argOpts['gif'] = {
param: 'string', desc:
`output gif filename. default is ${DEFAULT_GIF_NAME}`,
};
argOpts['movie'] = {
param: 'string', desc:
`output movie filename. default is ${DEFAULT_MOVIE_NAME}`,
};
argOpts['bkgMovie'] = {
param: 'string', desc:
`movie filename to be used as background to blend with transparent images`,
};
argOpts['noPlugins'] = {
desc:
`creates a project without plugins`,
};
argOpts['noTypescript'] = {
desc:
`creates a project without TypeScript files`,
};
argOpts['listDir'] = {
desc:
`serve command lists the directory contents if url has the querystring '?dir'`,
};
argOpts['loop'] = {
param: 'string', desc:
`defines how many times a gif will loop. set to -1 if you don't won't it to loop`,
};
argOpts['moviePre'] = {
param: 'array', allowOption: true, desc:
`arguments to be passed to ffmpeg before the arguments passed by abeamer`,
};
argOpts['moviePost'] = {
param: 'array', allowOption: true, desc:
`arguments to be passed to ffmpeg after the arguments passed by abeamer`,
};
argOpts['gifPre'] = {
param: 'array', allowOption: true, desc:
`arguments to be passed to gif generator(convert) before the arguments passed by abeamer`,
};
argOpts['gifPost'] = {
param: 'array', allowOption: true, desc:
`arguments to be passed to gif generator(convert) after the arguments passed by abeamer`,
};
argOpts['gifBackground'] = {
param: 'string', desc:
`background color used to replace the alpha channel in gif generation.
if this is value is set to "${MANUAL_BACKGROUND}" , no parameters relating are passed to the gif generator.
default is ${MANUAL_BACKGROUND}`,
};
// ------------------------------------------------------------------------
// Print Usage
// ------------------------------------------------------------------------
function printUsage(): void {
console.log(`abeamer [command] [options] [project-name|report-name]
The commands are:
${CMD_CHECK} checks if the all requirements are installed and configured
${CMD_CREATE} creates a project with project-name
${CMD_SERVE} starts a live server. Use it in case you need to load the config from JSON file
${CMD_RENDER} runs your project in the context of the headless browser.
${CMD_GIF} creates an animated gif from the project-name or report-name
${CMD_MOVIE} creates a movie from the project-name or report-name
e.g.
echo "checks if chrome, puppeteer, imagemagick, ffmpeg are installed and configured"
abeamer ${CMD_CHECK}
echo "create folder foo and copy necessary files"
abeamer ${CMD_CREATE} --width 640 --height 480 --fps 25 foo
cd foo
echo "start a live server"
echo "only required if you need to load your configuration from json file"
abeamer ${CMD_SERVE}
echo "generates the png files and a report on story-frames folder"
abeamer ${CMD_RENDER}
echo "creates story.gif file on story-frames folder"
abeamer ${CMD_GIF}
echo "creates story.mp4 file on story-frames folder"
abeamer ${CMD_MOVIE}
For more information, read:
https://www.abeamer.com/docs/latest/end-user/en/site/abeamer-cli/
`);
OptsParser.printUsage();
}
// ------------------------------------------------------------------------
// Fix Folder Name
// ------------------------------------------------------------------------
// function fixFolderName(folderName: string): string {
// folderName = fsix.toPosixSlash(folderName);
// if (folderName.search(/^.\/?$/) !== -1) {
// sysProcess.cwd()
// }
// return folderName;
// }
// ------------------------------------------------------------------------
// Parse Arguments
// ------------------------------------------------------------------------
function parseArguments(): uint {
const args: string[] = sysProcess.argv;
let argI = 1;
// @TODO: Improve this code
while (args[argI - 1].search(/abeamer/) === -1) { argI++; }
cmdName = args[argI++];
if (!cmdName) {
return DO_PRINT_USAGE;
} else if (cmdName === '--version') {
console.log(VERSION);
return DO_EXIT;
}
return OptsParser.iterateArgOpts(true, () => args[argI++],
(option, value) => {
switch (option) {
case '@param':
cmdParam = value as string;
outArgs.push(cmdParam);
return;
case 'version':
console.log(VERSION);
return DO_EXIT;
case 'll':
logLevel = value as int;
isVerbose = logLevel >= Consts.LL_VERBOSE;
if (isVerbose) {
console.log(`Args: [${args.join('],[')}]`);
console.log(`Current Path: ${sysProcess.cwd()}`);
}
break;
}
switch (cmdName) {
case CMD_RENDER:
outArgs.push('--' + option);
if (value) {
/* if (OptsParser.argOpts[option].param === 'string') {
value = `"${value}"`;
} */
outArgs.push(value as string);
}
break;
}
},
) || DO_RUN_COMMAND;
}
// ------------------------------------------------------------------------
// Runs External Commands
// ------------------------------------------------------------------------
function runSpawn(cmdLine: string, args: string[], callback?): void {
if (isVerbose) {
console.log(`spawn cmdLine: ${cmdLine}`);
console.log(`args: ${args.join(' ')}`);
}
const ls = sysSpawn(cmdLine, args);
ls.stdout.on('data', (data) => {
if (logLevel >= Consts.LL_SILENT) { console.log(data.toString()); }
});
ls.stderr.on('data', (data) => {
if (logLevel >= Consts.LL_SILENT) { console.error(data.toString()); }
});
ls.on('close', (_code) => {
callback();
});
}
// ------------------------------------------------------------------------
// Command: Check
// ------------------------------------------------------------------------
function commandCheck(): void {
let checkCount = 0;
const TOTAL_CHECK_COUNT = 5;
function displayCheck(what: string, passed: boolean, failedMsg: string): void {
checkCount++;
console.log(`${checkCount}. Check: ${what} --> ${passed ? 'OK' : 'Failed'}`);
if (!passed) {
console.log(' TODO:' + failedMsg + '\n');
}
if (checkCount === TOTAL_CHECK_COUNT) {
console.log('\n');
}
}
function addToStartUp(passed: boolean, key: string, value: string,
failedMsg: string): void {
displayCheck(`${key}=${value}`, passed, `
${failedMsg}
Add to the shell startup script:
${isWin ? 'SET' : 'export'} ${key}=${value}`);
}
function checkProgramIsValid(envKey: string, appName: string,
versionParam: string, matchRegEx: RegExp, requireMsg: string): void {
function displayResult(passed: boolean): void {
displayCheck(appName, passed, `
ABeamer requires ${requireMsg}
Either add the executable to the system path, or add to the shell startup script:
${isWin ? 'set' : 'export'} ${envKey}=<absolute-path-to-${appName}>`);
}
const envValue = sysProcess.env[envKey];
if (!envValue) {
fsix.runExternal(`${appName} ${versionParam}`,
(_error, stdout, stderr) => {
displayResult(stderr === '' && stdout.match(matchRegEx));
});
} else {
displayResult(sysFs.existsSync(envValue));
}
}
console.log(`\nChecking:\n`);
addToStartUp((sysProcess.env['PUPPETEER_SKIP_CHROMIUM_DOWNLOAD'] || '').toLowerCase() === 'true',
'PUPPETEER_SKIP_CHROMIUM_DOWNLOAD', 'TRUE',
'by default puppeteer downloads Chromium which is doesn\'t support many features');
const chromeBin = sysProcess.env['CHROME_BIN'];
if (!chromeBin) {
addToStartUp(false, 'CHROME_BIN', '<chrome-path>',
'puppeteer uses by default Chromium, set CHROME_BIN with the absolute path to chrome web browser executable');
} else {
addToStartUp(sysFs.existsSync(chromeBin), 'CHROME_BIN', '<chrome-path>',
'CHROME_BIN points to a missing chrome executable');
}
checkProgramIsValid('FFMPEG_BIN', 'ffmpeg', '-version', /ffmpeg version/,
'ffmpeg to generate movies');
checkProgramIsValid('IM_CONVERT_BIN', 'convert', '--version', /Version: ImageMagick/,
'ImageMagick convert program to generate gifs');
let puppeteer;
try {
puppeteer = require('puppeteer');
} catch (error) {
}
displayCheck('puppeteer', puppeteer, `
ABeamer requires puppeteer. Install using the following command
npm i puppeteer`);
}
// ------------------------------------------------------------------------
// Command: Create
// ------------------------------------------------------------------------
function commandCreate(): void {
const projName = fsix.toPosixSlash(cmdParam);
if (!projName) {
throw `Missing project name`;
}
if (projName[0] === '-' || projName.search(/[\"\'\?\*\+]/) !== -1
|| projName.search(/^[\.\/]+$/) !== -1) {
throw `Error: ${projName} is not valid project name`;
}
if (sysFs.existsSync(projName)) {
throw `Error: Project ${projName} already exists`;
}
if (projName.includes('/')) {
const dirname = sysPath.posix.dirname(projName);
fsix.mkdirpSync(dirname);
}
const ROOT_PATH = fsix.toPosixSlash(__dirname) + '/..';
const TEMPLATE_PATH = ROOT_PATH + '/gallery/hello-world';
const LIB_PATH = ROOT_PATH + '/client/lib';
const width = argOpts.width.value || RelConsts.DEFAULT_WIDTH;
const height = argOpts.height.value || RelConsts.DEFAULT_HEIGHT;
const fps = argOpts.fps.value || RelConsts.DEFAULT_FPS;
const noPlugins = argOpts['noPlugins'].hasOption;
const noTypescript = argOpts['noTypescript'].hasOption;
copyTree(TEMPLATE_PATH, projName, (text, fileName) => {
const fileBase = sysPath.basename(fileName);
switch (fileBase) {
case 'main.js':
case 'main.ts':
if (noTypescript) {
text = text.replace(/^.*sourceMappingURL=.*$/m, '');
}
text = text.replace(/createStory\([^)]*\)/, `createStory(/*FPS:*/${fps})`);
break;
case 'abeamer.ini':
text = text.replace(/width:\s*\d+/, `width: ${width}`)
.replace(/height:\s*\d+/, `height: ${height}`);
break;
case 'main.min.css':
text = text.replace(/.abeamer-scene{width:\d+px;height:\d+px}/,
`.abeamer-scene{width:${width}px;height:${height}px}`);
break;
case 'index.html':
// inserts the plugins.
if (!noPlugins) {
const plugins = fsix.loadJsonSync(`${ROOT_PATH}/client/lib/plugins/plugins-list.json`);
let pre = '';
let post = '';
text.replace(/^(.*)js\/abeamer\.min\.js(.*)$/m, (_app, _pre, _post) => {
pre = _pre;
post = _post;
return '';
});
text = text.replace(/^(.*js\/main\.js.*)$/m, (all) => {
return `\n <!-- remove the unnecessary plugins -->\n`
+ plugins.map(plugin => `${pre}plugins/${plugin}/${plugin}.js${post}`).join('\n')
+ '\n\n' + all;
});
}
break;
}
return text;
},
(fileBase: string) => {
if (noTypescript && fileBase.match(/(?:js\.map|\.ts|tsconfig\.json)$/)) { return false; }
return true;
});
copyTree(LIB_PATH, `${projName}/abeamer`, undefined,
(fileBase: string) => {
if (noTypescript && fileBase.match(/(?:typings|\.ts)$/)) { return false; }
if (noPlugins && fileBase.match(/plugins$/)) { return false; }
return !fileBase.match(/plugins-list\.json$/);
});
if (logLevel > Consts.LL_SILENT) {
console.log(`Project ${projName} created.
- frame-width: ${width}px
- frame-height: ${height}px
- fps: ${fps}
To modify the the frame dimensions, edit [abeamer.ini] and recompile the [css/main.scss] file.
To modify the fps, edit the [js/main.ts] file.
`);
}
}
/**
* Copies a tree structure from the `src` to `dst`,
* allowing to modify the content via `onCopyText` callback,
* and determine if copying a certain file or folder is allowed via `allowCopy`.
*/
function copyTree(srcPath: string, dstPath: string,
onCopyText?: (text: string, fileBase: string) => string,
allowCopy?: (fileBase: string) => boolean) {
if (isVerbose) {
console.log(`Copying Directory ${srcPath} to ${dstPath}`);
}
fsix.mkdirpSync(dstPath);
sysFs.readdirSync(srcPath).forEach(fileBase => {
if (allowCopy && !allowCopy(fileBase)) { return; }
const srcFileName = `${srcPath}/${fileBase}`;
const dstFileName = `${dstPath}/${fileBase}`;
const stats = sysFs.statSync(srcFileName);
if (stats.isFile()) {
if (isVerbose) {
console.log(`Copying ${srcFileName} to ${dstFileName}`);
}
let data = fsix.readUtf8Sync(srcFileName);
if (onCopyText) {
data = onCopyText(data, fileBase);
}
sysFs.writeFileSync(dstFileName, data);
} else if (stats.isDirectory()) {
copyTree(srcFileName, dstFileName, onCopyText, allowCopy);
}
});
}
// ------------------------------------------------------------------------
// Serve
// ------------------------------------------------------------------------
function commandServe(): void {
const hasMarked = sysFs.existsSync(sysPath.posix.join(__dirname,
'../node_modules/marked/bin/marked'));
const hasHighlightJs = sysFs.existsSync(sysPath.posix.join(__dirname,
'../node_modules/highlight.js/lib/index.js'));
const port = argOpts['port'].value as int || DEFAULT_PORT;
const allowDirListing = argOpts['listDir'].hasOption;
new HttpServerEx.ServerEx(port, isVerbose, 'EXIT_SERVER',
allowDirListing, hasMarked, hasHighlightJs).start();
if (logLevel >= Consts.LL_SILENT) {
if (hasMarked) {
console.log(`Using markdown compiler`);
}
console.log(`Serving on http://localhost:${port}/`);
if (allowDirListing) {
console.log(`Directory listing on http://localhost:${port}/?dir`);
}
}
}
// ------------------------------------------------------------------------
// Command: Render
// ------------------------------------------------------------------------
function commandRender(): void {
const serverName = (OptsParser.argOpts.server.value as string
|| RelConsts.DEFAULT_SERVER).toLowerCase();
if (RelConsts.SUPPORTED_SERVERS.indexOf(serverName) === -1) {
throw `Unknown ${serverName}`;
}
// if use hasn't provided the folder name nor config file
if (!cmdParam && !argOpts.config.value && !argOpts.url.value) { outArgs.push('.'); }
// adding this suffix, it solves the conflict of slimerjs `--config`.
// the `opt-parser.ts` will remove this extra suffix during parsing the name
const configArgIndex = outArgs.indexOf('--config');
if (configArgIndex !== -1) {
outArgs[configArgIndex] = outArgs[configArgIndex] + '__2';
}
outArgs.splice(0, 0, `${fsix.toPosixSlash(__dirname)}/../server/server-agent-${serverName}.js`);
const cmdLine = argOpts.serverExec.value as string ||
(RelConsts.NODE_SERVERS.indexOf(serverName) === -1 ? serverName : 'node');
runSpawn(cmdLine, outArgs, () => {
if (logLevel > Consts.LL_SILENT) { console.log(`Server finished`); }
});
}
// ------------------------------------------------------------------------
// getReport
// ------------------------------------------------------------------------
interface Report {
fps: uint;
width: uint;
height: uint;
dirname: string;
framespattern: string;
}
function getReport(): Report {
let reportFileName = fsix.toPosixSlash(cmdParam || '.');
const realReportFileName =
sysPath.posix.join(reportFileName, 'story-frames/frame-report.json');
// in case the user param is the project folder
if (sysFs.existsSync(realReportFileName)) {
reportFileName = realReportFileName;
}
if (isVerbose) {
console.log(`reportFileName: ${reportFileName}`);
console.log(`realReportFileName: ${realReportFileName}`);
}
if (!sysFs.existsSync(reportFileName)) {
throw `Report file ${reportFileName} doesn't exist`;
}
const report: Report = fsix.loadJsonSync(reportFileName);
report.dirname = sysPath.dirname(reportFileName);
if (isVerbose) { console.log(`report path: ${report.dirname}`); }
// handle relative paths
if (report.framespattern.substr(0, 2) === './') {
report.framespattern = report.dirname + '/' + report.framespattern.substr(2);
}
return report;
}
// ------------------------------------------------------------------------
// Command: Gif
// ------------------------------------------------------------------------
function commandGif(): void {
const report = getReport();
const gifFileName = argOpts['gif'].value as string
|| `${report.dirname}/${DEFAULT_GIF_NAME}`;
const toOptimize = true;
const cmdLine = sysProcess.env['IM_CONVERT_BIN'] || 'convert';
let args = ['-delay', `1x${report.fps}`];
const scale = OptsParser.computeScale(report.width, report.height);
if (scale) {
args.push('-scale', scale.join('x'));
}
const loop = argOpts['loop'].value as string || '0';
args.push('-loop', loop);
if (toOptimize) {
args.push('-strip', '-layers', 'optimize');
const gifBackground = argOpts['gifBackground'].value || DEFAULT_BACKGROUND;
if (gifBackground !== MANUAL_BACKGROUND) {
args.push('-background', gifBackground as string, '-alpha', 'remove');
}
}
args.push(report.framespattern.replace(/\%\d*d/, '*'), gifFileName);
if (argOpts['gifPre'].multipleValue) {
args = [...argOpts['gifPre'].multipleValue as string[], ...args];
}
if (argOpts['gifPost'].multipleValue) {
args = [...args, ...argOpts['gifPost'].multipleValue as string[]];
}
if (isVerbose) {
console.log(`\n${cmdLine} ${args.join(' ')}\n`);
}
runSpawn(cmdLine, args, () => {
if (logLevel > Consts.LL_SILENT) { console.log(`Created gif ${gifFileName}`); }
});
}
// ------------------------------------------------------------------------
// Command: Movie
// ------------------------------------------------------------------------
function commandMovie(): void {
const report = getReport();
const movieFileName = argOpts['movie'].value as string
|| `${report.dirname}/${DEFAULT_MOVIE_NAME}`;
const bkgMovieFileName = argOpts['bkgMovie'].value as string;
const cmdLine = sysProcess.env['FFMPEG_BIN'] || 'ffmpeg';
const scale = OptsParser.computeScale(report.width, report.height);
let args = [
'-r', report.fps.toString(),
'-f', 'image2',
];
if (!scale) {
args.push('-s', `${report.width}x${report.height}`);
}
args.push(
'-i', report.framespattern,
'-y', // overwrites automatically
);
if (scale) {
args.push('-vf', `scale=${scale.join('x')}`);
}
/* spell-checker: disable */
if (bkgMovieFileName) {
args.push('-vf', `movie=${bkgMovieFileName},hue=s=1[bg];[in]setpts=PTS,scale=-1:-1`
+ `,pad=iw:ih:0:0:color=yellow[m]; [bg][m]overlay=shortest=1:x=0:y=0`);
}
const ext = sysPath.extname(movieFileName);
let codec = '';
switch (ext) {
case '.mp4': codec = 'libx264'; break;
case '.webm': codec = 'libvpx-vp9'; break;
}
if (codec) {
args.push('-vcodec', codec);
}
args.push(movieFileName);
if (argOpts['moviePre'].multipleValue) {
args = [...argOpts['moviePre'].multipleValue as string[], ...args];
}
if (argOpts['moviePost'].multipleValue) {
args = [...args, ...argOpts['moviePost'].multipleValue as string[]];
}
if (isVerbose) {
console.log(`\next: ${ext}\n`);
console.log(`cmdLine:[${cmdLine} ${args.join(' ')}]\n\n`);
}
runSpawn(cmdLine, args, () => {
if (logLevel > Consts.LL_SILENT) { console.log(`Created movie ${movieFileName}`); }
});
}
// ------------------------------------------------------------------------
// Main Body
// ------------------------------------------------------------------------
function main() {
switch (parseArguments()) {
case DO_PRINT_USAGE:
printUsage();
break;
case DO_RUN_COMMAND:
if (isVerbose) {
console.log(`Run Command: ${cmdName}`);
}
switch (cmdName) {
case CMD_CHECK:
commandCheck();
break;
case CMD_CREATE:
commandCreate();
break;
case CMD_SERVE:
commandServe();
break;
case CMD_RENDER:
commandRender();
break;
case CMD_GIF:
commandGif();
break;
case CMD_MOVIE:
commandMovie();
break;
default:
throw `Unknown command ${cmdName}`;
}
break;
}
}
try {
main();
} catch (err) {
console.error(err.message || err.toString());
}
} | the_stack |
import type { ComputedRef } from "@vue/reactivity";
import { computed } from "@vue/runtime-core";
import { toGP } from "../core/geometry";
import type { GlobalPoint } from "../core/geometry";
import type { AssetListMap } from "../core/models/types";
import { Store } from "../core/store";
import { sendClientLocationOptions } from "../game/api/emits/client";
import { sendLabelAdd, sendLabelDelete, sendLabelFilterAdd, sendLabelFilterDelete } from "../game/api/emits/labels";
import { sendLocationChange } from "../game/api/emits/location";
import { sendMarkerCreate, sendMarkerRemove } from "../game/api/emits/marker";
import { sendNewNote, sendRemoveNote, sendUpdateNote } from "../game/api/emits/note";
import { sendChangePlayerRole } from "../game/api/emits/players";
import { sendRoomKickPlayer, sendRoomLock } from "../game/api/emits/room";
import { showClientRect } from "../game/client";
import type { Note } from "../game/models/general";
import type { Player } from "../game/models/player";
import type { ServerShape } from "../game/models/shapes";
import { setCenterPosition } from "../game/position";
import type { Label } from "../game/shapes/interfaces";
import { router } from "../router";
import { coreStore } from "./core";
import { floorStore } from "./floor";
import { UuidMap } from "./shapeMap";
interface GameState {
isConnected: boolean;
isDm: boolean;
isFakePlayer: boolean;
showUi: boolean;
boardInitialized: boolean;
// Player
players: Player[];
ownedTokens: Set<string>;
activeTokenFilters: Set<string> | undefined;
// Room
roomName: string;
roomCreator: string;
invitationCode: string;
publicName: string;
isLocked: boolean;
assets: AssetListMap;
annotations: Set<string>;
markers: Set<string>;
notes: Note[];
clipboard: ServerShape[];
clipboardPosition: GlobalPoint;
labels: Map<string, Label>;
filterNoLabel: boolean;
labelFilters: string[];
}
class GameStore extends Store<GameState> {
activeTokens: ComputedRef<Set<string>>;
constructor() {
super();
this.activeTokens = computed(() => {
if (this._state.activeTokenFilters !== undefined) return this._state.activeTokenFilters;
return this._state.ownedTokens;
});
}
protected data(): GameState {
return {
isConnected: false,
isDm: false,
isFakePlayer: false,
showUi: true,
boardInitialized: false,
players: [],
ownedTokens: new Set(),
activeTokenFilters: undefined,
roomName: "",
roomCreator: "",
invitationCode: "",
publicName: window.location.host,
isLocked: false,
assets: new Map(),
annotations: new Set(),
markers: new Set(),
notes: [],
clipboard: [],
clipboardPosition: toGP(0, 0),
labels: new Map(),
filterNoLabel: false,
labelFilters: [],
};
}
clear(): void {
this._state.activeTokenFilters?.clear();
this._state.ownedTokens.clear();
this._state.annotations.clear();
this._state.notes = [];
this._state.markers.clear();
this._state.boardInitialized = false;
}
// GENERAL STATE
setConnected(connected: boolean): void {
this._state.isConnected = connected;
}
setBoardInitialized(initialized: boolean): void {
this._state.boardInitialized = initialized;
}
setDm(isDm: boolean): void {
this._state.isDm = isDm;
}
setFakePlayer(isFakePlayer: boolean): void {
this._state.isFakePlayer = isFakePlayer;
this._state.isDm = !isFakePlayer;
floorStore.invalidateAllFloors();
}
toggleUi(): void {
this._state.showUi = !this._state.showUi;
}
// PLAYERS
setPlayers(players: Player[]): void {
this._state.players = players;
}
addPlayer(player: Player): void {
this._state.players.push(player);
}
updatePlayersLocation(
players: string[],
location: number,
sync: boolean,
targetPosition?: { x: number; y: number },
): void {
for (const player of this._state.players) {
if (players.includes(player.name)) {
player.location = location;
}
}
this._state.players = [...this._state.players];
if (sync) sendLocationChange({ location, users: players, position: targetPosition });
}
kickPlayer(playerId: number): void {
const player = this._state.players.find((p) => p.id === playerId);
if (player === undefined) return;
if (player.name === router.currentRoute.value.params.creator && coreStore.state.username !== player.name) {
return;
}
sendRoomKickPlayer(playerId);
this._state.players = this._state.players.filter((p) => p.id !== playerId);
}
setPlayerRole(playerId: number, role: number, sync: boolean): void {
const player = this._state.players.find((p) => p.id === playerId);
if (player === undefined) return;
if (player.name === router.currentRoute.value.params.creator && coreStore.state.username !== player.name) {
return;
}
player.role = role;
if (sync) sendChangePlayerRole({ player: playerId, role });
}
setShowPlayerRect(playerId: number, showPlayerRect: boolean): void {
const player = this._state.players.find((p) => p.id === playerId);
if (player === undefined) return;
player.showRect = showPlayerRect;
showClientRect(playerId, showPlayerRect);
}
// ROOM
setRoomName(name: string): void {
this._state.roomName = name;
}
setRoomCreator(creator: string): void {
this._state.roomCreator = creator;
}
setInvitationCode(invitationCode: string): void {
this._state.invitationCode = invitationCode;
}
setPublicName(name: string): void {
if (!name.length) return;
this._state.publicName = name;
}
setIsLocked(isLocked: boolean, sync: boolean): void {
this._state.isLocked = isLocked;
if (sync) sendRoomLock(isLocked);
}
// ACCESS
setActiveTokens(...tokens: string[]): void {
this._state.activeTokenFilters = new Set(tokens);
floorStore.invalidateLightAllFloors();
}
unsetActiveTokens(): void {
this._state.activeTokenFilters = undefined;
floorStore.invalidateLightAllFloors();
}
addActiveToken(token: string): void {
if (this._state.activeTokenFilters === undefined) return;
this._state.activeTokenFilters.add(token);
if (this._state.activeTokenFilters.size === this._state.ownedTokens.size)
this._state.activeTokenFilters = undefined;
floorStore.invalidateLightAllFloors();
}
removeActiveToken(token: string): void {
if (this._state.activeTokenFilters === undefined) {
this._state.activeTokenFilters = new Set([...this._state.ownedTokens]);
}
this._state.activeTokenFilters.delete(token);
floorStore.invalidateLightAllFloors();
}
addOwnedToken(token: string): void {
this._state.ownedTokens.add(token);
}
removeOwnedToken(token: string): void {
this._state.ownedTokens.delete(token);
}
// ASSETS
setAssets(assets: AssetListMap): void {
this._state.assets = assets;
}
// ANNOTATIONS
addAnnotation(shape: string): void {
this._state.annotations.add(shape);
}
removeAnnotation(shape: string): void {
this._state.annotations.delete(shape);
}
// MARKERS
newMarker(marker: string, sync: boolean): void {
if (!this._state.markers.has(marker)) {
this._state.markers.add(marker);
if (sync) sendMarkerCreate(marker);
}
}
jumpToMarker(marker: string): void {
const shape = UuidMap.get(marker);
if (shape == undefined) return;
setCenterPosition(shape.center());
sendClientLocationOptions();
floorStore.invalidateAllFloors();
}
removeMarker(marker: string, sync: boolean): void {
if (this._state.markers.has(marker)) {
this._state.markers.delete(marker);
if (sync) sendMarkerRemove(marker);
}
}
// NOTES
newNote(note: Note, sync: boolean): void {
this._state.notes.push(note);
if (sync) sendNewNote(note);
}
updateNote(note: Note, sync: boolean): void {
const actualNote = this._state.notes.find((n) => n.uuid === note.uuid);
if (actualNote === undefined) return;
actualNote.title = note.title;
actualNote.text = note.text;
if (sync) sendUpdateNote(note);
}
removeNote(note: Note, sync: boolean): void {
this._state.notes = this._state.notes.filter((n) => n.uuid !== note.uuid);
if (sync) sendRemoveNote(note.uuid);
}
// CLIPBOARD
setClipboard(clipboard: ServerShape[]): void {
this._state.clipboard = clipboard;
}
setClipboardPosition(position: GlobalPoint): void {
this._state.clipboardPosition = position;
}
// LABELS
addLabel(label: Label, sync: boolean): void {
this._state.labels.set(label.uuid, label);
if (sync) sendLabelAdd(label);
}
addLabelFilter(filter: string, sync: boolean): void {
this._state.labelFilters.push(filter);
floorStore.invalidateAllFloors();
if (sync) sendLabelFilterAdd(filter);
}
setLabelFilters(filters: string[]): void {
this._state.labelFilters = filters;
}
removeLabelFilter(filter: string, sync: boolean): void {
const idx = this._state.labelFilters.indexOf(filter);
if (idx >= 0) {
this._state.labelFilters.splice(idx, 1);
floorStore.invalidateAllFloors();
if (sync) sendLabelFilterDelete(filter);
}
}
setLabelVisibility(uuid: string, visible: boolean): void {
if (!this._state.labels.has(uuid)) return;
this._state.labels.get(uuid)!.visible = visible;
}
deleteLabel(uuid: string, sync: boolean): void {
if (!this._state.labels.has(uuid)) return;
const label = this._state.labels.get(uuid)!;
for (const shape of UuidMap.values()) {
const i = shape.labels.indexOf(label);
if (i >= 0) {
shape.labels.splice(i, 1);
shape.layer.invalidate(false);
}
}
this._state.labels.delete(uuid);
if (sync) sendLabelDelete({ uuid });
}
}
export const gameStore = new GameStore();
(window as any).gameStore = gameStore; | the_stack |
import 'reflect-metadata';
import { Injector, rootInjector } from './injector';
import {
TInjectTokenProvider,
IProviderClass,
TProviders,
TInjectItem,
Type,
} from '../types';
import {
metadataOfInjectable,
metadataOfOptional,
metadataOfHost,
metadataOfSelf,
metadataOfSkipSelf,
metadataOfInject,
metadataOfPropInject,
metadataOfPropHost,
metadataOfPropOptional,
metadataOfPropSelf,
metadataOfPropSkipSelf,
} from './metadata';
import { resolveParameterInjectMap, resolvePropertyInjectMap } from './base-inject-factory';
/**
* bind property for @Inject
*
* @param {Function} _constructor
* @param {*} factoryInstance
* @param {Injector} [injector]
*/
function bindProperty(_constructor: Function, factoryInstance: any, injector?: Injector) {
// @Inject 属性注入
const injectList: TInjectItem[] = Reflect.getMetadata(metadataOfPropInject, _constructor) || [];
// 干预等级 @SkipSelf > @Self > @Host > @Optional
const skipSelfList: string[] = Reflect.getMetadata(metadataOfPropSkipSelf, _constructor) || [];
const selfList: string[] = Reflect.getMetadata(metadataOfPropSelf, _constructor) || [];
const hostList: string[] = Reflect.getMetadata(metadataOfPropHost, _constructor) || [];
const optionalList: string[] = Reflect.getMetadata(metadataOfPropOptional, _constructor) || [];
// 使用自定义注解,还可以定义是否解决注入
resolvePropertyInjectMap.forEach((resolveInject, key) => {
const list: { property: string, decoratorArgument: any }[] = Reflect.getMetadata(key, _constructor) || [];
list.forEach(inject => {
let bubblingLayer: number | 'always' = 'always';
if (hostList.indexOf(inject.property) !== -1) bubblingLayer = 1;
if (selfList.indexOf(inject.property) !== -1) bubblingLayer = 0;
let findInjector = injector;
if (skipSelfList.indexOf(inject.property) !== -1) findInjector = injector.parentInjector;
const findProvider = resolveInject({
key,
property: inject.property,
decoratorArgument: inject.decoratorArgument,
bubblingLayer,
}, findInjector);
if (!findProvider) {
// use @Optional will return null
if (optionalList.indexOf(inject.property) !== -1) {
factoryInstance[inject.property] = null;
return;
}
throw new Error(`Instance of ${key} can't be ${findProvider}`);
}
factoryInstance[inject.property] = findProvider;
});
});
if (injectList && injectList.length > 0) {
injectList.forEach(inject => {
let bubblingLayer: number | 'always' = 'always';
if (hostList.indexOf(inject.property) !== -1) bubblingLayer = 1;
if (selfList.indexOf(inject.property) !== -1) bubblingLayer = 0;
// 构建冒泡开始的injector
let findInjector = injector;
if (skipSelfList.indexOf(inject.property) !== -1) findInjector = injector.parentInjector;
if (inject && inject.injector) findInjector = inject.injector;
let findProvider = findInjector.getInstance(inject.token, bubblingLayer);
if (!findProvider) {
// use @Optional will return null
if (optionalList.indexOf(inject.property) !== -1) {
factoryInstance[inject.property] = null;
return;
}
findProvider = getService(findInjector, inject.token, _constructor, bubblingLayer);
}
factoryInstance[inject.property] = findProvider;
});
}
}
/**
* get service from Injector
*
* @param {Injector} [injector]
* @param {*} [key]
* @param {*} [_constructor]
* @param {(number | 'always')} [bubblingLayer='always']
* @returns
*/
export function getService(injector?: Injector, key?: any, _constructor?: any, bubblingLayer: number | 'always' = 'always') {
const findProvider: TInjectTokenProvider = injector.getProvider(key, bubblingLayer);
if (findProvider) {
let findService: any;
if (findProvider.useClass) {
findService = findProvider.useClass;
} else if (findProvider.useValue) {
return findProvider.useValue;
} else if (findProvider.useFactory) {
const factoryArgs = argumentsCreator(_constructor, injector, findProvider.deps);
return findProvider.useFactory(...factoryArgs);
} else findService = findProvider;
const serviceParentInjector = injector.getParentInjectorOfProvider(key, bubblingLayer);
const serviceInjector = serviceParentInjector.fork();
if (findService.isSingletonMode === false) {
return NvInstanceFactory(findService, null, serviceInjector, findProvider.deps);
} else {
const serviceInStance = NvInstanceFactory(findService, null, serviceInjector, findProvider.deps);
injector.setInstance(key, serviceInStance);
return serviceInStance;
}
} else {
throw new Error(`In injector could'nt find ${key}`);
}
}
/**
* format providers for @NvModule @Directive @Component
*
* @export
* @param {TProviders} [providers]
* @returns {TProviders}
*/
export function providersFormater(providers: TProviders): TProviders {
if (!providers) return [];
return providers.map(provider => {
if ((provider as TInjectTokenProvider).provide) {
if (!(provider as TInjectTokenProvider).useClass && !(provider as TInjectTokenProvider).useValue && !(provider as TInjectTokenProvider).useFactory) {
return { ...provider, useClass: (provider as TInjectTokenProvider).provide };
} else {
return provider;
}
} else {
return { provide: provider as Function, useClass: provider as Function };
}
});
}
/**
* Create arguments for injectionCreator with injector and depsToken
*
* @param {Function} _constructor
* @param {Injector} [injector]
* @param {any[]} [depsToken]
* @returns {any[]}
*/
function argumentsCreator(_constructor: Function, injector?: Injector, depsToken?: any[]): any[] {
if (!depsToken || (Array.isArray(depsToken) && depsToken.length === 0)) return [];
const args: any[] = [];
// 干预等级 @SkipSelf > @Self > @Host > @Optional
const skipSelfList: number[] = Reflect.getMetadata(metadataOfSkipSelf, _constructor) || [];
const selfList: number[] = Reflect.getMetadata(metadataOfSelf, _constructor) || [];
const hostList: number[] = Reflect.getMetadata(metadataOfHost, _constructor) || [];
const optionalList: number[] = Reflect.getMetadata(metadataOfOptional, _constructor) || [];
// 使用 @Inject 代替获取类型
const injectTokenList: TInjectItem[] = Reflect.getMetadata(metadataOfInject, _constructor) || [];
// find instance from provider
const needInjectedClassLength = depsToken.length;
for (let i = 0; i < needInjectedClassLength; i++) {
// 构建冒泡层数
let bubblingLayer: number | 'always' = 'always';
if (hostList.indexOf(i) !== -1) bubblingLayer = 1;
if (selfList.indexOf(i) !== -1) bubblingLayer = 0;
const findInjectToken = injectTokenList.find((value) => value.index === i);
// 构建冒泡开始的injector
let findInjector = injector;
if (skipSelfList.indexOf(i) !== -1) findInjector = injector.parentInjector;
if (findInjectToken && findInjectToken.injector) findInjector = findInjectToken.injector;
const key = (findInjectToken && findInjectToken.token) ? findInjectToken.token : depsToken[i];
const isOptional = optionalList.indexOf(i) !== -1;
let findProvider = null;
// 使用自定义注解,还可以定义是否解决注入
let canJump = false;
resolveParameterInjectMap.forEach((resolveInject, key) => {
const list: { argumentIndex: number; decoratorArgument: string; }[] = Reflect.getMetadata(key, _constructor) || [];
const findInject = list.find((value) => value.argumentIndex === i);
if (findInject) {
findProvider = resolveInject({
key,
argumentIndex: findInject.argumentIndex,
decoratorArgument: findInject.decoratorArgument,
bubblingLayer,
}, findInjector);
canJump = true;
}
});
if (canJump) {
if (!isOptional && (findProvider === undefined || findProvider === null)) throw new Error(`Instance of ${key} can't be ${findProvider}`);
args.push(findProvider);
continue;
}
// 默认注解,使用构造函数或@Inject
if (findInjector.getInstance(key, bubblingLayer)) {
args.push(findInjector.getInstance(key, bubblingLayer));
continue;
} else {
// use @Optional will return null
if (isOptional) {
args.push(null);
continue;
}
findProvider = getService(findInjector, key, _constructor, bubblingLayer);
args.push(findProvider);
continue;
}
}
return args;
}
/**
* use injector to create arguments for constructor
*
* only building providers which need depsToken
*
* @export
* @param {Function} _constructor
* @param {Injector} [injector]
* @param {any[]} [depsToken]
* @returns {any[]}
*/
export function injectionCreator(_constructor: Function, injector?: Injector, depsToken?: any[]): any[] {
let _depsToken: any[] = depsToken || [];
if ((_constructor as any).injectTokens) _depsToken = (_constructor as any).injectTokens;
else _depsToken = Reflect.getMetadata(metadataOfInjectable, _constructor) || [];
// build $privateProviders into injector of @Component and @Directive
if ((_constructor.prototype as IProviderClass).$privateProviders) {
const length = (_constructor.prototype as IProviderClass).$privateProviders.length;
for (let i = 0; i < length; i++) {
const service = (_constructor.prototype as IProviderClass).$privateProviders[i];
if ((service as TInjectTokenProvider).provide) injector.setProvider((service as TInjectTokenProvider).provide, service);
else injector.setProvider(service as Function, service as Function);
}
}
return argumentsCreator(_constructor, injector, _depsToken);
}
/**
* create an instance with factory method
*
* use injectionCreator to get arguments from Injector
* only building provider need depsToken
*
* @export
* @template T
* @param {Function} _constructor
* @param {any[]} [deps]
* @param {Injector} [injector=rootInjector]
* @param {any[]} [depsToken]
* @returns {T}
*/
export function NvInstanceFactory<T = any>(_constructor: Function, deps?: any[], injector: Injector = rootInjector, depsToken?: any[]): T {
const args = (deps && deps instanceof Array) ? deps : injectionCreator(_constructor, injector, depsToken);
const factoryInstance = (new (_constructor as any)(...args)) as T;
(factoryInstance as any).$privateInjector = injector;
bindProperty(_constructor, factoryInstance, injector);
return factoryInstance;
} | the_stack |
import { expect } from "chai";
import "mocha";
import { assert as SinonAssert, spy } from "sinon";
import {
AdjustType,
Color,
ColorScene,
Command,
CommandType,
DevicePropery,
FlowState,
IConfig,
} from "../src/models";
import { Yeelight } from "../src/yeelight";
import { TestUtils } from "./test-util";
/* tslint:disable:only-arrow-functions */
describe("Yeelight Class Test", () => {
const options: IConfig = { lightIp: "127.0.0.1", lightPort: 55443, timeout: 2000 };
beforeEach(TestUtils.beforeEach);
afterEach(TestUtils.afterEach);
it("connect() should success", async () => {
const yeelight = new Yeelight(options);
const y = await yeelight.connect();
expect(y).not.eq(null);
expect(y.connected).to.eq(true);
y.disconnect();
});
describe("setName() tests", function() {
this.retries(3);
it("setName() should work when send valid message", async () => {
options.lightPort = TestUtils.port;
const yeelight = new Yeelight(options);
yeelight.disablePing = true;
const y = await yeelight.connect();
TestUtils.mockSocket({ id: 1, result: ["ok"] }, (x) => {
expect(x).to.deep.eq({
id: 1, method: "set_name", params: ["unit_test"],
});
});
const result = await y.setName("unit_test");
expect(result).to.not.eq(null);
yeelight.disconnect();
});
it("setName() should fire commandSuccess, set_name, set_name_sent event", async () => {
const yeelight = new Yeelight(options);
yeelight.disablePing = true;
options.lightPort = TestUtils.port;
const y = await yeelight.connect();
const expectData = {
action: "set_name",
command: new Command(1, CommandType.SET_NAME, ["unit_test"]),
result: { id: 1, result: ["ok"] },
success: true,
};
const spy1 = spy();
const spy2 = spy();
const spy3 = spy();
y.once("set_name", spy1);
y.once("commandSuccess", spy2);
y.once("set_name_sent", spy3);
TestUtils.mockSocket({ id: 1, result: ["ok"] }, (x) => {
expect(x).to.deep.eq({
id: 1, method: "set_name", params: ["unit_test"],
});
});
const result = await y.setName("unit_test");
expect({ ...result }).to.deep.equal(expectData);
SinonAssert.calledWith(spy1, expectData);
SinonAssert.calledWith(spy2, expectData);
SinonAssert.calledWith(spy3, expectData.command);
yeelight.disconnect();
});
// tslint:disable-next-line:max-line-length
it("setName() should fire error when send invalid name, should fire set_name, commandError, set_name_sent events",
async () => {
const yeelight = new Yeelight(options);
yeelight.disablePing = true;
options.lightPort = TestUtils.port;
const y = await yeelight.connect();
const expectData1 = {
action: "set_name",
command: new Command(1, CommandType.SET_NAME, ["this is invalid name"]),
result: { id: 1, error: { code: -1, message: "General error" } },
success: false,
};
const spy1 = spy();
const spy2 = spy();
const spy3 = spy();
y.once("set_name", spy1);
y.once("commandError", spy2);
y.once("set_name_sent", spy3);
TestUtils.mockSocket({ id: 1, error: { code: -1, message: "General error" } }, (x) => {
expect(x).to.deep.eq({
id: 1, method: "set_name", params: ["this is invalid name"],
});
});
let result = null;
let errResult;
try {
result = await y.setName("this is invalid name");
} catch (error) {
errResult = error;
}
expect(result).to.be.equal(null);
expect({ ...errResult }).to.deep.equal(expectData1);
SinonAssert.calledWith(spy1, expectData1);
SinonAssert.calledWith(spy2, expectData1);
SinonAssert.calledWith(spy3, expectData1.command);
yeelight.disconnect();
});
it("setName() should reject promise, raise commandTimedout event when socket not response",
async () => {
const yeelight = new Yeelight(options);
yeelight.disablePing = true;
options.lightPort = TestUtils.port;
const y = await yeelight.connect();
const expectData = {
action: "set_name",
command: new Command(1, CommandType.SET_NAME, ["mybulb"]),
success: false,
};
const spy2 = spy();
const spy3 = spy();
y.once("commandTimedout", spy2);
y.once("set_name_sent", spy3);
TestUtils.mockSocket(null, (x) => {
expect(x).to.deep.eq({
id: 1, method: "set_name", params: ["mybulb"],
});
});
try {
const result = await y.setName("mybulb");
} catch (err) {
// promise will reject on timeout
}
SinonAssert.calledWith(spy2, expectData.command);
SinonAssert.calledWith(spy3, expectData.command);
yeelight.disconnect();
});
});
describe("manipulator methods", function() {
async function init() {
const yeelight = new Yeelight(options);
yeelight.disablePing = true;
await yeelight.connect();
return yeelight;
}
function removeClasses<T>(o: T): T {
return JSON.parse(JSON.stringify(o));
}
function testMethod(
methodName: string,
fcn: (yeelight: Yeelight) => any,
sendData: any,
replyData: any,
verifyReply?: any,
) {
it("method " + methodName + " should work when send valid message", async () => {
const yeelight = await init();
TestUtils.mockSocket(replyData.result, (x) => {
expect(x).to.deep.eq(sendData);
});
let result = await fcn(yeelight);
const reply = (
verifyReply === undefined ?
replyData :
verifyReply
);
if (result) {
result = removeClasses(result);
}
expect(result).to.deep.eq(reply);
yeelight.disconnect();
});
}
testMethod(
"toggle",
(yeelight) => yeelight.toggle(),
{ id: 1, method: "toggle", params: [] },
{
action: "toggle",
command: { id: 1, method: "toggle", params: [] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"cronAdd",
(yeelight) => yeelight.cronAdd(0, 1),
{ id: 1, method: "cron_add", params: [ 0, 1 ] },
{
action: "cron_add",
command: { id: 1, method: "cron_add", params: [ 0, 1 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"cronGet",
(yeelight) => yeelight.cronGet(0),
{ id: 1, method: "cron_get", params: [ 0 ] },
{
action: "cron_get",
command: { id: 1, method: "cron_get", params: [ 0 ] },
result: { id: 1, result: [ null ] },
success: true,
},
);
testMethod(
"cronDelete",
(yeelight) => yeelight.cronDelete(0),
{ id: 1, method: "cron_del", params: [ 0 ] },
{
action: "cron_del",
command: { id: 1, method: "cron_del", params: [ 0 ] },
result: { id: 1, result: [ "ok" ] },
success: true },
);
testMethod(
"setDefault",
(yeelight) => yeelight.setDefault(),
{ id: 1, method: "set_default", params: [] },
{
action: "set_default",
command: { id: 1, method: "set_default", params: [] },
result: { id: 1, result: [ "ok" ] },
success: true },
);
testMethod(
"startColorFlow",
(yeelight) => {
return yeelight.startColorFlow([
new FlowState(500, 1, new Color(1, 254, 1).getValue(), 1),
new FlowState(500, 1, new Color(255, 0, 0).getValue(), 1),
new FlowState(500, 1, new Color(0, 0, 255).getValue(), 1),
]);
},
{
id: 1,
method: "start_cf",
params: [ 0, 1, "500,1,130561,1,500,1,16711680,1,500,1,255,1" ],
},
{
action: "start_cf",
command:
{
id: 1,
method: "start_cf",
params: [ 0, 1, "500,1,130561,1,500,1,16711680,1,500,1,255,1" ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"stopColorFlow",
(yeelight) => yeelight.stopColorFlow(),
{ id: 1, method: "stop_cf", params: [] },
{
action: "stop_cf",
command: { id: 1, method: "stop_cf", params: [] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"getProperty",
(yeelight) => yeelight.getProperty([DevicePropery.BRIGHT, DevicePropery.POWER]),
{ id: 1, method: "get_prop", params: [ "bright", "power" ] },
{
action: "get_prop",
command: { id: 1, method: "get_prop", params: [ "bright", "power" ] },
result: { id: 1, result: [ "1", "off" ] },
success: true,
},
);
testMethod(
"setCtAbx",
(yeelight) => yeelight.setCtAbx(2234, "smooth"),
{ id: 1, method: "set_ct_abx", params: [ 2234, "smooth", 500 ] },
{
action: "set_ct_abx",
command: { id: 1, method: "set_ct_abx", params: [ 2234, "smooth", 500 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"setRGB",
(yeelight) => yeelight.setRGB(new Color(0, 0, 255), "smooth"),
{ id: 1, method: "set_rgb", params: [ 255, "smooth", 500 ] },
{
action: "set_rgb",
command: { id: 1, method: "set_rgb", params: [ 255, "smooth", 500 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"setHSV",
(yeelight) => yeelight.setHSV(240, 100, "smooth"),
{
id: 1,
method: "set_hsv",
params: [ 240, 100, "smooth", 500 ],
},
{
action: "set_hsv",
command:
{
id: 1,
method: "set_hsv",
params: [ 240, 100, "smooth", 500 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"setBright",
(yeelight) => yeelight.setBright(1),
{ id: 1, method: "set_bright", params: [ 1, "sudden", 500 ] },
{
action: "set_bright",
command: { id: 1, method: "set_bright", params: [ 1, "sudden", 500 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"setAdjust",
(yeelight) => yeelight.setAdjust(AdjustType.INCREASE, "bright"),
{
id: 1,
method: "set_adjust",
params: [ "increase", "bright" ],
},
{
action: "set_adjust",
command: { id: 1, method: "set_adjust", params: [ "increase", "bright" ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"setName",
(yeelight) => yeelight.setName("new_name"),
{ id: 1, method: "set_name", params: [ "new_name" ] },
{
action: "set_name",
command: { id: 1, method: "set_name", params: [ "new_name" ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"adjust",
(yeelight) => yeelight.adjust(CommandType.ADJUST_BRIGHT, 5),
{ id: 1, method: "adjust_bright", params: [ 5, 500 ] },
{
action: "adjust_bright",
command: { id: 1, method: "adjust_bright", params: [ 5, 500 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
testMethod(
"ping",
(yeelight) => yeelight.ping(),
{ id: 1, method: "ping", params: [] },
{
action: "ping",
command: { id: 1, method: "ping", params: [] },
result: { id: 1, error:{code: -1, message: "method not supported"} },
success: false,
},
null,
);
testMethod(
"setScene",
(yeelight) => yeelight.setScene(new ColorScene(new Color(1, 254, 1), 1)),
{ id: 1, method: "set_scene", params: [ "color", 130561, 1 ] },
{
action: "set_scene",
command: { id: 1, method: "set_scene", params: [ "color", 130561, 1 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);
/*testMethod(
"setMusic",
(yeelight) => yeelight.setMusic(1, "10.0.1.20", 80),
{ id: 1, method: "set_music", params: [ "10.0.1.20", 80 ] },
{
action: "set_music",
command: { id: 1, method: "set_music", params: [ "10.0.1.20", 80 ] },
result: { id: 1, result: [ "ok" ] },
success: true,
},
);*/
});
}); | the_stack |
import * as React from 'react'
import Input from 'src/components/input'
import classnames from 'classnames/bind'
import { default as Button, ButtonGroup } from 'src/components/button'
import { stringToSearch, SearchOptions, stringifySearch } from 'src/components/search_query_builder/helpers'
import Modal from 'src/components/modal'
import SearchQueryBuilder from 'src/components/search_query_builder'
import { useModal, renderModals, useWiredData } from 'src/helpers'
import { Tag, ViewName } from 'src/global_types'
import { getTags } from 'src/services'
const cx = classnames.bind(require('./stylesheet'))
export default (props: {
onRequestCreateFinding: () => void,
onRequestCreateEvidence: () => void,
onSearch: (query: string) => void,
query: string,
operationSlug: string,
viewName: ViewName,
}) => {
const [queryInput, setQueryInput] = React.useState<string>("")
const helpModal = useModal<void>(modalProps => <SearchHelpModal {...modalProps} />)
React.useEffect(() => {
setQueryInput(props.query)
}, [props.query])
const inputRef = React.useRef<HTMLInputElement>(null)
const builderModal = useModal<{ searchText: string }>(modalProps => (
<SearchBuilderModal
{...modalProps}
onChanged={(result: string) => {
setQueryInput(result)
props.onSearch(result)
}}
operationSlug={props.operationSlug}
viewName={props.viewName}
/>
))
return (
<>
<div className={cx('root')}>
<div className={cx('search-container')}>
<Input
ref={inputRef}
className={cx('search')}
inputClassName={cx('search-input')}
value={queryInput}
onChange={setQueryInput}
placeholder="Filter Timeline"
icon={require('./search.svg')}
onKeyDown={e => {
if (e.key === 'Enter') {
inputRef.current?.blur()
props.onSearch(queryInput)
}
}}
/>
<a className={cx('search-help-icon')} onClick={() => helpModal.show()} title="Search Help"></a>
<a className={cx('edit-filter-icon')} onClick={() => builderModal.show({ searchText: queryInput })} title="Edit Query Filters"></a>
</div>
<ButtonGroup>
<Button onClick={props.onRequestCreateEvidence}>Create Evidence</Button>
<Button onClick={props.onRequestCreateFinding}>Create Finding</Button>
</ButtonGroup>
</div>
{renderModals(helpModal, builderModal)}
</>
)
}
const SearchBuilderModal = (props: {
searchText: string,
operationSlug: string,
viewName: ViewName,
onRequestClose: () => void,
onChanged: (resultString: string) => void,
}) => {
const wiredTags = useWiredData<Array<Tag>>(
React.useCallback(() => getTags({ operationSlug: props.operationSlug }), [props.operationSlug])
)
return (<>
{wiredTags.render(tags => (
<Modal title="Query Builder" onRequestClose={props.onRequestClose}>
<SearchQueryBuilder
searchOptions={stringToSearch(props.searchText, tags)}
onChanged={(result: SearchOptions) => {
props.onChanged(stringifySearch(result))
props.onRequestClose()
}}
operationSlug={props.operationSlug}
viewName={props.viewName}
/>
</Modal>
))}
</>)
}
const CodeSnippet = (props: {
children: React.ReactNode,
className?: string | Array<string>
}) => <span className={cx('code', props.className)}>{props.children}</span>
const CodeExample = (props: {
children: React.ReactNode
className?: string | Array<string>
}) => <span className={cx('example', props.className)}>{props.children}</span>
type FilterDetail = { field: string, description: React.ReactNode }
const FilterDescriptionRow = (props: {
filter: FilterDetail
}) => (
<tr className={cx('filter-row')}>
<td className={cx('filter-field')}>{props.filter.field}</td>
<td className={cx('filter-description')}>{props.filter.description}</td>
</tr>
)
const SearchHelpModal = (props: {
onRequestClose: () => void,
}) => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
props.onRequestClose()
}
}
React.useEffect(() => {
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
})
return <Modal title="Search Help" onRequestClose={props.onRequestClose} >
<div>
<p>
Timeline results can be influenced by using the Filter Timeline text box. Filters are applied
by specifying the correct syntax, and are joined together to provide ever-narrower search
results.
</p>
<p>
In general, search queries are presented in the following form:
<CodeExample>Free Text specific-field:"specific value"</CodeExample>
Here, the "Free Text Section" phrase will search all evidence for any occurance of
{" "}<CodeSnippet>Free</CodeSnippet> and <CodeSnippet>Text</CodeSnippet>. The
{" "}<CodeSnippet>specific-field</CodeSnippet> will search just the specific-field attribute
for the value <CodeSnippet>specific value</CodeSnippet>. Filters must be specified without a
space on either side of the colon. Multiple filters can be provided in a single search. Also
note that <CodeSnippet>specific value</CodeSnippet> was written in quotes. This is not
required for any field, but provide the ability to search over phrases rather than words.
</p>
<p>
As an example, consider the search:
<CodeExample>"Darth Vader" creator:"George Lucas" tag:sci-fi</CodeExample>
Performing this search over a set of movies might return several <em>Star Wars</em> movies but
exclude <em>Indiana Jones</em>. Removing <CodeSnippet>Darth Vader</CodeSnippet> would
expand the search to include <em>THX 1138</em>, while adding
{" "}<CodeSnippet>"Jar Jar Binks"</CodeSnippet> would condense the results to just
{" "}<em>Star Wars</em> episodes 1-3.
</p>
<p>The below table lists all of the currently available filters, and value limitations, if any:</p>
<table>
<tbody>
{HelpText.map(f => <FilterDescriptionRow filter={f} key={f.field} />)}
</tbody>
</table>
</div>
</Modal >
}
const HelpText: Array<FilterDetail> = [
{
field: 'tag',
description:
<>
<p>
Filters the result by requiring that the evidence or finding contain each of the
specified tag fields.
</p>
<p>Multiple <CodeSnippet>tag</CodeSnippet> fields can be specified.</p>
<p>To easily create this filter, click on the desired tags next to any evidence.</p>
</>
},
{
field: 'operator',
description:
<>
<p>
Filters the result by requiring that the evidence or finding was created by a particular
user.
</p>
<p>Only one <CodeSnippet>operator</CodeSnippet> field can be specified.</p>
<p>To easily create this filter, click on the desired username next to any evidence.</p>
</>
},
{
field: 'range',
description:
<>
<p>
Filters the result by requiring that the evidence to have occurred within a particular
date range. In the findings timeline, this will require that all evidence for a finding
be contained with the indicated date range. Only one range can be specified.
Date Format: <CodeSnippet>yyyy-mm-dd,yyyy-mm-dd</CodeSnippet> where
y, m, and d are year, month and day digits respectively.
For example: <CodeSnippet>2020-01-01,2020-01-31</CodeSnippet> covers the entire
month of January, 2020.
</p>
<p>Only one <CodeSnippet>range</CodeSnippet> field can be specified.</p>
<p>Click on the calendar next to the Timeline Filter to help specify the date.</p>
</>
},
{
field: 'sort',
description:
<>
<p>
Orders the filter in a particular direction. By default, wiith no filter provided,
results are ordered by "last evidence first", or an effective reverse-chronological
order.
</p>
<p>
Possible values:
{" "}<CodeSnippet>asc</CodeSnippet>,
{" "}<CodeSnippet>ascending</CodeSnippet> or
{" "}<CodeSnippet>chronological</CodeSnippet>
</p>
<p>
Each of the above values will order the results in a "first-evidence-first", or
chronological order.
</p>
<p>Only one <CodeSnippet>sort</CodeSnippet> field can be specified.</p>
</>
},
{
field: 'linked',
description:
<>
<p>
Filters the result by finding evidence that either has, or has not been attached to a finding.
</p>
<p>
Possible values: <CodeSnippet>true</CodeSnippet>, <CodeSnippet>false</CodeSnippet>
</p>
<p>
Provide <CodeSnippet>true</CodeSnippet> to require the evidence has been linked
with a finding, or <CodeSnippet>false</CodeSnippet> to require evidence that has
not been linked with a finding.
{" "}<em>This will only have an effect in the Evidence Timeline.</em>
</p>
<p>Only one <CodeSnippet>linked</CodeSnippet> field can be specified.</p>
</>
},
{
field: 'with-evidence',
description:
<>
<p>
Filters the result by requiring a fidning to contain a particular piece of evidence.
<em>This will only have an effect in the Findings Timeline.</em>
</p>
<p>Only one <CodeSnippet>with-evidence</CodeSnippet> field can be specified.</p>
</>
},
{
field: 'uuid',
description:
<>
<p>
Filters the result by requiring that the evidence or finding have a particular ID.
This is typically used to share evidence with other users. While it can be specified
manually, the preferred method is to click the "Copy Permalink" button
next to the desired evidence, and share the link as needed.
</p>
<p>Only one <CodeSnippet>uuid</CodeSnippet> field can be specified.</p>
</>
},
] | the_stack |
import jsonld from "jsonld";
import { suites, SECURITY_CONTEXT_URL } from "jsonld-signatures";
import {
SignatureSuiteOptions,
CreateProofOptions,
CanonizeOptions,
CreateVerifyDataOptions,
VerifyProofOptions,
VerifySignatureOptions,
SuiteSignOptions
} from "./types";
import { w3cDate } from "./utilities";
import { Bls12381G2KeyPair } from "@mattrglobal/bls12381-key-pair";
/**
* A BBS+ signature suite for use with BLS12-381 key pairs
*/
export class BbsBlsSignature2020 extends suites.LinkedDataProof {
/**
* Default constructor
* @param options {SignatureSuiteOptions} options for constructing the signature suite
*/
constructor(options: SignatureSuiteOptions = {}) {
const {
verificationMethod,
signer,
key,
date,
useNativeCanonize,
LDKeyClass
} = options;
// validate common options
if (
verificationMethod !== undefined &&
typeof verificationMethod !== "string"
) {
throw new TypeError('"verificationMethod" must be a URL string.');
}
super({
type: "sec:BbsBlsSignature2020"
});
this.proof = {
"@context": [
{
sec: "https://w3id.org/security#",
proof: {
"@id": "sec:proof",
"@type": "@id",
"@container": "@graph"
}
},
"https://w3id.org/security/bbs/v1"
],
type: "BbsBlsSignature2020"
};
this.LDKeyClass = LDKeyClass ?? Bls12381G2KeyPair;
this.signer = signer;
this.verificationMethod = verificationMethod;
this.proofSignatureKey = "proofValue";
if (key) {
if (verificationMethod === undefined) {
this.verificationMethod = key.id;
}
this.key = key;
if (typeof key.signer === "function") {
this.signer = key.signer();
}
if (typeof key.verifier === "function") {
this.verifier = key.verifier();
}
}
if (date) {
this.date = new Date(date);
if (isNaN(this.date)) {
throw TypeError(`"date" "${date}" is not a valid date.`);
}
}
this.useNativeCanonize = useNativeCanonize;
}
/**
* @param options {CreateProofOptions} options for creating the proof
*
* @returns {Promise<object>} Resolves with the created proof object.
*/
async createProof(options: CreateProofOptions): Promise<object> {
const {
document,
purpose,
documentLoader,
expansionMap,
compactProof
} = options;
let proof;
if (this.proof) {
// use proof JSON-LD document passed to API
proof = await jsonld.compact(this.proof, SECURITY_CONTEXT_URL, {
documentLoader,
expansionMap,
compactToRelative: false
});
} else {
// create proof JSON-LD document
proof = { "@context": SECURITY_CONTEXT_URL };
}
// ensure proof type is set
proof.type = this.type;
// set default `now` date if not given in `proof` or `options`
let date = this.date;
if (proof.created === undefined && date === undefined) {
date = new Date();
}
// ensure date is in string format
if (date !== undefined && typeof date !== "string") {
date = w3cDate(date);
}
// add API overrides
if (date !== undefined) {
proof.created = date;
}
if (this.verificationMethod !== undefined) {
proof.verificationMethod = this.verificationMethod;
}
// allow purpose to update the proof; the `proof` is in the
// SECURITY_CONTEXT_URL `@context` -- therefore the `purpose` must
// ensure any added fields are also represented in that same `@context`
proof = await purpose.update(proof, {
document,
suite: this,
documentLoader,
expansionMap
});
// create data to sign
const verifyData = (
await this.createVerifyData({
document,
proof,
documentLoader,
expansionMap,
compactProof
})
).map(item => new Uint8Array(Buffer.from(item)));
// sign data
proof = await this.sign({
verifyData,
document,
proof,
documentLoader,
expansionMap
});
return proof;
}
/**
* @param options {object} options for verifying the proof.
*
* @returns {Promise<{object}>} Resolves with the verification result.
*/
async verifyProof(options: VerifyProofOptions): Promise<object> {
const { proof, document, documentLoader, expansionMap, purpose } = options;
try {
// create data to verify
const verifyData = (
await this.createVerifyData({
document,
proof,
documentLoader,
expansionMap,
compactProof: false
})
).map(item => new Uint8Array(Buffer.from(item)));
// fetch verification method
const verificationMethod = await this.getVerificationMethod({
proof,
document,
documentLoader,
expansionMap
});
// verify signature on data
const verified = await this.verifySignature({
verifyData,
verificationMethod,
document,
proof,
documentLoader,
expansionMap
});
if (!verified) {
throw new Error("Invalid signature.");
}
// ensure proof was performed for a valid purpose
const { valid, error } = await purpose.validate(proof, {
document,
suite: this,
verificationMethod,
documentLoader,
expansionMap
});
if (!valid) {
throw error;
}
return { verified: true };
} catch (error) {
return { verified: false, error };
}
}
async canonize(input: any, options: CanonizeOptions): Promise<string> {
const { documentLoader, expansionMap, skipExpansion } = options;
return jsonld.canonize(input, {
algorithm: "URDNA2015",
format: "application/n-quads",
documentLoader,
expansionMap,
skipExpansion,
useNative: this.useNativeCanonize
});
}
async canonizeProof(proof: any, options: CanonizeOptions): Promise<string> {
const { documentLoader, expansionMap } = options;
proof = { ...proof };
delete proof[this.proofSignatureKey];
return this.canonize(proof, {
documentLoader,
expansionMap,
skipExpansion: false
});
}
/**
* @param document {CreateVerifyDataOptions} options to create verify data
*
* @returns {Promise<{string[]>}.
*/
async createVerifyData(options: CreateVerifyDataOptions): Promise<string[]> {
const { proof, document, documentLoader, expansionMap } = options;
const proofStatements = await this.createVerifyProofData(proof, {
documentLoader,
expansionMap
});
const documentStatements = await this.createVerifyDocumentData(document, {
documentLoader,
expansionMap
});
// concatenate c14n proof options and c14n document
return proofStatements.concat(documentStatements);
}
/**
* @param proof to canonicalize
* @param options to create verify data
*
* @returns {Promise<{string[]>}.
*/
async createVerifyProofData(
proof: any,
{ documentLoader, expansionMap }: any
): Promise<string[]> {
const c14nProofOptions = await this.canonizeProof(proof, {
documentLoader,
expansionMap
});
return c14nProofOptions.split("\n").filter(_ => _.length > 0);
}
/**
* @param document to canonicalize
* @param options to create verify data
*
* @returns {Promise<{string[]>}.
*/
async createVerifyDocumentData(
document: any,
{ documentLoader, expansionMap }: any
): Promise<string[]> {
const c14nDocument = await this.canonize(document, {
documentLoader,
expansionMap
});
return c14nDocument.split("\n").filter(_ => _.length > 0);
}
/**
* @param document {object} to be signed.
* @param proof {object}
* @param documentLoader {function}
* @param expansionMap {function}
*/
async getVerificationMethod({ proof, documentLoader }: any): Promise<any> {
let { verificationMethod } = proof;
if (typeof verificationMethod === "object") {
verificationMethod = verificationMethod.id;
}
if (!verificationMethod) {
throw new Error('No "verificationMethod" found in proof.');
}
// Note: `expansionMap` is intentionally not passed; we can safely drop
// properties here and must allow for it
const result = await jsonld.frame(
verificationMethod,
{
"@context": SECURITY_CONTEXT_URL,
"@embed": "@always",
id: verificationMethod
},
{
documentLoader,
compactToRelative: false,
expandContext: SECURITY_CONTEXT_URL
}
);
if (!result) {
throw new Error(`Verification method ${verificationMethod} not found.`);
}
// ensure verification method has not been revoked
if (result.revoked !== undefined) {
throw new Error("The verification method has been revoked.");
}
return result;
}
/**
* @param options {SuiteSignOptions} Options for signing.
*
* @returns {Promise<{object}>} the proof containing the signature value.
*/
async sign(options: SuiteSignOptions): Promise<object> {
const { verifyData, proof } = options;
if (!(this.signer && typeof this.signer.sign === "function")) {
throw new Error(
"A signer API with sign function has not been specified."
);
}
const proofValue: Uint8Array = await this.signer.sign({
data: verifyData
});
proof[this.proofSignatureKey] = Buffer.from(proofValue).toString("base64");
return proof;
}
/**
* @param verifyData {VerifySignatureOptions} Options to verify the signature.
*
* @returns {Promise<boolean>}
*/
async verifySignature(options: VerifySignatureOptions): Promise<boolean> {
const { verificationMethod, verifyData, proof } = options;
let { verifier } = this;
if (!verifier) {
const key = await this.LDKeyClass.from(verificationMethod);
verifier = key.verifier(key, this.alg, this.type);
}
return await verifier.verify({
data: verifyData,
signature: new Uint8Array(
Buffer.from(proof[this.proofSignatureKey] as string, "base64")
)
});
}
static proofType = [
"BbsBlsSignature2020",
"sec:BbsBlsSignature2020",
"https://w3id.org/security#BbsBlsSignature2020"
];
} | the_stack |
import * as path from 'path';
import {
ComparisonOperator,
IAlarmAction,
IMetric,
MathExpression,
TreatMissingData,
} from '@aws-cdk/aws-cloudwatch';
import {SnsAction} from '@aws-cdk/aws-cloudwatch-actions';
import {
IConnectable,
ISecurityGroup,
IVpc,
Port,
SubnetSelection,
} from '@aws-cdk/aws-ec2';
import {
ApplicationLoadBalancer,
ApplicationTargetGroup,
IApplicationLoadBalancerTarget,
} from '@aws-cdk/aws-elasticloadbalancingv2';
import {IPolicy, IRole, Policy, ServicePrincipal} from '@aws-cdk/aws-iam';
import {IKey, Key} from '@aws-cdk/aws-kms';
import {Code, Runtime, SingletonFunction} from '@aws-cdk/aws-lambda';
import {ITopic, Topic} from '@aws-cdk/aws-sns';
import {LambdaSubscription} from '@aws-cdk/aws-sns-subscriptions';
import {
Construct,
Duration,
IResource,
Names,
RemovalPolicy,
ResourceEnvironment,
Stack,
} from '@aws-cdk/core';
import {LoadBalancerFactory} from './load-balancer-manager';
import {tagConstruct} from './runtime-info';
/**
* Information about an Elastic Load Balancing resource limit for your AWS account.
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_Limit.html
*/
export interface Limit {
/**
* The name of the limit. The possible values are:
*
* application-load-balancers
* listeners-per-application-load-balancer
* listeners-per-network-load-balancer
* network-load-balancers
* rules-per-application-load-balancer
* target-groups
* target-groups-per-action-on-application-load-balancer
* target-groups-per-action-on-network-load-balancer
* target-groups-per-application-load-balancer
* targets-per-application-load-balancer
* targets-per-availability-zone-per-network-load-balancer
* targets-per-network-load-balancer
*/
readonly name: string;
/**
* The maximum value of the limit.
*/
readonly max: number;
}
/**
* Interface for the fleet which can be registered to Health Monitor.
* This declares methods to be implemented by different kind of fleets
* like ASG, Spot etc.
*/
export interface IMonitorableFleet extends IConnectable {
/**
* This field expects the component of type IApplicationLoadBalancerTarget
* which can be attached to Application Load Balancer for monitoring.
*
* eg. An AutoScalingGroup
*/
readonly targetToMonitor: IApplicationLoadBalancerTarget;
/**
* This field expects the base capacity metric of the fleet against
* which, the healthy percent will be calculated.
*
* eg.: GroupDesiredCapacity for an ASG
*/
readonly targetCapacityMetric: IMetric;
/**
* This field expects a policy which can be attached to the lambda
* execution role so that it is capable of suspending the fleet.
*
* eg.: autoscaling:UpdateAutoScalingGroup permission for an ASG
*/
readonly targetUpdatePolicy: IPolicy;
/**
* This field expects the maximum instance count this fleet can have.
*
* eg.: maxCapacity for an ASG
*/
readonly targetCapacity: number;
/**
* This field expects the scope in which to create the monitoring resource
* like TargetGroups, Listener etc.
*/
readonly targetScope: Construct;
}
/**
* Interface for the Health Monitor.
*/
export interface IHealthMonitor extends IResource {
/**
* Attaches the load-balancing target to the ELB for instance-level
* monitoring.
*
* @param monitorableFleet
* @param healthCheckConfig
*/
registerFleet(monitorableFleet: IMonitorableFleet, healthCheckConfig: HealthCheckConfig): void;
}
/**
* Properties for configuring a health check
*/
export interface HealthCheckConfig {
/**
* The approximate time between health checks for an individual target.
*
* @default Duration.minutes(5)
*/
readonly interval?: Duration;
/**
* The port that the health monitor uses when performing health checks on the targets.
*
* @default 8081
*/
readonly port?: number;
/**
* The number of consecutive health check failures required before considering a target unhealthy.
*
* @default 3
*/
readonly instanceUnhealthyThresholdCount?: number;
/**
* The number of consecutive health checks successes required before considering an unhealthy target healthy.
*
* @default 2
*/
readonly instanceHealthyThresholdCount?: number;
/**
* The percent of healthy hosts to consider fleet healthy and functioning.
*
* @default 65%
*/
readonly healthyFleetThresholdPercent?: number;
}
/**
* Properties for the Health Monitor.
*/
export interface HealthMonitorProps {
/**
* VPC to launch the Health Monitor in.
*/
readonly vpc: IVpc;
/**
* Describes the current Elastic Load Balancing resource limits for your AWS account.
* This object should be the output of 'describeAccountLimits' API.
*
* @default default account limits for ALB is used
*
* @see https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ELBv2.html#describeAccountLimits-property
*/
readonly elbAccountLimits?: Limit[];
/**
* A KMS Key, either managed by this CDK app, or imported.
*
* @default A new Key will be created and used.
*/
readonly encryptionKey?: IKey;
/**
* Indicates whether deletion protection is enabled for the LoadBalancer.
*
* @default true
*
* Note: This value is true by default which means that the deletion protection is enabled for the
* load balancer. Hence, user needs to disable it using AWS Console or CLI before deleting the stack.
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html#deletion-protection
*/
readonly deletionProtection?: boolean;
/**
* Any load balancers that get created by calls to registerFleet() will be created in these subnets.
*
* @default: The VPC default strategy
*/
readonly vpcSubnets?: SubnetSelection;
/**
* Security group for the health monitor. This is security group is associated with the health monitor's load balancer.
*
* @default: A security group is created
*/
readonly securityGroup?: ISecurityGroup;
}
/**
* A new or imported Health Monitor.
*/
abstract class HealthMonitorBase extends Construct implements IHealthMonitor {
/**
* The stack in which this Health Monitor is defined.
*/
public abstract readonly stack: Stack;
/**
* The environment this resource belongs to.
*/
public abstract readonly env: ResourceEnvironment;
/**
* Attaches the load-balancing target to the ELB for instance-level
* monitoring.
*
* @param monitorableFleet
* @param healthCheckConfig
*/
public abstract registerFleet(monitorableFleet: IMonitorableFleet, healthCheckConfig: HealthCheckConfig): void;
}
/**
* This construct is responsible for the deep health checks of compute instances.
* It also replaces unhealthy instances and suspends unhealthy fleets.
* Although, using this constructs adds up additional costs for monitoring,
* it is highly recommended using this construct to help avoid / minimize runaway costs for compute instances.
*
* An instance is considered to be unhealthy when:
* 1) Deadline client is not installed on it;
* 2) Deadline client is installed but not running on it;
* 3) RCS is not configured correctly for Deadline client;
* 4) it is unable to connect to RCS due to any infrastructure issues;
* 5) the health monitor is unable to reach it because of some infrastructure issues.
*
* A fleet is considered to be unhealthy when:
* 1) at least 1 instance is unhealthy for the configured grace period;
* 2) a percentage of unhealthy instances in the fleet is above a threshold at any given point of time.
*
* This internally creates an array of application load balancers and attaches
* the worker-fleet (which internally is implemented as an Auto Scaling Group) to its listeners.
* There is no load-balancing traffic on the load balancers,
* it is only used for health checks.
* Intention is to use the default properties of laod balancer health
* checks which does HTTP pings at frequent intervals to all the
* instances in the fleet and determines its health. If any of the
* instance is found unhealthy, it is replaced. The target group
* also publishes the unhealthy target count metric which is used
* to identify the unhealthy fleet.
*
* Other than the default instance level protection, it also creates a lambda
* which is responsible to set the fleet size to 0 in the event of a fleet
* being sufficiently unhealthy to warrant termination.
* This lambda is triggered by CloudWatch alarms via SNS (Simple Notification Service).
*
* 
*
* Resources Deployed
* ------------------------
* - Application Load Balancer(s) doing frequent pings to the workers.
* - An Amazon Simple Notification Service (SNS) topic for all unhealthy fleet notifications.
* - An AWS Key Management Service (KMS) Key to encrypt SNS messages - If no encryption key is provided.
* - An Amazon CloudWatch Alarm that triggers if a worker fleet is unhealthy for a long period.
* - Another CloudWatch Alarm that triggers if the healthy host percentage of a worker fleet is lower than allowed.
* - A single AWS Lambda function that sets fleet size to 0 when triggered in response to messages on the SNS Topic.
* - Execution logs of the AWS Lambda function are published to a log group in Amazon CloudWatch.
*
* Security Considerations
* ------------------------
* - The AWS Lambda that is deployed through this construct will be created from a deployment package
* that is uploaded to your CDK bootstrap bucket during deployment. You must limit write access to
* your CDK bootstrap bucket to prevent an attacker from modifying the actions performed by this Lambda.
* We strongly recommend that you either enable Amazon S3 server access logging on your CDK bootstrap bucket,
* or enable AWS CloudTrail on your account to assist in post-incident analysis of compromised production
* environments.
* - The AWS Lambda that is created by this construct to terminate unhealthy worker fleets has permission to
* UpdateAutoScalingGroup ( https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_UpdateAutoScalingGroup.html )
* on all of the fleets that this construct is monitoring. You should not grant any additional actors/principals the
* ability to modify or execute this Lambda.
* - Execution of the AWS Lambda for terminating unhealthy workers is triggered by messages to the Amazon Simple
* Notification Service (SNS) Topic that is created by this construct. Any principal that is able to publish notification
* to this SNS Topic can cause the Lambda to execute and reduce one of your worker fleets to zero instances. You should
* not grant any additional principals permissions to publish to this SNS Topic.
*/
export class HealthMonitor extends HealthMonitorBase {
/**
* Default health check listening port
*/
public static readonly DEFAULT_HEALTH_CHECK_PORT: number = 63415;
/**
* Resource Tracker in Deadline currently publish health status every 5 min, hence keeping this same
*/
public static readonly DEFAULT_HEALTH_CHECK_INTERVAL: Duration = Duration.minutes(5);
/**
* Resource Tracker in Deadline currently determines host unhealthy in 15 min, hence keeping this count
*/
public static readonly DEFAULT_UNHEALTHY_HOST_THRESHOLD: number = 3;
/**
* This is the minimum possible value of ALB health-check config, we want to mark worker healthy ASAP
*/
public static readonly DEFAULT_HEALTHY_HOST_THRESHOLD: number = 2;
/**
* Since we are not doing any load balancing, this port is just an arbitrary port.
*/
public static readonly LOAD_BALANCER_LISTENING_PORT: number = 8081;
/**
* This number is taken from Resource Tracker implementation. If a fleet's healthy percent
* is less than this threshold at any given point of time, it is suspended.
*/
private static readonly DEFAULT_HEALTHY_FLEET_THRESHOLD_PERCENT_HARD: number = 65;
/**
* This number is taken from Resource Tracker implementation. If a fleet has at least 1
* unhealthy host for a period of 2 hours, it is suspended.
*/
private static readonly DEFAULT_UNHEALTHY_FLEET_THRESHOLD_PERCENT_GRACE: number = 0;
/**
* This number is taken from Resource Tracker implementation. We monitor unhealthy fleet for immediate
* termination for a period fo 5 minutes.
*/
private static readonly DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_HARD: Duration = Duration.minutes(5);
/**
* In Resource Tracker, we evaluate the fleet's health for determining the grace period over a period
* of 5 minutes. For the first unhealthy signal, a instance can take upto 10min (max), hence we are
* setting this period to be 15.
*/
private static readonly DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_GRACE: Duration = Duration.minutes(15);
/**
* This number is taken from Resource Tracker implementation. Fleet is terminated immediately if it
* has unhealthy host percent above the hard limit.
*/
private static readonly DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_THRESHOLD_HARD: number = 1;
/**
* This number is taken from Resource Tracker implementation. The grace period duration is 2 hours,
* since the grace period is 15 minutes, we need continuous 8 data points crossing the threshold.
*/
private static readonly DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_THRESHOLD_GRACE: number = 8;
/**
* The stack in which this Health Monitor is defined.
*/
public readonly stack: Stack;
/**
* The environment this resource belongs to.
*/
public readonly env: ResourceEnvironment;
/**
* SNS topic for all unhealthy fleet notifications. This is triggered by
* the grace period and hard terminations alarms for the registered fleets.
*
* This topic can be subscribed to get all fleet termination notifications.
*/
public readonly unhealthyFleetActionTopic: ITopic;
private readonly props: HealthMonitorProps;
private readonly lbFactory: LoadBalancerFactory;
private readonly unhealthyFleetActionLambda: SingletonFunction;
private readonly alarmTopicAction: IAlarmAction;
constructor(scope: Construct, id: string, props: HealthMonitorProps) {
super(scope, id);
this.stack = Stack.of(scope);
this.env = {
account: this.stack.account,
region: this.stack.region,
};
this.props = props;
this.lbFactory = new LoadBalancerFactory(this, props.vpc);
const topicEncryptKey = props.encryptionKey || new Key(this, 'SNSEncryptionKey', {
description: `This key is used to encrypt SNS messages for ${Names.uniqueId(this)}.`,
enableKeyRotation: true,
removalPolicy: RemovalPolicy.DESTROY,
trustAccountIdentities: true,
});
// allow cloudwatch service to send encrypted messages
topicEncryptKey.grant(new ServicePrincipal('cloudwatch.amazonaws.com'), 'kms:Decrypt', 'kms:GenerateDataKey');
this.unhealthyFleetActionTopic = new Topic(this, 'UnhealthyFleetTopic', {
masterKey: topicEncryptKey,
});
this.unhealthyFleetActionTopic.grantPublish(new ServicePrincipal('cloudwatch.amazonaws.com'));
this.alarmTopicAction = new SnsAction(this.unhealthyFleetActionTopic);
this.unhealthyFleetActionLambda = new SingletonFunction(this, 'UnhealthyFleetAction', {
code: Code.fromAsset(path.join(__dirname, '..', '..', 'lambdas', 'nodejs', 'unhealthyFleetAction')),
runtime: Runtime.NODEJS_12_X,
handler: 'index.handler',
lambdaPurpose: 'unhealthyFleetTermination',
timeout: Duration.seconds(300),
uuid: '28bccf6a-aa76-478c-9239-e2f5bcc0254c',
});
this.unhealthyFleetActionTopic.addSubscription(new LambdaSubscription(this.unhealthyFleetActionLambda));
// Tag deployed resources with RFDK meta-data
tagConstruct(this);
}
/**
* Attaches the load-balancing target to the ELB for instance-level
* monitoring. The ELB does frequent pings to the workers and determines
* if a worker node is unhealthy. If so, it replaces the instance.
*
* It also creates an Alarm for healthy host percent and suspends the
* fleet if the given alarm is breaching. It sets the maxCapacity
* property of the auto-scaling group to 0. This should be
* reset manually after fixing the issue.
*
* @param monitorableFleet
* @param healthCheckConfig
*/
public registerFleet(monitorableFleet: IMonitorableFleet, healthCheckConfig: HealthCheckConfig): void {
const {loadBalancer, targetGroup} = this.lbFactory.registerWorkerFleet(
monitorableFleet,
healthCheckConfig,
this.props);
this.createFleetAlarms(monitorableFleet, healthCheckConfig, loadBalancer, targetGroup);
}
private createFleetAlarms(
monitorableFleet: IMonitorableFleet,
healthCheckConfig: HealthCheckConfig,
loadBalancer: ApplicationLoadBalancer,
targetGroup: ApplicationTargetGroup) {
monitorableFleet.connections.allowFrom(loadBalancer,
Port.tcp(healthCheckConfig.port || HealthMonitor.LOAD_BALANCER_LISTENING_PORT));
const percentMetric = new MathExpression({
label: 'UnhealthyHostPercent',
expression: 'IF(fleetCapacity, 100*(unhealthyHostCount/fleetCapacity), 0)',
usingMetrics: {
unhealthyHostCount: targetGroup.metricUnhealthyHostCount({
statistic: 'max',
}),
fleetCapacity: monitorableFleet.targetCapacityMetric,
},
period: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_HARD,
});
// When unhealthy fleet is more than healthyFleetThresholdPercent or 35% at any given period of 5 minutes
const immediateTerminationAlarm = percentMetric.createAlarm(monitorableFleet.targetScope, 'UnhealthyFleetTermination', {
treatMissingData: TreatMissingData.NOT_BREACHING,
threshold: 100 - (healthCheckConfig.healthyFleetThresholdPercent || HealthMonitor.DEFAULT_HEALTHY_FLEET_THRESHOLD_PERCENT_HARD),
comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,
evaluationPeriods: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_THRESHOLD_HARD,
datapointsToAlarm: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_THRESHOLD_HARD,
actionsEnabled: true,
});
immediateTerminationAlarm.addAlarmAction(this.alarmTopicAction);
// When at least one node is unhealthy over a period of 2 hours
const percentMetricGracePeriod = new MathExpression({
label: 'UnhealthyHostPercent',
expression: 'IF(fleetCapacity, 100*(unhealthyHostCount/fleetCapacity), 0)',
usingMetrics: {
unhealthyHostCount: targetGroup.metricUnhealthyHostCount({
statistic: 'max',
}),
fleetCapacity: monitorableFleet.targetCapacityMetric,
},
period: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_GRACE,
});
const gracePeriodTerminationAlarm = percentMetricGracePeriod.createAlarm(monitorableFleet.targetScope, 'UnhealthyFleetGracePeriod', {
treatMissingData: TreatMissingData.NOT_BREACHING,
threshold: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_THRESHOLD_PERCENT_GRACE,
comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,
evaluationPeriods: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_THRESHOLD_GRACE,
datapointsToAlarm: HealthMonitor.DEFAULT_UNHEALTHY_FLEET_ALARM_PERIOD_THRESHOLD_GRACE,
actionsEnabled: true,
});
gracePeriodTerminationAlarm.addAlarmAction(this.alarmTopicAction);
(monitorableFleet.targetUpdatePolicy as Policy).attachToRole(this.unhealthyFleetActionLambda.role as IRole);
}
} | the_stack |
import { TokenType } from "./token-stream";
/**
* Contains traits of a particular token type
*/
export interface TokenTraits {
/**
* This token is an instruction
*/
instruction?: boolean;
/**
* This token is a Z80 Next instruction
*/
next?: boolean;
/**
* Indicates if an instruction is simple (argumentless)
*/
simple?: boolean;
/**
* This token is a pragma
*/
pragma?: boolean;
/**
* This token is a statement;
*/
statement?: boolean;
/**
* This token is a directive
*/
directive?: boolean;
/**
* This token can be the start of an expression
*/
expressionStart?: boolean;
/**
* Represents a macro-time function?
*/
macroTimeFunction?: boolean;
/**
* Represents a parse-time function
*/
parseTimeFunction?: boolean;
/**
* Represents a literal?
*/
literal?: boolean;
/**
* Represents a register?
*/
reg?: boolean;
/**
* Represents a standard 8-bit register?
*/
reg8?: boolean;
/**
* Represenst a special 8-bit register?
*/
reg8Spec?: boolean;
/**
* Represents an 8-bit index register?
*/
reg8Idx?: boolean;
/**
* Represents an 16-bit register?
*/
reg16?: boolean;
/**
* Represents an 16-bit special register?
*/
reg16Spec?: boolean;
/**
* Represents an 16-bit index register?
*/
reg16Idx?: boolean;
/**
* Represents a condition value?
*/
condition?: boolean;
/**
* Represents a JR condition value?
*/
relCondition?: boolean;
}
/**
* Gets the traits of the specified token type
* @param type Token type
*/
export function getTokenTraits(type: TokenType): TokenTraits {
return tokenTraits.get(type) ?? {};
}
/**
* This map contains the traits of token types
*/
const tokenTraits = new Map<TokenType, TokenTraits>();
// ----------------------------------------------------------------------------
// A
tokenTraits.set(TokenType.A, { reg: true, reg8: true });
tokenTraits.set(TokenType.AF, { reg: true, reg16Spec: true });
tokenTraits.set(TokenType.AF_, { reg: true, reg16Spec: true });
tokenTraits.set(TokenType.Adc, { instruction: true });
tokenTraits.set(TokenType.Add, { instruction: true });
tokenTraits.set(TokenType.AlignPragma, { pragma: true });
tokenTraits.set(TokenType.Ampersand, {});
tokenTraits.set(TokenType.And, { instruction: true });
tokenTraits.set(TokenType.Assign, { pragma: true });
// ----------------------------------------------------------------------------
// B
tokenTraits.set(TokenType.B, { reg: true, reg8: true });
tokenTraits.set(TokenType.BankPragma, { pragma: true });
tokenTraits.set(TokenType.BC, { reg: true, reg16: true });
tokenTraits.set(TokenType.BinaryLiteral, {
expressionStart: true,
literal: true,
});
tokenTraits.set(TokenType.BinaryNot, { expressionStart: true });
tokenTraits.set(TokenType.Bit, { instruction: true });
tokenTraits.set(TokenType.Break, { statement: true });
tokenTraits.set(TokenType.Brlc, { instruction: true, next: true });
tokenTraits.set(TokenType.Bsla, { instruction: true, next: true });
tokenTraits.set(TokenType.Bsra, { instruction: true, next: true });
tokenTraits.set(TokenType.Bsrf, { instruction: true, next: true });
tokenTraits.set(TokenType.Bsrl, { instruction: true, next: true });
// ----------------------------------------------------------------------------
// C
tokenTraits.set(TokenType.C, {
reg: true,
reg8: true,
condition: true,
relCondition: true,
});
tokenTraits.set(TokenType.Call, { instruction: true });
tokenTraits.set(TokenType.Ccf, { instruction: true, simple: true });
tokenTraits.set(TokenType.CharLiteral, {
expressionStart: true,
literal: true,
});
tokenTraits.set(TokenType.CiEqual, {});
tokenTraits.set(TokenType.CiNotEqual, {});
tokenTraits.set(TokenType.Colon, {});
tokenTraits.set(TokenType.Comma, {});
tokenTraits.set(TokenType.CompareBinPragma, { pragma: true });
tokenTraits.set(TokenType.Continue, { statement: true });
tokenTraits.set(TokenType.Cp, { instruction: true });
tokenTraits.set(TokenType.Cpd, { instruction: true, simple: true });
tokenTraits.set(TokenType.Cpdr, { instruction: true, simple: true });
tokenTraits.set(TokenType.Cpi, { instruction: true, simple: true });
tokenTraits.set(TokenType.Cpir, { instruction: true, simple: true });
tokenTraits.set(TokenType.Cpl, { instruction: true, simple: true });
tokenTraits.set(TokenType.CurAddress, { expressionStart: true, literal: true });
tokenTraits.set(TokenType.CurCnt, { expressionStart: true, literal: true });
// ----------------------------------------------------------------------------
// D
tokenTraits.set(TokenType.D, { reg: true, reg8: true });
tokenTraits.set(TokenType.DE, { reg: true, reg16: true });
tokenTraits.set(TokenType.Daa, { instruction: true, simple: true });
tokenTraits.set(TokenType.Dec, { instruction: true });
tokenTraits.set(TokenType.DecimalLiteral, {
expressionStart: true,
literal: true,
});
tokenTraits.set(TokenType.Def, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.DefbPragma, { pragma: true });
tokenTraits.set(TokenType.DefcPragma, { pragma: true });
tokenTraits.set(TokenType.DefgPragma, { pragma: true });
tokenTraits.set(TokenType.DefgxPragma, { pragma: true });
tokenTraits.set(TokenType.DefhPragma, { pragma: true });
tokenTraits.set(TokenType.DefineDir, { directive: true });
tokenTraits.set(TokenType.DefmPragma, { pragma: true });
tokenTraits.set(TokenType.DefnPragma, { pragma: true });
tokenTraits.set(TokenType.DefsPragma, { pragma: true });
tokenTraits.set(TokenType.DefwPragma, { pragma: true });
tokenTraits.set(TokenType.Di, { instruction: true, simple: true });
tokenTraits.set(TokenType.DispPragma, { pragma: true });
tokenTraits.set(TokenType.Divide, {});
tokenTraits.set(TokenType.Djnz, { instruction: true });
tokenTraits.set(TokenType.Dot, { expressionStart: true, literal: true });
tokenTraits.set(TokenType.DoubleColon, { expressionStart: true });
// ----------------------------------------------------------------------------
// E
tokenTraits.set(TokenType.E, { reg: true, reg8: true });
tokenTraits.set(TokenType.Ei, { instruction: true, simple: true });
tokenTraits.set(TokenType.Elif, { statement: true });
tokenTraits.set(TokenType.Else, { statement: true });
tokenTraits.set(TokenType.ElseDir, { directive: true });
tokenTraits.set(TokenType.EndIfDir, { directive: true });
tokenTraits.set(TokenType.EndModule, { statement: true });
tokenTraits.set(TokenType.Endif, { statement: true });
tokenTraits.set(TokenType.Endl, { statement: true });
tokenTraits.set(TokenType.Endm, { statement: true });
tokenTraits.set(TokenType.Endp, { statement: true });
tokenTraits.set(TokenType.Ends, { statement: true });
tokenTraits.set(TokenType.Endw, { statement: true });
tokenTraits.set(TokenType.EntPragma, { pragma: true });
tokenTraits.set(TokenType.EquPragma, { pragma: true });
tokenTraits.set(TokenType.Equal, {});
tokenTraits.set(TokenType.ErrorPragma, { pragma: true });
tokenTraits.set(TokenType.Ex, { instruction: true });
tokenTraits.set(TokenType.Exclamation, { expressionStart: true });
tokenTraits.set(TokenType.ExternPragma, { pragma: true });
tokenTraits.set(TokenType.Exx, { instruction: true, simple: true });
// ----------------------------------------------------------------------------
// F
tokenTraits.set(TokenType.False, { expressionStart: true, literal: true });
tokenTraits.set(TokenType.FillbPragma, { pragma: true });
tokenTraits.set(TokenType.FillwPragma, { pragma: true });
tokenTraits.set(TokenType.For, { statement: true });
// ----------------------------------------------------------------------------
// G
tokenTraits.set(TokenType.GoesTo, {});
tokenTraits.set(TokenType.GreaterThan, {});
tokenTraits.set(TokenType.GreaterThanOrEqual, {});
// ----------------------------------------------------------------------------
// H
tokenTraits.set(TokenType.H, { reg: true, reg8: true });
tokenTraits.set(TokenType.HL, { reg: true, reg16: true });
tokenTraits.set(TokenType.HReg, {
expressionStart: true,
});
tokenTraits.set(TokenType.Halt, { instruction: true, simple: true });
tokenTraits.set(TokenType.HexadecimalLiteral, {
expressionStart: true,
literal: true,
});
// ----------------------------------------------------------------------------
// H
tokenTraits.set(TokenType.I, { reg: true, reg8Spec: true });
tokenTraits.set(TokenType.IX, { reg: true, reg16Idx: true });
tokenTraits.set(TokenType.IY, { reg: true, reg16Idx: true });
tokenTraits.set(TokenType.Identifier, { expressionStart: true });
tokenTraits.set(TokenType.If, { statement: true });
tokenTraits.set(TokenType.IfDefDir, { directive: true });
tokenTraits.set(TokenType.IfDir, { directive: true });
tokenTraits.set(TokenType.IfModDir, { directive: true });
tokenTraits.set(TokenType.IfNDefDir, { directive: true });
tokenTraits.set(TokenType.IfNModDir, { directive: true });
tokenTraits.set(TokenType.IfNUsed, { statement: true });
tokenTraits.set(TokenType.IfUsed, { statement: true });
tokenTraits.set(TokenType.Im, { instruction: true });
tokenTraits.set(TokenType.In, { instruction: true });
tokenTraits.set(TokenType.Inc, { instruction: true });
tokenTraits.set(TokenType.IncludeBinPragma, { pragma: true });
tokenTraits.set(TokenType.IncludeDir, { directive: true });
tokenTraits.set(TokenType.Ind, { instruction: true, simple: true });
tokenTraits.set(TokenType.Indr, { instruction: true, simple: true });
tokenTraits.set(TokenType.Ini, { instruction: true, simple: true });
tokenTraits.set(TokenType.Inir, { instruction: true, simple: true });
tokenTraits.set(TokenType.InjectOptPragma, { pragma: true });
tokenTraits.set(TokenType.InlineComment, {});
tokenTraits.set(TokenType.IsCPort, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsCondition, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsExpr, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsIndexedAddr, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg16, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg16Idx, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg16Std, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg8, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg8Idx, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg8Spec, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsReg8Std, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegIndirect, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegA, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegAf, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegB, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegC, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegBc, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegD, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegE, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegDe, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegH, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegL, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegHl, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegI, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegR, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegXh, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegXl, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegIx, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegYh, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegYl, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegIy, {
expressionStart: true,
macroTimeFunction: true,
});
tokenTraits.set(TokenType.IsRegSp, {
expressionStart: true,
macroTimeFunction: true,
});
// ----------------------------------------------------------------------------
// J
tokenTraits.set(TokenType.Jp, { instruction: true });
tokenTraits.set(TokenType.Jr, { instruction: true });
// ----------------------------------------------------------------------------
// L
tokenTraits.set(TokenType.L, { reg: true, reg8: true });
tokenTraits.set(TokenType.LDBrac, { expressionStart: true });
tokenTraits.set(TokenType.LineDir, { directive: true });
tokenTraits.set(TokenType.LPar, { expressionStart: true });
tokenTraits.set(TokenType.LReg, {
expressionStart: true,
});
tokenTraits.set(TokenType.LSBrac, { expressionStart: true });
tokenTraits.set(TokenType.LTextOf, {
expressionStart: true,
parseTimeFunction: true,
});
tokenTraits.set(TokenType.Ld, { instruction: true });
tokenTraits.set(TokenType.Ldd, { instruction: true, simple: true });
tokenTraits.set(TokenType.Lddr, { instruction: true, simple: true });
tokenTraits.set(TokenType.Lddrx, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Lddx, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Ldi, { instruction: true, simple: true });
tokenTraits.set(TokenType.Ldir, { instruction: true, simple: true });
tokenTraits.set(TokenType.Ldirx, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Ldix, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Ldpirx, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Ldws, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.LeftShift, {});
tokenTraits.set(TokenType.LessThan, {});
tokenTraits.set(TokenType.LessThanOrEqual, {});
tokenTraits.set(TokenType.Local, { statement: true });
tokenTraits.set(TokenType.Loop, { statement: true });
// ----------------------------------------------------------------------------
// M
tokenTraits.set(TokenType.M, { condition: true });
tokenTraits.set(TokenType.Macro, { statement: true });
tokenTraits.set(TokenType.MaxOp, {});
tokenTraits.set(TokenType.MinOp, {});
tokenTraits.set(TokenType.Minus, { expressionStart: true });
tokenTraits.set(TokenType.Mirror, { instruction: true, next: true });
tokenTraits.set(TokenType.ModelPragma, { pragma: true });
tokenTraits.set(TokenType.Module, { statement: true });
tokenTraits.set(TokenType.Modulo, {});
tokenTraits.set(TokenType.Mul, { instruction: true, next: true });
tokenTraits.set(TokenType.Multiplication, {
expressionStart: true,
literal: true,
});
// ----------------------------------------------------------------------------
// N
tokenTraits.set(TokenType.NC, { condition: true, relCondition: true });
tokenTraits.set(TokenType.NZ, { condition: true, relCondition: true });
tokenTraits.set(TokenType.Neg, { instruction: true, simple: true });
tokenTraits.set(TokenType.Next, { statement: true });
tokenTraits.set(TokenType.NextReg, { instruction: true, next: true });
tokenTraits.set(TokenType.NoneArg, {});
tokenTraits.set(TokenType.Nop, { instruction: true, simple: true });
tokenTraits.set(TokenType.NotEqual, {});
// ----------------------------------------------------------------------------
// O
tokenTraits.set(TokenType.OctalLiteral, {
expressionStart: true,
literal: true,
});
tokenTraits.set(TokenType.Or, { instruction: true });
tokenTraits.set(TokenType.OrgPragma, { pragma: true });
tokenTraits.set(TokenType.Otdr, { instruction: true, simple: true });
tokenTraits.set(TokenType.Otir, { instruction: true, simple: true });
tokenTraits.set(TokenType.Out, { instruction: true });
tokenTraits.set(TokenType.OutInB, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Outd, { instruction: true, simple: true });
tokenTraits.set(TokenType.Outi, { instruction: true, simple: true });
// ----------------------------------------------------------------------------
// P
tokenTraits.set(TokenType.P, { condition: true });
tokenTraits.set(TokenType.PE, { condition: true });
tokenTraits.set(TokenType.PO, { condition: true });
tokenTraits.set(TokenType.PixelAd, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.PixelDn, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.Plus, { expressionStart: true });
tokenTraits.set(TokenType.Pop, { instruction: true });
tokenTraits.set(TokenType.Proc, { statement: true });
tokenTraits.set(TokenType.Push, { instruction: true });
// ----------------------------------------------------------------------------
// Q
tokenTraits.set(TokenType.QuestionMark, {});
// ----------------------------------------------------------------------------
// R
tokenTraits.set(TokenType.R, { reg: true, reg8Spec: true });
tokenTraits.set(TokenType.RDBrac, {});
tokenTraits.set(TokenType.RPar, {});
tokenTraits.set(TokenType.RSBrac, {});
tokenTraits.set(TokenType.RealLiteral, {
expressionStart: true,
literal: true,
});
tokenTraits.set(TokenType.Repeat, { statement: true });
tokenTraits.set(TokenType.Res, { instruction: true });
tokenTraits.set(TokenType.Ret, { instruction: true });
tokenTraits.set(TokenType.Reti, { instruction: true, simple: true });
tokenTraits.set(TokenType.Retn, { instruction: true, simple: true });
tokenTraits.set(TokenType.RightShift, {});
tokenTraits.set(TokenType.Rl, { instruction: true });
tokenTraits.set(TokenType.Rla, { instruction: true, simple: true });
tokenTraits.set(TokenType.Rlc, { instruction: true });
tokenTraits.set(TokenType.Rlca, { instruction: true, simple: true });
tokenTraits.set(TokenType.Rld, { instruction: true, simple: true });
tokenTraits.set(TokenType.RndSeedPragma, { pragma: true });
tokenTraits.set(TokenType.Rr, { instruction: true });
tokenTraits.set(TokenType.Rra, { instruction: true, simple: true });
tokenTraits.set(TokenType.Rrc, { instruction: true });
tokenTraits.set(TokenType.Rrca, { instruction: true, simple: true });
tokenTraits.set(TokenType.Rrd, { instruction: true, simple: true });
tokenTraits.set(TokenType.Rst, { instruction: true });
// ----------------------------------------------------------------------------
// S
tokenTraits.set(TokenType.SP, { reg: true, reg16: true });
tokenTraits.set(TokenType.Sbc, { instruction: true });
tokenTraits.set(TokenType.Scf, { instruction: true, simple: true });
tokenTraits.set(TokenType.Set, { instruction: true });
tokenTraits.set(TokenType.SetAE, {
instruction: true,
simple: true,
next: true,
});
tokenTraits.set(TokenType.SkipPragma, { pragma: true });
tokenTraits.set(TokenType.Sla, { instruction: true });
tokenTraits.set(TokenType.Sll, { instruction: true });
tokenTraits.set(TokenType.Sra, { instruction: true });
tokenTraits.set(TokenType.Srl, { instruction: true });
tokenTraits.set(TokenType.Step, {});
tokenTraits.set(TokenType.StringLiteral, {
expressionStart: true,
literal: true,
});
tokenTraits.set(TokenType.Struct, { statement: true });
tokenTraits.set(TokenType.Sub, { instruction: true });
tokenTraits.set(TokenType.Swapnib, {
instruction: true,
simple: true,
next: true,
});
// ----------------------------------------------------------------------------
// T
tokenTraits.set(TokenType.Test, { instruction: true, next: true });
tokenTraits.set(TokenType.TextOf, {
expressionStart: true,
parseTimeFunction: true,
});
tokenTraits.set(TokenType.To, {});
tokenTraits.set(TokenType.TracePragma, { pragma: true });
tokenTraits.set(TokenType.TraceHexPragma, { pragma: true });
tokenTraits.set(TokenType.True, { expressionStart: true, literal: true });
// ----------------------------------------------------------------------------
// U
tokenTraits.set(TokenType.UndefDir, {});
tokenTraits.set(TokenType.Until, { statement: true });
tokenTraits.set(TokenType.UpArrow, {});
// ----------------------------------------------------------------------------
// V
tokenTraits.set(TokenType.VarPragma, { pragma: true });
tokenTraits.set(TokenType.VerticalBar, {});
// ----------------------------------------------------------------------------
// W
tokenTraits.set(TokenType.While, { statement: true });
// ----------------------------------------------------------------------------
// X
tokenTraits.set(TokenType.XH, { reg: true, reg8Idx: true });
tokenTraits.set(TokenType.XL, { reg: true, reg8Idx: true });
tokenTraits.set(TokenType.XentPragma, { pragma: true });
tokenTraits.set(TokenType.Xor, { instruction: true });
tokenTraits.set(TokenType.XorgPragma, { pragma: true });
// ----------------------------------------------------------------------------
// Y
tokenTraits.set(TokenType.YH, { reg: true, reg8Idx: true });
tokenTraits.set(TokenType.YL, { reg: true, reg8Idx: true });
// ----------------------------------------------------------------------------
// Z
tokenTraits.set(TokenType.Z, { condition: true, relCondition: true });
tokenTraits.set(TokenType.ZxBasicPragma, { pragma: true }); | the_stack |
import * as React from 'react';
import type {
DOMRectSize,
ExtractFeatureFromClass,
MinimalWebViewProps,
WebshellProps
} from '../types';
import type {
HTMLDimensions,
HandleHTMLDimensionsFeature,
HTMLDimensionsImplementation
} from '../features/HandleHTMLDimensionsFeature';
import { StyleProp, ViewStyle } from 'react-native';
import Feature from '../Feature';
const initialDimensions = { width: undefined, height: undefined };
const overridenWebViewProps = {
scalesPageToFit: false,
showsVerticalScrollIndicator: false,
disableScrollViewPanResponder: true,
contentMode: 'mobile'
} as const;
const overridenWebViewKeys = Object.keys(overridenWebViewProps);
/**
* The state of synchronization between viewport and content size:
*
* - `init`: the initial state;
* - `syncing`: the content size is being determined;
* - `synced`: the viewport size has been adjusted to content size.
*
* @public
*/
export type AutoheightSyncState = 'init' | 'syncing' | 'synced';
/**
* The state returned by {@link useAutoheight} hook.
*
* @typeparam S - The type of the `Webshell` props used by this hook.
*
* @public
*/
export interface AutoheightState<
S extends WebshellProps<
MinimalWebViewProps,
[ExtractFeatureFromClass<typeof HandleHTMLDimensionsFeature>]
>
> {
/**
* The props to inject into webshell in order to support "autoheight"
* behavior.
*/
autoheightWebshellProps: Pick<
S,
| 'webshellDebug'
| 'onDOMHTMLDimensions'
| 'style'
| 'scalesPageToFit'
| 'showsVerticalScrollIndicator'
| 'disableScrollViewPanResponder'
| 'contentMode'
> &
Partial<S>;
/**
* The implementation used to generate resize events.
*/
resizeImplementation: HTMLDimensionsImplementation | null;
/**
* An object describing the content size. When the size is not yet known,
* this object fields will be undefined.
*/
contentSize: Partial<DOMRectSize>;
/**
* The state of synchronization between viewport and content size:
*
* - `'init'`: the initial, "onMount" state;
* - `'syncing'`: the content size is being determined;
* - `'synced'`: the viewport size has been adjusted to content size.
*
*/
syncState: AutoheightSyncState;
}
/**
* Named parameters for autoheight hook.
*
* @typeparam S - The type of the `Webshell` props used by this hook.
*
* @public
*/
export interface AutoheightParams<
S extends WebshellProps<MinimalWebViewProps, Feature<any, any>[]>
> {
/**
* It's best to pass all props directed to `Webshell` here. This is
* advised because the hook might react to specific props and warn you of
* some incompatibilities.
*/
webshellProps: S;
/**
* By default, the width of `Webshell` will grow to the horizontal space available.
* This is realized with `width: '100%'` and `alignSelf: 'stretch'`.
* If you need to set explicit width, do it here.
*/
width?: number;
/**
* The height occupied by the `WebView` prior to knowing its content height.
* It will be reused each time the source changes.
*
* @defaultValue 0
*/
initialHeight?: number;
/**
* When a width change is detected on viewport, the height of the `WebView`
* will be set to `undefined` for a few milliseconds. This will allow the
* best handling of height constraint in edge-cases with, for example,
* content expanding vertically (display: flex), at the cost of a small flash.
*
* @defaultValue true
*/
resetHeightOnViewportWidthChange?: boolean;
}
interface AutoheightInternalState {
implementation: HTMLDimensionsImplementation | null;
contentSize: Partial<DOMRectSize>;
syncState: AutoheightSyncState;
lastFrameChangedWidth: boolean;
viewportWidth: number;
}
const initialState: AutoheightInternalState = {
implementation: null,
contentSize: initialDimensions,
syncState: 'init',
lastFrameChangedWidth: false,
viewportWidth: 0
};
function useDevFeedbackEffect({
autoHeightParams: { webshellProps },
state: {
implementation,
contentSize: { width, height }
}
}: {
autoHeightParams: AutoheightParams<WebshellProps<MinimalWebViewProps, []>>;
state: AutoheightInternalState;
}) {
const numberOfEventsRef = React.useRef(0);
const { webshellDebug } = webshellProps;
const forbiddenWebViewProps = overridenWebViewKeys
.map((key) => [key, webshellProps[key]])
.reduce((prev, [key, value]) => {
prev[key] = value;
return prev;
}, {} as any);
React.useEffect(
function warnOverridenProps() {
for (const forbiddenKey of overridenWebViewKeys) {
if (
forbiddenWebViewProps[forbiddenKey] !== undefined &&
forbiddenWebViewProps[forbiddenKey] !==
overridenWebViewProps[forbiddenKey]
) {
console.warn(
`${useAutoheight.name}: You cannot set "${forbiddenKey}" prop to "${webshellProps[forbiddenKey]}" with autoheight hook. The value will be overriden to "${overridenWebViewProps[forbiddenKey]}".`
);
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[webshellDebug, ...Object.values(forbiddenWebViewProps)]
);
React.useEffect(
function debugDOMHTMLDimensions() {
webshellDebug &&
console.info(
`${
useAutoheight.name
}: DOMHTMLDimensions event #${++numberOfEventsRef.current} (implementation: ${implementation}, content width: ${width}, content height: ${height})`
);
},
[webshellDebug, implementation, height, width]
);
}
function useAutoheightState<
S extends WebshellProps<
MinimalWebViewProps,
[ExtractFeatureFromClass<typeof HandleHTMLDimensionsFeature>]
>
>(autoHeightParams: AutoheightParams<S>) {
const { webshellProps, initialHeight } = autoHeightParams;
const { source = {}, webshellDebug } = webshellProps;
const [state, setState] = React.useState<AutoheightInternalState>(
initialState
);
if (__DEV__) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useDevFeedbackEffect({ autoHeightParams, state });
}
React.useEffect(
function resetHeightOnSourceChanges() {
setState(({ contentSize, viewportWidth }) => ({
viewportWidth,
contentSize: {
height: undefined,
width: contentSize.width
},
implementation: null,
syncState: 'syncing',
lastFrameChangedWidth: false
}));
__DEV__ &&
webshellDebug &&
console.info(
`${useAutoheight.name}: source change detected, resetting height to ${initialHeight}dp.`
);
},
[source.uri, source.html, webshellDebug, initialHeight]
);
if (__DEV__) {
}
return { state, setState };
}
/**
*
* This hook will provide props to inject in a shell component to implement an "autoheight" behavior.
* It requires {@link HandleHTMLDimensionsFeature} to have be instantiated in the shell.
* Also recommend (see remarks):
*
* - {@link ForceElementSizeFeature},
* - {@link ForceResponsiveViewportFeature}.
*
* @remarks
* This hook has caveats you must understand:
*
* - Because the viewport height is now bound to the content heigh, you cannot
* and must not have an element which height depends on viewport, such as
* when using `vh` unit or `height: 100%;` on body. That will either create
* an infinite loop, or a zero-height page (this happens for Wikipedia).
* Hence, it is strongly advised that you use autoheight only with content
* you have been able to test. This can be worked around by forcing body
* height to 'auto', see {@link ForceElementSizeFeature}.
* - In some circumstances, the mobile browser might use a virtual
* viewport much larger then the available width in the `<WebView />`, often
* around 980px for websites which have been built for desktop. For
* this autoheight component to be reliable, you must ensure that the
* content has a [meta viewport element](https://www.w3schools.com/css/css_rwd_viewport.asp)
* in the header. You can enforce this behavior with {@link ForceResponsiveViewportFeature}.
*
* @example
*
* ```tsx
* export default function MinimalAutoheightWebView(
* webshellProps: ComponentProps<typeof Webshell>
* ) {
* const { autoheightWebshellProps } = useAutoheight({
* webshellProps
* });
* return <Webshell {...autoheightWebshellProps} />;
* }
* ```
*
* @param params - The parameters to specify autoheight behavior.
* @typeparam S - The type of the `Webshell` props used by this hook.
* @returns - An object to implement autoheight behavior.
*
* @public
*/
export default function useAutoheight<
S extends WebshellProps<
MinimalWebViewProps,
[ExtractFeatureFromClass<typeof HandleHTMLDimensionsFeature>]
>
>(params: AutoheightParams<S>): AutoheightState<S> {
const {
webshellProps,
initialHeight = 0,
width: userExplicitWidth,
resetHeightOnViewportWidthChange = true
} = params;
const {
style,
onNavigationStateChange,
scalesPageToFit,
webshellDebug,
onDOMHTMLDimensions,
...passedProps
} = webshellProps;
const { state, setState } = useAutoheightState(params);
const {
contentSize: { height },
implementation,
lastFrameChangedWidth
} = state;
const shouldReinitNextFrameHeight =
typeof userExplicitWidth !== 'number' &&
lastFrameChangedWidth &&
resetHeightOnViewportWidthChange;
const handleOnDOMHTMLDimensions = React.useCallback(
function handleOnDOMHTMLDimensions(htmlDimensions: HTMLDimensions) {
setState((prevState) => {
return {
viewportWidth: htmlDimensions.layoutViewport.width,
implementation: htmlDimensions.implementation,
contentSize: htmlDimensions.content,
syncState: 'synced',
lastFrameChangedWidth:
prevState.viewportWidth !== htmlDimensions.layoutViewport.width
};
});
typeof onDOMHTMLDimensions === 'function' &&
onDOMHTMLDimensions(htmlDimensions);
},
[setState, onDOMHTMLDimensions]
);
const autoHeightStyle = React.useMemo<StyleProp<ViewStyle>>(
() => [
style as StyleProp<ViewStyle>,
{
width:
typeof userExplicitWidth === 'number' ? userExplicitWidth : '100%',
height: shouldReinitNextFrameHeight
? undefined
: typeof height === 'number'
? height
: initialHeight,
alignSelf: 'stretch'
}
],
[
height,
userExplicitWidth,
initialHeight,
style,
shouldReinitNextFrameHeight
]
);
React.useEffect(
function resetLastFrameChangedWidth() {
const timeout = setTimeout(
() =>
setState((prevState) => ({
...prevState,
lastFrameChangedWidth: false
})),
50
);
return () => clearTimeout(timeout);
},
[shouldReinitNextFrameHeight, setState]
);
return {
autoheightWebshellProps: {
...passedProps,
webshellDebug,
onDOMHTMLDimensions: handleOnDOMHTMLDimensions,
style: autoHeightStyle,
...overridenWebViewProps
} as AutoheightState<S>['autoheightWebshellProps'],
resizeImplementation: implementation,
contentSize: state.contentSize,
syncState: state.syncState
};
} | the_stack |
// tslint:disable:function-name // Grandfathered in
// tslint:disable:cyclomatic-complexity // Grandfathered in
// tslint:disable:variable-name
// tslint:disable-next-line:no-suspicious-comment
// TODO: rename this module to refer to "basic tokens", etc.
import * as Iterator from "../../util/Iterator";
/**
* The different types of tokens that can be generated by a basic Tokenizer.
* This tokenizer knows nothing about JSON, it just recognizes basic punctuation
* and groups of digits and letters (not grouped into numbers or strings etc).
*/
export const enum TokenType {
LeftCurlyBracket,
RightCurlyBracket,
LeftSquareBracket,
RightSquareBracket,
LeftParenthesis,
RightParenthesis,
Underscore,
Period,
Dash,
Plus,
Comma,
Colon,
SingleQuote,
DoubleQuote,
Backslash,
ForwardSlash,
Asterisk,
Space,
Tab,
NewLine,
CarriageReturn,
CarriageReturnNewLine,
Letters,
Digits,
Unrecognized
}
/**
* An individual Token that has been parsed by a basic Tokenizer.
*/
export class Token {
constructor(private _text: string, private _type: TokenType) {
}
/**
* Gets the original string that this basic token was parsed from.
*/
public toString(): string {
return this._text;
}
/**
* Get the number of characters that make up this token.
*/
public length(): number {
return this._text.length;
}
/**
* Get the type of this token.
*/
public getType(): TokenType {
return this._type;
}
/**
* Convenient way of seeing what this token represents in the debugger, shouldn't be used for production code
*/
public get __debugDisplay(): string {
return `<${this.toString()}>`;
}
}
export const LeftCurlyBracket = new Token("{", TokenType.LeftCurlyBracket);
export const RightCurlyBracket = new Token("}", TokenType.RightCurlyBracket);
export const LeftSquareBracket = new Token("[", TokenType.LeftSquareBracket);
export const RightSquareBracket = new Token("]", TokenType.RightSquareBracket);
export const LeftParenthesis = new Token("(", TokenType.LeftParenthesis);
export const RightParenthesis = new Token(")", TokenType.RightParenthesis);
export const Underscore = new Token("_", TokenType.Underscore);
export const Period = new Token(".", TokenType.Period);
export const Dash = new Token("-", TokenType.Dash);
export const Plus = new Token("+", TokenType.Plus);
export const Comma = new Token(",", TokenType.Comma);
export const Colon = new Token(":", TokenType.Colon);
export const SingleQuote = new Token(`'`, TokenType.SingleQuote);
export const DoubleQuote = new Token(`"`, TokenType.DoubleQuote);
export const Backslash = new Token("\\", TokenType.Backslash);
export const ForwardSlash = new Token("/", TokenType.ForwardSlash);
export const Asterisk = new Token("*", TokenType.Asterisk);
export const Space = new Token(" ", TokenType.Space);
export const Tab = new Token("\t", TokenType.Tab);
export const NewLine = new Token("\n", TokenType.NewLine);
export const CarriageReturn = new Token("\r", TokenType.CarriageReturn);
export const CarriageReturnNewLine = new Token("\r\n", TokenType.CarriageReturnNewLine);
/**
* Create a Letters Token from the provided text.
*/
export function Letters(text: string): Token {
return new Token(text, TokenType.Letters);
}
/**
* Create a Digits Token from the provided text.
*/
export function Digits(text: string): Token {
return new Token(text, TokenType.Digits);
}
/**
* Create an Unrecognized Token from the provided text.
*/
export function Unrecognized(text: string): Token {
return new Token(text, TokenType.Unrecognized);
}
/**
* A Tokenizer that breaks a provided text string into a sequence of basic Tokens.
*/
export class Tokenizer implements Iterator.Iterator<Token> {
private _textLength: number;
private _textIndex: number = -1;
private _currentToken: Token | undefined;
constructor(private _text: string) {
this._textLength = _text ? _text.length : 0;
}
/**
* Convenient way of seeing what this object represents in the debugger, shouldn't be used for production code
*/
public get __debugDisplay(): string {
const charactersBeforeCurrent = 25;
const charactersAfterCurrent = 50;
return `${this._text.slice(this._textIndex - charactersBeforeCurrent, this._textIndex)}<<${this._currentToken ? this._currentToken.toString() : ''}>>${this._text.slice(this._textIndex + 1, this._textIndex + 1 + charactersAfterCurrent)}`;
}
/**
* Get whether this Tokenizer has started tokenizing its text string.
*/
public hasStarted(): boolean {
return 0 <= this._textIndex;
}
/**
* Get the current Token that this Tokenizer has parsed from the source text. If this Tokenizer
* hasn't started parsing the source text, or if it has parsed the entire source text, then this
* will return undefined.
*/
public current(): Token | undefined {
return this._currentToken;
}
/**
* Get the current character that this Tokenizer is pointing at.
*/
private get currentCharacter(): string | undefined {
return 0 <= this._textIndex && this._textIndex < this._textLength ? this._text[this._textIndex] : undefined;
}
/**
* Move this Tokenizer to the next character in its source text.
*/
private nextCharacter(): void {
++this._textIndex;
}
/**
* Move this Tokenizer to the next Token in the source text string.
* @returns True if there is a current token after moving
*/
// tslint:disable-next-line:max-func-body-length
public moveNext(): boolean {
if (!this.hasStarted()) {
this.nextCharacter();
}
if (!this.currentCharacter) {
this._currentToken = undefined;
} else {
switch (this.currentCharacter) {
case "{":
this._currentToken = LeftCurlyBracket;
this.nextCharacter();
break;
case "}":
this._currentToken = RightCurlyBracket;
this.nextCharacter();
break;
case "[":
this._currentToken = LeftSquareBracket;
this.nextCharacter();
break;
case "]":
this._currentToken = RightSquareBracket;
this.nextCharacter();
break;
case "(":
this._currentToken = LeftParenthesis;
this.nextCharacter();
break;
case ")":
this._currentToken = RightParenthesis;
this.nextCharacter();
break;
case "_":
this._currentToken = Underscore;
this.nextCharacter();
break;
case ".":
this._currentToken = Period;
this.nextCharacter();
break;
case "-":
this._currentToken = Dash;
this.nextCharacter();
break;
case "+":
this._currentToken = Plus;
this.nextCharacter();
break;
case ",":
this._currentToken = Comma;
this.nextCharacter();
break;
case ":":
this._currentToken = Colon;
this.nextCharacter();
break;
case `'`:
this._currentToken = SingleQuote;
this.nextCharacter();
break;
case `"`:
this._currentToken = DoubleQuote;
this.nextCharacter();
break;
case "\\":
this._currentToken = Backslash;
this.nextCharacter();
break;
case "/":
this._currentToken = ForwardSlash;
this.nextCharacter();
break;
case "*":
this._currentToken = Asterisk;
this.nextCharacter();
break;
case "\n":
this._currentToken = NewLine;
this.nextCharacter();
break;
case "\r":
this.nextCharacter();
// tslint:disable-next-line: strict-boolean-expressions // false positive - nextCharacter modifies this.currentCharacter from "\r" value
if (this.currentCharacter && this.currentCharacter.toString() === "\n") {
this._currentToken = CarriageReturnNewLine;
this.nextCharacter();
} else {
this._currentToken = CarriageReturn;
}
break;
case " ":
this._currentToken = Space;
this.nextCharacter();
break;
case "\t":
this._currentToken = Tab;
this.nextCharacter();
break;
default:
if (isLetter(this.currentCharacter)) {
this._currentToken = Letters(this.readWhile(isLetter));
} else if (isDigit(this.currentCharacter)) {
this._currentToken = Digits(this.readWhile(isDigit));
} else {
this._currentToken = Unrecognized(this.currentCharacter);
this.nextCharacter();
}
break;
}
}
return !!this._currentToken;
}
/**
* Read and return a sequence of characters from the source text that match the provided
* condition function.
*/
private readWhile(condition: (character: string) => boolean): string {
// tslint:disable-next-line: strict-boolean-expressions
let result: string = this.currentCharacter || '';
this.nextCharacter();
while (this.currentCharacter && condition(this.currentCharacter)) {
result += this.currentCharacter;
this.nextCharacter();
}
return result;
}
}
/**
* Get whether the provided character is a letter or not.
*/
function isLetter(character: string): boolean {
return ("a" <= character && character <= "z") || ("A" <= character && character <= "Z");
}
/**
* Get whether the provided character is a digit or not.
*/
function isDigit(character: string): boolean {
return "0" <= character && character <= "9";
} | the_stack |
import {
AlfrescoApiService,
NodesApiService,
SearchService,
TranslationService,
EcmUserModel
} from '@alfresco/adf-core';
import {
Group,
GroupMemberEntry,
GroupMemberPaging, GroupsApi,
Node,
PathElement,
PermissionElement,
QueryBody
} from '@alfresco/js-api';
import { Injectable } from '@angular/core';
import { forkJoin, from, Observable, of, throwError } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { PermissionDisplayModel } from '../models/permission.model';
import { RoleModel } from '../models/role.model';
@Injectable({
providedIn: 'root'
})
export class NodePermissionService {
_groupsApi: GroupsApi;
get groupsApi(): GroupsApi {
this._groupsApi = this._groupsApi ?? new GroupsApi(this.apiService.getInstance());
return this._groupsApi;
}
constructor(private apiService: AlfrescoApiService,
private searchApiService: SearchService,
private nodeService: NodesApiService,
private translation: TranslationService) {
}
/**
* Gets a list of roles for the current node.
* @param node The target node
* @returns Array of strings representing the roles
*/
getNodeRoles(node: Node): Observable<string[]> {
const retrieveSiteQueryBody: QueryBody = this.buildRetrieveSiteQueryBody(node.path.elements);
return this.searchApiService.searchByQueryBody(retrieveSiteQueryBody)
.pipe(
switchMap((siteNodeList: any) => {
if (siteNodeList.list.entries.length > 0) {
const siteName = siteNodeList.list.entries[0].entry.name;
return this.getGroupMembersBySiteName(siteName);
} else {
return of(node.permissions?.settable);
}
})
);
}
getNodePermissions(node: Node): PermissionDisplayModel[] {
const result: PermissionDisplayModel[] = [];
if (node?.permissions?.locallySet) {
node.permissions.locallySet.map((permissionElement) => {
result.push(new PermissionDisplayModel(permissionElement));
});
}
if (node?.permissions?.inherited) {
node.permissions.inherited.map((permissionElement) => {
const permissionInherited = new PermissionDisplayModel(permissionElement);
permissionInherited.isInherited = true;
result.push(permissionInherited);
});
}
return result;
}
/**
* Updates the permission role for a node.
* @param node Target node
* @param updatedPermissionRole Permission role to update or add
* @returns Node with updated permission
*/
updatePermissionRole(node: Node, updatedPermissionRole: PermissionElement): Observable<Node> {
const permissionBody = { permissions: { locallySet: [] } };
const index = node.permissions.locallySet.map((permission) => permission.authorityId).indexOf(updatedPermissionRole.authorityId);
permissionBody.permissions.locallySet = permissionBody.permissions.locallySet.concat(node.permissions.locallySet);
if (index !== -1) {
permissionBody.permissions.locallySet[index] = updatedPermissionRole;
} else {
permissionBody.permissions.locallySet.push(updatedPermissionRole);
}
return this.nodeService.updateNode(node.id, permissionBody);
}
/**
* Update permissions for a node.
* @param nodeId ID of the target node
* @param permissionList New permission settings
* @returns Node with updated permissions
*/
updateNodePermissions(nodeId: string, permissionList: PermissionElement[]): Observable<Node> {
return this.nodeService.getNode(nodeId).pipe(
switchMap((node) => this.updateLocallySetPermissions(node, permissionList))
);
}
/**
* Updates the locally set permissions for a node.
* @param node ID of the target node
* @param permissions Permission settings
* @returns Node with updated permissions
*/
updateLocallySetPermissions(node: Node, permissions: PermissionElement[]): Observable<Node> {
const permissionBody = { permissions: { locallySet: [] } };
const permissionList = permissions;
const duplicatedPermissions = this.getDuplicatedPermissions(node.permissions.locallySet, permissionList);
if (duplicatedPermissions.length > 0) {
const list = duplicatedPermissions.map((permission) => 'authority -> ' + permission.authorityId + ' / role -> ' + permission.name).join(', ');
const duplicatePermissionMessage: string = this.translation.instant('PERMISSION_MANAGER.ERROR.DUPLICATE-PERMISSION', { list });
return throwError(duplicatePermissionMessage);
}
permissionBody.permissions.locallySet = node.permissions.locallySet ? node.permissions.locallySet.concat(permissionList) : permissionList;
return this.nodeService.updateNode(node.id, permissionBody);
}
private getDuplicatedPermissions(nodeLocallySet: PermissionElement[], permissionListAdded: PermissionElement[]): PermissionElement[] {
const duplicatePermissions: PermissionElement[] = [];
if (nodeLocallySet) {
permissionListAdded.forEach((permission: PermissionElement) => {
const duplicate = nodeLocallySet.find((localPermission) => this.isEqualPermission(localPermission, permission));
if (duplicate) {
duplicatePermissions.push(duplicate);
}
});
}
return duplicatePermissions;
}
private isEqualPermission(oldPermission: PermissionElement, newPermission: PermissionElement): boolean {
return oldPermission.accessStatus === newPermission.accessStatus &&
oldPermission.authorityId === newPermission.authorityId &&
oldPermission.name === newPermission.name;
}
/**
* Removes a permission setting from a node.
* @param node ID of the target node
* @param permissionToRemove Permission setting to remove
* @returns Node with modified permissions
*/
removePermission(node: Node, permissionToRemove: PermissionElement): Observable<Node> {
const permissionBody = { permissions: { locallySet: [] } };
const index = node.permissions.locallySet.map((permission) => permission.authorityId).indexOf(permissionToRemove.authorityId);
if (index !== -1) {
node.permissions.locallySet.splice(index, 1);
permissionBody.permissions.locallySet = node.permissions.locallySet;
return this.nodeService.updateNode(node.id, permissionBody);
} else {
return of(node);
}
}
private getGroupMembersBySiteName(siteName: string): Observable<string[]> {
const groupName = 'GROUP_site_' + siteName;
return this.getGroupMemberByGroupName(groupName)
.pipe(
map((groupMemberPaging: GroupMemberPaging) => {
const displayResult: string[] = [];
groupMemberPaging.list.entries.forEach((member: GroupMemberEntry) => {
displayResult.push(this.formattedRoleName(member.entry.displayName, 'site_' + siteName));
});
return displayResult;
})
);
}
/**
* Gets all members related to a group name.
* @param groupName Name of group to look for members
* @param opts Extra options supported by JS-API
* @returns List of members
*/
getGroupMemberByGroupName(groupName: string, opts?: any): Observable<GroupMemberPaging> {
return from(this.groupsApi.listGroupMemberships(groupName, opts));
}
private formattedRoleName(displayName, siteName): string {
return displayName.replace(siteName + '_', '');
}
private buildRetrieveSiteQueryBody(nodePath: PathElement[]): QueryBody {
const pathNames = nodePath.map((node: PathElement) => 'name: "' + node.name + '"');
const builtPathNames = pathNames.join(' OR ');
return {
'query': {
'query': builtPathNames
},
'paging': {
'maxItems': 100,
'skipCount': 0
},
'include': ['aspectNames', 'properties'],
'filterQueries': [
{
'query':
"TYPE:'st:site'"
}
]
};
}
getLocalPermissions(node: Node): PermissionDisplayModel[] {
const result: PermissionDisplayModel[] = [];
if (node?.permissions?.locallySet) {
node.permissions.locallySet.forEach((permissionElement) => {
result.push(new PermissionDisplayModel(permissionElement));
});
}
return result;
}
getInheritedPermission(node: Node): PermissionDisplayModel[] {
const result: PermissionDisplayModel[] = [];
if (node?.permissions?.inherited) {
node.permissions.inherited.forEach((permissionElement) => {
const permissionInherited = new PermissionDisplayModel(permissionElement);
permissionInherited.isInherited = true;
result.push(permissionInherited);
});
}
return result;
}
/**
* Removes permissions setting from a node.
* @param node target node with permission
* @param permissions Permissions to remove
* @returns Node with modified permissions
*/
removePermissions(node: Node, permissions: PermissionElement[]): Observable<Node> {
const permissionBody = { permissions: { locallySet: [] } };
permissions.forEach((permission) => {
const index = node.permissions.locallySet.findIndex((locallySet) => locallySet.authorityId === permission.authorityId);
if (index !== -1) {
node.permissions.locallySet.splice(index, 1);
}
});
permissionBody.permissions.locallySet = node.permissions.locallySet;
return this.nodeService.updateNode(node.id, permissionBody);
}
/**
* updates permissions setting from a node.
* @param node target node with permission
* @param permissions Permissions to update
* @returns Node with modified permissions
*/
updatePermissions(node: Node, permissions: PermissionElement[]): Observable<Node> {
const permissionBody = { permissions: { locallySet: [] } };
permissionBody.permissions.locallySet = permissions;
return this.nodeService.updateNode(node.id, permissionBody);
}
/**
* Gets all node detail for nodeId along with settable permissions.
* @param nodeId Id of the node
* @returns node and it's associated roles { node: Node; roles: RoleModel[] }
*/
getNodeWithRoles(nodeId: string): Observable<{ node: Node; roles: RoleModel[] }> {
return this.nodeService.getNode(nodeId).pipe(
switchMap(node => {
return forkJoin({
node: of(node),
roles: this.getNodeRoles(node)
.pipe(
catchError(() => of(node.permissions?.settable)),
map(_roles => _roles.map(role => ({ role, label: role }))
)
)
});
})
);
}
transformNodeToUserPerson(node: Node): { person: EcmUserModel, group: Group } {
let person = null, group = null;
if (node.nodeType === 'cm:person') {
const firstName = node.properties['cm:firstName'];
const lastName = node.properties['cm:lastName'];
const email = node.properties['cm:email'];
const id = node.properties['cm:userName'];
person = new EcmUserModel({ id, firstName, lastName, email });
}
if (node.nodeType === 'cm:authorityContainer') {
const displayName = node.properties['cm:authorityDisplayName'] || node.properties['cm:authorityName'];
const id = node.properties['cm:authorityName'];
group = new Group({ displayName, id });
}
return { person, group };
}
} | the_stack |
import {
PageRequesterData,
Chapter,
Series,
SeriesSourceType,
WebviewFunc,
ExtensionClientInterface,
SettingType,
ExtensionMetadata,
SeriesListResponse,
WebviewResponse,
} from 'houdoku-extension-lib';
import aki, {
RegistrySearchPackage,
RegistrySearchResults,
} from 'aki-plugin-manager';
import { IpcMain } from 'electron';
import fetch from 'node-fetch';
import DOMParser from 'dom-parser';
import log from 'electron-log';
import { gt } from 'semver';
import { FSExtensionClient, FS_METADATA } from './extensions/filesystem';
import ipcChannels from '../constants/ipcChannels.json';
const domParser = new DOMParser();
const EXTENSION_CLIENTS: { [key: string]: ExtensionClientInterface } = {};
export async function loadExtensions(
pluginsDir: string,
webviewFn: WebviewFunc
) {
log.info('Loading extensions...');
Object.keys(EXTENSION_CLIENTS).forEach((extensionId: string) => {
const extMetadata = EXTENSION_CLIENTS[extensionId].getMetadata();
if (extMetadata.id !== FS_METADATA.id) {
aki.unload(
pluginsDir,
`@houdoku/extension-${extMetadata.name
.toLowerCase()
.replaceAll(' ', '')}`,
// eslint-disable-next-line no-eval
eval('require') as NodeRequire
);
}
delete EXTENSION_CLIENTS[extensionId];
log.info(`Unloaded extension ${extMetadata.name} (ID ${extensionId})`);
});
const fsExtensionClient = new FSExtensionClient(fetch, webviewFn, domParser);
EXTENSION_CLIENTS[fsExtensionClient.getMetadata().id] = fsExtensionClient;
aki.list(pluginsDir).forEach((pluginDetails: [string, string]) => {
const pluginName = pluginDetails[0];
if (pluginName.startsWith('@houdoku/extension-')) {
const mod = aki.load(
pluginsDir,
pluginName,
// eslint-disable-next-line no-eval
eval('require') as NodeRequire
);
const client = new mod.ExtensionClient(fetch, webviewFn, domParser);
log.info(`Loaded extension "${pluginName}" version ${pluginDetails[1]}`);
EXTENSION_CLIENTS[client.getMetadata().id] = client;
}
});
}
/**
* Get a series from an extension.
*
* The series is populated with fields provided by the content source, and is sufficient to be
* imported into the user's library. Note that the id field will be undefined since that refers
* to the id for the series after being imported.
*
* @param extensionId
* @param sourceType the type of the series source
* @param seriesId
* @returns promise for the matching series
*/
function getSeries(
extensionId: string,
sourceType: SeriesSourceType,
seriesId: string
): Promise<Series | undefined> {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Getting series ${seriesId} from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
return extension.getSeries(sourceType, seriesId).catch((err: Error) => {
log.error(err);
return undefined;
});
}
/**
* Get a list of chapters for a series on the content source.
*
* Chapters are populated with fields provided by the content source. Note that there may be
* multiple instances of the "same" chapter which are actually separate releases (either by
* different groups or in different languages).
*
* @param extensionId
* @param sourceType the type of the series source
* @param seriesId
* @returns promise for a list of chapters
*/
function getChapters(
extensionId: string,
sourceType: SeriesSourceType,
seriesId: string
): Promise<Chapter[]> {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Getting chapters for series ${seriesId} from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
return extension.getChapters(sourceType, seriesId).catch((err: Error) => {
log.error(err);
return [];
});
}
/**
* Get a PageRequesterData object with values for getting individual page URLs.
*
* The PageRequesterData is solely used to be provided to getPageUrls, and should be considered
* unique for each chapter (it will only work for the chapter with id specified to this function).
*
* @param extensionId
* @param sourceType the type of the series source
* @param seriesSourceId
* @param chapterSourceId
* @returns promise for the PageRequesterData for this chapter
*/
function getPageRequesterData(
extensionId: string,
sourceType: SeriesSourceType,
seriesSourceId: string,
chapterSourceId: string
): Promise<PageRequesterData> {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Getting page requester data for series ${seriesSourceId} chapter ${chapterSourceId} from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
return extension
.getPageRequesterData(sourceType, seriesSourceId, chapterSourceId)
.catch((err: Error) => {
log.error(err);
return { server: '', hash: '', numPages: 0, pageFilenames: [] };
});
}
/**
* Get page URLs for a chapter.
*
* The values from this function CANNOT be safely used as an image source; they must be passed to
* getPageData which is strictly for that purpose.
*
* @param extensionId
* @param pageRequesterData the PageRequesterData from getPageRequesterData for this chapter
* @returns a list of urls for this chapter which can be passed to getPageData
*/
function getPageUrls(
extensionId: string,
pageRequesterData: PageRequesterData
): string[] {
try {
const pageUrls =
EXTENSION_CLIENTS[extensionId].getPageUrls(pageRequesterData);
return pageUrls;
} catch (err) {
return [];
}
}
/**
* Get data for a page.
*
* The value from this function (within the promise) can be put inside the src tag of an HTML <img>.
* In most cases it is simply a promise for the provided URL; however, that cannot be guaranteed
* since we may also need to load data from an archive.
*
* @param extensionId
* @param series
* @param url the URL for the page from getPageUrls
* @returns promise for page data that can be put inside an <img> src
*/
async function getPageData(
extensionId: string,
series: Series,
url: string
): Promise<string> {
return EXTENSION_CLIENTS[extensionId]
.getPageData(series, url)
.catch((err: Error) => {
log.error(err);
return '';
});
}
/**
* Search for a series.
*
* @param extensionId
* @param text the user's search input; this can contain parameters in the form "key:value" which
* are utilized at the extension's discretion
* @returns promise for SeriesListResponse
*/
function search(
extensionId: string,
text: string,
page: number
): Promise<SeriesListResponse> {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Searching for "${text}" from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
let adjustedText: string = text;
const paramsRegExp = new RegExp(/\S*:\S*/g);
const matchParams: RegExpMatchArray | null = text.match(paramsRegExp);
let params: { [key: string]: string } = {};
if (matchParams !== null) {
matchParams.forEach((match: string) => {
const parts: string[] = match.split(':');
params = { [parts[0]]: parts[1], ...params };
});
adjustedText = text.replace(paramsRegExp, '');
}
return extension.getSearch(adjustedText, params, page).catch((err: Error) => {
log.error(err);
return { seriesList: [], hasMore: false };
});
}
/**
* Get the directory for a content source (often the same as an empty search).
*
* @param extensionId
* @returns promise for SeriesListResponse
*/
function directory(
extensionId: string,
page: number
): Promise<SeriesListResponse> {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Getting directory from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
return extension.getDirectory(page).catch((err: Error) => {
log.error(err);
return { seriesList: [], hasMore: false };
});
}
/**
* Get types for an extension's settings.
*
* @param extensionId
* @returns map of settings from the extension to their SettingType
*/
function getSettingTypes(extensionId: string): { [key: string]: SettingType } {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Getting setting types from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
try {
return extension.getSettingTypes();
} catch (err) {
log.error(err);
return {};
}
}
/**
* Get settings for the extension.
*
* @param extensionId
* @returns map of settings from the extension, with default/initial values set
*/
function getSettings(extensionId: string): { [key: string]: unknown } {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Getting settings from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
try {
return extension.getSettings();
} catch (err) {
log.error(err);
return {};
}
}
/**
* Set the settings for an extension.
*
* @param extensionId
* @param settings a map of settings for the extension
*/
function setSettings(
extensionId: string,
settings: { [key: string]: unknown }
): void {
const extension = EXTENSION_CLIENTS[extensionId];
log.info(
`Setting settings from extension ${extensionId} (v=${
extension.getMetadata().version
})`
);
try {
extension.setSettings(settings);
} catch (err) {
log.error(err);
}
}
export const createExtensionIpcHandlers = (
ipcMain: IpcMain,
pluginsDir: string,
webviewFn: (url: string) => Promise<WebviewResponse>
) => {
log.debug('Creating extension IPC handlers in main...');
ipcMain.handle(ipcChannels.EXTENSION_MANAGER.RELOAD, async (event) => {
await loadExtensions(pluginsDir, webviewFn);
return event.sender.send(ipcChannels.APP.LOAD_STORED_EXTENSION_SETTINGS);
});
ipcMain.handle(
ipcChannels.EXTENSION_MANAGER.INSTALL,
(_event, name: string, version: string) => {
return new Promise<void>((resolve) => {
aki.install(name, version, pluginsDir, () => {
resolve();
});
});
}
);
ipcMain.handle(
ipcChannels.EXTENSION_MANAGER.UNINSTALL,
(_event, name: string) => {
return new Promise<void>((resolve) => {
aki.uninstall(name, pluginsDir, () => {
resolve();
});
});
}
);
ipcMain.handle(ipcChannels.EXTENSION_MANAGER.LIST, async () => {
return aki.list(pluginsDir);
});
ipcMain.handle(
ipcChannels.EXTENSION_MANAGER.GET,
async (_event, extensionId: string) => {
return extensionId in EXTENSION_CLIENTS
? EXTENSION_CLIENTS[extensionId].getMetadata()
: undefined;
}
);
ipcMain.handle(ipcChannels.EXTENSION_MANAGER.GET_ALL, () => {
return Object.values(EXTENSION_CLIENTS).map(
(client: ExtensionClientInterface) => client.getMetadata()
);
});
ipcMain.handle(ipcChannels.EXTENSION_MANAGER.CHECK_FOR_UPDATESS, async () => {
if (Object.values(EXTENSION_CLIENTS).length <= 1) return {};
log.debug('Checking for extension updates...');
const availableUpdates: {
[key: string]: { metadata: ExtensionMetadata; newVersion: string };
} = {};
const registryResults: RegistrySearchResults = await aki.search(
'extension',
'houdoku',
100
);
registryResults.objects.forEach((registryResult) => {
const pkg: RegistrySearchPackage = registryResult.package;
const description = JSON.parse(pkg.description);
if (description.id in EXTENSION_CLIENTS) {
const metadata = EXTENSION_CLIENTS[description.id].getMetadata();
if (gt(pkg.version, metadata.version)) {
availableUpdates[metadata.id] = {
metadata,
newVersion: pkg.version,
};
}
}
});
log.debug(
`Found ${
Object.values(availableUpdates).length
} available extension updates`
);
return availableUpdates;
});
ipcMain.handle(
ipcChannels.EXTENSION.GET_SERIES,
(
_event,
extensionId: string,
sourceType: SeriesSourceType,
seriesId: string
) => {
return getSeries(extensionId, sourceType, seriesId);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.GET_CHAPTERS,
(
_event,
extensionId: string,
sourceType: SeriesSourceType,
seriesId: string
) => {
return getChapters(extensionId, sourceType, seriesId);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.GET_PAGE_REQUESTER_DATA,
(
_event,
extensionId: string,
sourceType: SeriesSourceType,
seriesSourceId: string,
chapterSourceId: string
) => {
return getPageRequesterData(
extensionId,
sourceType,
seriesSourceId,
chapterSourceId
);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.GET_PAGE_URLS,
(_event, extensionId: string, pageRequesterData: PageRequesterData) => {
return getPageUrls(extensionId, pageRequesterData);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.GET_PAGE_DATA,
(_event, extensionId: string, series: Series, url: string) => {
return getPageData(extensionId, series, url);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.SEARCH,
(_event, extensionId: string, text: string, page: number) => {
return search(extensionId, text, page);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.DIRECTORY,
(_event, extensionId: string, page: number) => {
return directory(extensionId, page);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.GET_SETTING_TYPES,
(_event, extensionId: string) => {
return getSettingTypes(extensionId);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.GET_SETTINGS,
(_event, extensionId: string) => {
return getSettings(extensionId);
}
);
ipcMain.handle(
ipcChannels.EXTENSION.SET_SETTINGS,
(_event, extensionId: string, settings: { [key: string]: unknown }) => {
return setSettings(extensionId, settings);
}
);
}; | the_stack |
import { ContainerAdapterClient } from '../../container_adapter_client'
import { MasterNodeRegTestContainer } from '@defichain/testcontainers'
import {
ExtHTLC,
HTLC,
ICXClaimDFCHTLCInfo,
ICXDFCHTLCInfo,
ICXEXTHTLCInfo,
ICXGenericResult,
ICXHTLCType,
ICXListHTLCOptions,
ICXOffer,
ICXOfferInfo,
ICXOrder,
ICXOrderInfo,
ICXOrderStatus
} from '../../../src/category/icxorderbook'
import BigNumber from 'bignumber.js'
import { accountBTC, accountDFI, ICXSetup, idDFI, symbolDFI } from './icx_setup'
import { RpcApiError } from '../../../src'
describe('ICXOrderBook.submitExtHTLC', () => {
const container = new MasterNodeRegTestContainer()
const client = new ContainerAdapterClient(container)
const icxSetup = new ICXSetup(container, client)
beforeAll(async () => {
await container.start()
await container.waitForReady()
await container.waitForWalletCoinbaseMaturity()
await icxSetup.createAccounts()
await icxSetup.createBTCToken()
await icxSetup.initializeTokensIds()
await icxSetup.mintBTCtoken(100)
await icxSetup.fundAccount(accountDFI, symbolDFI, 500)
await icxSetup.fundAccount(accountBTC, symbolDFI, 10) // for fee
await icxSetup.createBTCDFIPool()
await icxSetup.addLiquidityToBTCDFIPool(1, 100)
await icxSetup.setTakerFee(0.001)
})
afterAll(async () => {
await container.stop()
})
afterEach(async () => {
await icxSetup.closeAllOpenOffers()
})
it('should submit ExtHTLC for a DFC buy offer', async () => {
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders()
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId].status).toStrictEqual(ICXOrderStatus.OPEN)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make Offer to partial amount 10 DFI - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(0.10), // 0.10 BTC = 10 DFI
ownerAddress: accountBTC
}
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.01 DFI has been reduced from the accountBTCBeforeOffer[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.01))
// List the ICX offers for orderTx = createOrderTxId and check
const offersForOrder1: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders({ orderTx: createOrderTxId })
expect(Object.keys(offersForOrder1).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((offersForOrder1 as Record<string, ICXOfferInfo>)[makeOfferTxId].status).toStrictEqual(ICXOrderStatus.OPEN)
const accountDFIBeforeDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// create DFCHTLC - maker
const DFCHTLC: HTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(10), // in DFC
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
timeout: 1440
}
const DFCHTLCTxId = (await client.icxorderbook.submitDFCHTLC(DFCHTLC)).txid
await container.generate(1)
const accountDFIAfterDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// maker fee should be reduced from accountDFIBeforeDFCHTLC
expect(accountDFIAfterDFCHTLC[idDFI]).toStrictEqual(accountDFIBeforeDFCHTLC[idDFI].minus(0.01))
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.call('icx_listhtlcs', [listHTLCOptions], 'bignumber')
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).type).toStrictEqual(ICXHTLCType.DFC)
expect((HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).status).toStrictEqual(ICXOrderStatus.OPEN)
expect((HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).offerTx).toStrictEqual(makeOfferTxId)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC - taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC)).txid
await container.generate(1)
// List htlc for offer Tx makeOfferTxId
const listHTLCOptionsAfterExtHTLC = {
offerTx: makeOfferTxId
}
const HTLCsAfterExtHTLC: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.call('icx_listhtlcs', [listHTLCOptionsAfterExtHTLC], 'bignumber')
expect(Object.keys(HTLCsAfterExtHTLC).length).toStrictEqual(3) // extra entry for the warning text returned by the RPC atm.
expect(HTLCsAfterExtHTLC[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual(
{
type: ICXHTLCType.EXTERNAL,
status: ICXOrderStatus.OPEN,
offerTx: makeOfferTxId,
amount: ExtHTLC.amount,
amountInDFCAsset: ExtHTLC.amount.dividedBy(order.orderPrice),
hash: ExtHTLC.hash,
htlcScriptAddress: ExtHTLC.htlcScriptAddress,
ownerPubkey: ExtHTLC.ownerPubkey,
timeout: new BigNumber(ExtHTLC.timeout),
height: expect.any(BigNumber)
}
)
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCAfterEXTHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should submit ExtHTLC for a BTC buy offer', async () => {
const order: ICXOrder = {
chainFrom: 'BTC',
tokenTo: idDFI,
ownerAddress: accountDFI,
amountFrom: new BigNumber(2),
orderPrice: new BigNumber(100)
}
// create order - maker
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders()
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId].status).toStrictEqual(ICXOrderStatus.OPEN)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// create Offer to partial amount 1 BTC - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(100), // 100 DFI = 1 BTC
ownerAddress: accountBTC,
receivePubkey: '0348790cb93b203a8ea5ce07279cb209d807b535b2ca8b0988a6f7a6578e41f7a5'
}
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.1 DFI has been reduced from the accountBTCBeforeOffer[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.1))
// List the ICX offers for orderTx = createOrderTxId and check
const offersForOrder1: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders({ orderTx: createOrderTxId })
expect(Object.keys(offersForOrder1).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((offersForOrder1 as Record<string, ICXOfferInfo>)[makeOfferTxId].status).toStrictEqual(ICXOrderStatus.OPEN)
const accountDFIBeforeExtHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// submit EXT HTLC - maker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(1),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 100
}
const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC)).txid
await container.generate(1)
// List htlc
const listHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.call('icx_listhtlcs', [listHTLCOptions], 'bignumber')
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect(HTLCs[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual(
{
type: ICXHTLCType.EXTERNAL,
status: ICXOrderStatus.OPEN,
offerTx: makeOfferTxId,
amount: ExtHTLC.amount,
amountInDFCAsset: ExtHTLC.amount.multipliedBy(order.orderPrice),
hash: ExtHTLC.hash,
htlcScriptAddress: ExtHTLC.htlcScriptAddress,
ownerPubkey: ExtHTLC.ownerPubkey,
timeout: new BigNumber(ExtHTLC.timeout),
height: expect.any(BigNumber)
}
)
const accountDFIAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// maker deposit should be reduced from accountDFI
expect(accountDFIAfterEXTHTLC[idDFI]).toStrictEqual(accountDFIBeforeExtHTLC[idDFI].minus(0.1))
})
it('should submit ExtHTLC for a DFC buy offer with input utxos', async () => {
const { order, createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC - taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
// input utxos
const inputUTXOs = await container.fundAddress(accountBTC, 10)
const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC, [inputUTXOs])).txid
await container.generate(1)
const rawtx = await container.call('getrawtransaction', [ExtHTLCTxId, true])
expect(rawtx.vin[0].txid).toStrictEqual(inputUTXOs.txid)
expect(rawtx.vin[0].vout).toStrictEqual(inputUTXOs.vout)
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.call('icx_listhtlcs', [listHTLCOptions], 'bignumber')
expect(Object.keys(HTLCs).length).toStrictEqual(3) // extra entry for the warning text returned by the RPC atm.
expect(HTLCs[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual(
{
type: ICXHTLCType.EXTERNAL,
status: ICXOrderStatus.OPEN,
offerTx: makeOfferTxId,
amount: ExtHTLC.amount,
amountInDFCAsset: ExtHTLC.amount.dividedBy(order.orderPrice),
hash: ExtHTLC.hash,
htlcScriptAddress: ExtHTLC.htlcScriptAddress,
ownerPubkey: ExtHTLC.ownerPubkey,
timeout: new BigNumber(ExtHTLC.timeout),
height: expect.any(BigNumber)
}
)
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCBeforeEXTHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should return an error when submitting ExtHTLC with incorrect ExtHTLC.offerTx', async () => {
const { createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC with offer tx "123"- taker
const ExtHTLC: ExtHTLC = {
offerTx: '123',
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'offerTx (0000000000000000000000000000000000000000000000000000000000000123) does not exist\', code: -8, method: icx_submitexthtlc')
// submit EXT HTLC with offer tx "INVALID_OFFER_TX_ID"- taker
const ExtHTLC2: ExtHTLC = {
offerTx: 'INVALID_OFFER_TX_ID',
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const promise2 = client.icxorderbook.submitExtHTLC(ExtHTLC2)
await expect(promise2).rejects.toThrow(RpcApiError)
await expect(promise2).rejects.toThrow('RpcApiError: \'offerTx (0000000000000000000000000000000000000000000000000000000000000000) does not exist\', code: -8, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCBeforeEXTHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should return an error when submitting ExtHTLC with incorrect ExtHTLC.amount than the amount in DFC HTLC', async () => {
const { createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC with amount 0.20 BTC- taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.20), // here we are passing 0.20 BTC which is greater than the amount in DFC HTLC which is 0.1 BTC
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\namount must be equal to calculated dfchtlc amount\', code: -32600, method: icx_submitexthtlc')
// submit EXT HTLC with amount 0.05 BTC- taker
const ExtHTLC2: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.05), // here we are passing 0.05 BTC which is lesser than the amount in DFC HTLC which is 0.1 BTC
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const promise2 = client.icxorderbook.submitExtHTLC(ExtHTLC2)
await expect(promise2).rejects.toThrow(RpcApiError)
await expect(promise2).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\namount must be equal to calculated dfchtlc amount\', code: -32600, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCBeforeEXTHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should return an error when submitting ExtHTLC with incorrect hash from the hash in DFC HTLC', async () => {
const { createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC with incorrect hash "INCORRECT_HASH" from DFCHTLC hash - taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: 'INCORRECT_HASH',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\nInvalid hash, external htlc hash is different than dfc htlc hash\', code: -32600, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCAfterDFCHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should return an error when submitting ExtHTLC with invalid ExtHTLC.ownerPubkey', async () => {
const { createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC with incorrect ownerPubkey "INVALID_OWNER_PUB_KEY" - taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: 'INVALID_OWNER_PUB_KEY',
timeout: 24
}
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Invalid public key: INVALID_OWNER_PUB_KEY\', code: -5, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCBeforeEXTHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should test submitting ExtHTLC with different values for ExtHTLC.timeout', async () => {
const { createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC with timeout < 24 - taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 14
}
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\ntimeout must be greater than 23\', code: -32600, method: icx_submitexthtlc')
// submit EXT HTLC with a ExtHTLC.timeout such that order->creationHeight + order->expiry < current height + (ExtHTLC.timeout * 16) - taker
ExtHTLC.timeout = 400
const promise2 = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise2).rejects.toThrow(RpcApiError)
await expect(promise2).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\norder will expire before ext htlc expires!\', code: -32600, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCAfterDFCHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should return an error when submitting an ExtHTLC, prior to the DFC HTLC for buy DFI offer', async () => {
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders()
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId].status).toStrictEqual(ICXOrderStatus.OPEN)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make Offer to partial amount 10 DFI - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(0.10), // 0.10 BTC = 10 DFI
ownerAddress: accountBTC
}
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.01 DFI has been reduced from the accountBTCBeforeOffer[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.01))
// List the ICX offers for orderTx = createOrderTxId and check
const offersForOrder1: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders({ orderTx: createOrderTxId })
expect(Object.keys(offersForOrder1).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((offersForOrder1 as Record<string, ICXOfferInfo>)[makeOfferTxId].status).toStrictEqual(ICXOrderStatus.OPEN)
// No DFC HTLC submitted yet.
// submit EXT HTLC - taker
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC)
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\noffer (' + makeOfferTxId + ') needs to have dfc htlc submitted first, but no dfc htlc found!\', code: -32600, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(1) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCAfterDFCHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
it('should not submit ExtHTLC for a DFC buy offer with arbitary input utxos', async () => {
const { createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01))
const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC)
await icxSetup.createDFCHTLCForDFIBuyOffer(makeOfferTxId, new BigNumber(10), '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', 1440)
const accountBTCBeforeEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// submit EXT HTLC with incorrect ownerPubkey "INVALID_OWNER_PUB_KEY" - taker
const ExtHTLC: ExtHTLC = {
offerTx: makeOfferTxId,
amount: new BigNumber(0.10),
hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220',
htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N',
ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252',
timeout: 24
}
// input utxos
const inputUTXOs = await container.fundAddress(await container.getNewAddress(), 10)
const promise = client.icxorderbook.submitExtHTLC(ExtHTLC, [inputUTXOs])
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Test ICXSubmitEXTHTLCTx execution failed:\ntx must have at least one input from offer owner\', code: -32600, method: icx_submitexthtlc')
// List htlc
const listHTLCOptions: ICXListHTLCOptions = {
offerTx: makeOfferTxId
}
const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await container.call('icx_listhtlcs', [listHTLCOptions])
expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
const accountBTCAfterEXTHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// should have the same balance as accountBTCBeforeEXTHTLC
expect(accountBTCAfterEXTHTLC).toStrictEqual(accountBTCBeforeEXTHTLC)
})
}) | the_stack |
import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRoute, Router, RouterState } from '@angular/router';
import { of, Subject } from 'rxjs';
import { FormBuilder } from '@angular/forms';
import { ArtemisTestModule } from '../../test.module';
import { UserManagementUpdateComponent } from 'app/admin/user-management/user-management-update.component';
import { User } from 'app/core/user/user.model';
import { JhiLanguageHelper } from 'app/core/language/language.helper';
import { UserService } from 'app/core/user/user.service';
import { Authority } from 'app/shared/constants/authority.constants';
import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { MockNgbModalService } from '../../helpers/mocks/service/mock-ngb-modal.service';
import { Organization } from 'app/entities/organization.model';
import { OrganizationSelectorComponent } from 'app/shared/organization-selector/organization-selector.component';
import { NgForm, NgModel } from '@angular/forms';
import { MockDirective, MockModule } from 'ng-mocks';
import { MockTranslateService, TranslatePipeMock } from '../../helpers/mocks/service/mock-translate.service';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatChipInputEvent, MatChipsModule } from '@angular/material/chips';
import { TranslateService } from '@ngx-translate/core';
import { MockRouter } from '../../helpers/mocks/mock-router';
import { Title } from '@angular/platform-browser';
import * as Sentry from '@sentry/browser';
import { LANGUAGES } from 'app/core/language/language.constants';
describe('User Management Update Component', () => {
let comp: UserManagementUpdateComponent;
let fixture: ComponentFixture<UserManagementUpdateComponent>;
let service: UserService;
let titleService: Title;
const parentRoute = {
data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', [Authority.USER], ['admin'], undefined, undefined, undefined) }),
} as any as ActivatedRoute;
const route = { parent: parentRoute } as any as ActivatedRoute;
let mockRouterState: RouterState;
let modalService: NgbModal;
let translateService: TranslateService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule, MockModule(MatFormFieldModule), MockModule(MatChipsModule)],
declarations: [UserManagementUpdateComponent, TranslatePipeMock, MockDirective(NgForm), MockDirective(NgModel)],
providers: [
FormBuilder,
{
provide: ActivatedRoute,
useValue: route,
},
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: NgbModal, useClass: MockNgbModalService },
{ provide: TranslateService, useClass: MockTranslateService },
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(UserManagementUpdateComponent);
comp = fixture.componentInstance;
service = TestBed.inject(UserService);
modalService = TestBed.inject(NgbModal);
titleService = TestBed.inject(Title);
translateService = TestBed.inject(TranslateService);
mockRouterState = {
snapshot: {
root: { firstChild: {}, data: {} },
},
} as RouterState;
});
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('OnInit', () => {
it('Should load authorities and language on init', inject(
[JhiLanguageHelper],
fakeAsync((languageHelper: JhiLanguageHelper) => {
// GIVEN
jest.spyOn(service, 'authorities').mockReturnValue(of(['USER']));
const getAllSpy = jest.spyOn(languageHelper, 'getAll').mockReturnValue([]);
// WHEN
comp.ngOnInit();
// THEN
expect(service.authorities).toHaveBeenCalled();
expect(comp.authorities).toEqual(['USER']);
expect(getAllSpy).toHaveBeenCalled();
}),
));
it('should load available languages', inject(
[JhiLanguageHelper],
fakeAsync((languageHelper: JhiLanguageHelper) => {
// GIVEN
const getAllSpy = jest.spyOn(languageHelper, 'getAll');
// WHEN
comp.ngOnInit();
// THEN
expect(getAllSpy).toHaveBeenCalledOnce();
expect(comp.languages).toEqual(LANGUAGES);
}),
));
it('should return current language', inject(
[JhiLanguageHelper],
fakeAsync((languageHelper: JhiLanguageHelper) => {
// GIVEN
const routerMock: MockRouter = TestBed.inject<MockRouter>(Router as any);
routerMock.setRouterState(mockRouterState);
// WHEN
translateService.use('en');
// THEN
languageHelper.language.subscribe((res) => expect(res).toEqual(translateService.currentLang));
}),
));
it('should set page title based on router snapshot', inject(
[JhiLanguageHelper],
fakeAsync((languageHelper: JhiLanguageHelper) => {
// GIVEN
const routerMock: MockRouter = TestBed.inject<MockRouter>(Router as any);
mockRouterState.snapshot.root.data = { pageTitle: 'parent.page.test' };
mockRouterState.snapshot.root.firstChild!.data = { pageTitle: 'child.page.test' };
routerMock.setRouterState(mockRouterState);
const updateTitleSpy = jest.spyOn(languageHelper, 'updateTitle');
const getPageTitleSpy = jest.spyOn(languageHelper, 'getPageTitle');
const setTitleOnTitleServiceSpy = jest.spyOn(titleService, 'setTitle');
// WHEN
translateService.use('en');
// THEN
expect(updateTitleSpy).toHaveBeenCalledOnce();
expect(getPageTitleSpy).toHaveBeenCalledTimes(2);
expect(getPageTitleSpy).toHaveBeenNthCalledWith(1, mockRouterState.snapshot.root);
expect(getPageTitleSpy).toHaveBeenNthCalledWith(2, mockRouterState.snapshot.root.firstChild);
expect(getPageTitleSpy).toHaveLastReturnedWith('child.page.test');
expect(setTitleOnTitleServiceSpy).toHaveBeenCalledOnce();
expect(setTitleOnTitleServiceSpy).toHaveBeenCalledWith('child.page.test');
}),
));
it('should set page title to default', inject(
[JhiLanguageHelper],
fakeAsync((languageHelper: JhiLanguageHelper) => {
// GIVEN
const routerMock: MockRouter = TestBed.inject<MockRouter>(Router as any);
routerMock.setRouterState(mockRouterState);
const updateTitleSpy = jest.spyOn(languageHelper, 'updateTitle');
const setTitleOnTitleServiceSpy = jest.spyOn(titleService, 'setTitle');
// WHEN
translateService.use('en');
// THEN
expect(updateTitleSpy).toHaveBeenCalledOnce();
expect(setTitleOnTitleServiceSpy).toHaveBeenCalledOnce();
expect(setTitleOnTitleServiceSpy).toHaveBeenCalledWith('global.title');
}),
));
it('should capture exception if title translation not found', inject(
[JhiLanguageHelper],
fakeAsync((languageHelper: JhiLanguageHelper) => {
// GIVEN
const routerMock: MockRouter = TestBed.inject<MockRouter>(Router as any);
routerMock.setRouterState(mockRouterState);
const updateTitleSpy = jest.spyOn(languageHelper, 'updateTitle');
const getTranslationSpy = jest.spyOn(translateService, 'get').mockReturnValue(of(undefined));
const setTitleOnTitleServiceSpy = jest.spyOn(titleService, 'setTitle');
const captureExceptionSpy = jest.spyOn(Sentry, 'captureException');
// WHEN
translateService.use('en');
// THEN
expect(updateTitleSpy).toHaveBeenCalledOnce();
expect(getTranslationSpy).toHaveBeenCalledOnce();
expect(getTranslationSpy).toHaveBeenCalledWith('global.title');
expect(captureExceptionSpy).toHaveBeenCalledOnce();
expect(captureExceptionSpy).toHaveBeenCalledWith(new Error("Translation key 'global.title' for page title not found"));
expect(setTitleOnTitleServiceSpy).not.toHaveBeenCalled();
}),
));
});
describe('save', () => {
it('Should call update service on save for existing user', inject(
[],
fakeAsync(() => {
// GIVEN
const entity = new User(123);
jest.spyOn(service, 'update').mockReturnValue(
of(
new HttpResponse({
body: entity,
}),
),
);
comp.user = entity;
comp.user.login = 'test_user';
// WHEN
comp.save();
tick(); // simulate async
// THEN
expect(service.update).toHaveBeenCalledWith(entity);
expect(comp.isSaving).toEqual(false);
}),
));
it('Should call create service on save for new user', inject(
[],
fakeAsync(() => {
// GIVEN
const entity = new User();
jest.spyOn(service, 'create').mockReturnValue(of(new HttpResponse({ body: entity })));
comp.user = entity;
// WHEN
comp.save();
tick(); // simulate async
// THEN
expect(service.create).toHaveBeenCalledWith(entity);
expect(comp.isSaving).toEqual(false);
}),
));
});
it('should set saving to false on save error', () => {
comp.isSaving = true;
// @ts-ignore
comp.onSaveError();
expect(comp.isSaving).toBeFalse();
});
it('should set password to undefined if random password should be used', () => {
comp.user = { password: 'abc' } as User;
comp.shouldRandomizePassword(true);
expect(comp.user.password).toBe(undefined);
comp.shouldRandomizePassword(false);
expect(comp.user.password).toBe('');
});
it('should open organizations modal', () => {
const orgs = [{}] as Organization[];
comp.user = { organizations: orgs } as User;
const sub = new Subject<Organization>();
const modalRef = {
componentInstance: { organizations: undefined },
closed: sub.asObservable(),
} as NgbModalRef;
const openSpy = jest.spyOn(modalService, 'open').mockReturnValue(modalRef);
comp.openOrganizationsModal();
expect(openSpy).toHaveBeenCalledOnce();
expect(openSpy).toHaveBeenCalledWith(OrganizationSelectorComponent, { size: 'xl', backdrop: 'static' });
expect(modalRef.componentInstance.organizations).toBe(orgs);
const newOrg = {} as Organization;
sub.next(newOrg);
expect(orgs).toContain(newOrg);
comp.user.organizations = undefined;
sub.next(newOrg);
expect(comp.user.organizations).toEqual([newOrg]);
});
it('should remove organization from user', () => {
const org0 = { id: 1 };
const org1 = { id: 2 };
comp.user = { organizations: [org0, org1] } as User;
comp.removeOrganizationFromUser(org1);
expect(comp.user.organizations).toEqual([org0]);
});
it('should add users to groups', () => {
const groupCtrlSetValueSpy = jest.spyOn(comp.groupCtrl, 'setValue');
const newGroup = 'nicegroup';
comp.user = { groups: [] } as any as User;
const event = { value: newGroup, chipInput: { clear: jest.fn() } } as any as MatChipInputEvent;
comp.onGroupAdd(comp.user, event);
expect(comp.user.groups).toEqual([newGroup]);
expect(event.chipInput!.clear).toHaveBeenCalledOnce();
expect(groupCtrlSetValueSpy).toHaveBeenCalledOnce();
expect(groupCtrlSetValueSpy).toHaveBeenCalledWith(null);
});
}); | the_stack |
import { Connection } from "jsforce";
import * as _ from "lodash";
import * as xml2js from "xml2js";
import * as fs from "fs-extra";
import * as path from "path";
import FileUtils from "../../utils/fileutils";
import { FileProperties } from "jsforce";
import { SFPowerkit, LoggerLevel } from "../../sfpowerkit";
import { SfdxError } from "@salesforce/core";
if (Symbol["asyncIterator"] === undefined) {
// tslint:disable-next-line:no-any
(Symbol as any)["asyncIterator"] = Symbol.for("asyncIterator");
}
const STANDARD_VALUE_SETS = [
"AccountContactMultiRoles",
"AccountContactRole",
"AccountOwnership",
"AccountRating",
"AccountType",
"AddressCountryCode",
"AddressStateCode",
"AssetStatus",
"CampaignMemberStatus",
"CampaignStatus",
"CampaignType",
"CaseContactRole",
"CaseOrigin",
"CasePriority",
"CaseReason",
"CaseStatus",
"CaseType",
"ContactRole",
"ContractContactRole",
"ContractStatus",
"EntitlementType",
"EventSubject",
"EventType",
"FiscalYearPeriodName",
"FiscalYearPeriodPrefix",
"FiscalYearQuarterName",
"FiscalYearQuarterPrefix",
"IdeaCategory",
"IdeaMultiCategory",
"IdeaStatus",
"IdeaThemeStatus",
"Industry",
"InvoiceStatus",
"LeadSource",
"LeadStatus",
"OpportunityCompetitor",
"OpportunityStage",
"OpportunityType",
"OrderStatus",
"OrderType",
"PartnerRole",
"Product2Family",
"QuestionOrigin",
"QuickTextCategory",
"QuickTextChannel",
"QuoteStatus",
"SalesTeamRole",
"Salutation",
"ServiceContractApprovalStatus",
"SocialPostClassification",
"SocialPostEngagementLevel",
"SocialPostReviewedStatus",
"SolutionStatus",
"TaskPriority",
"TaskStatus",
"TaskSubject",
"TaskType",
"WorkOrderLineItemStatus",
"WorkOrderPriority",
"WorkOrderStatus",
];
/**
* This code was adapted from github:sfdx-jayree-plugin project which was
* based on the original github:sfdx-hydrate project
*/
export class Packagexml {
public configs: BuildConfig;
private conn: Connection;
private packageTypes = {};
private ipRegex: RegExp;
public result: {
type: string;
createdById?: string;
createdByName?: string;
createdDate?: string;
fileName?: string;
fullName: string;
id?: string;
lastModifiedById?: string;
lastModifiedByName?: string;
lastModifiedDate?: string;
manageableState?: string;
namespacePrefix?: string;
}[];
constructor(conn: Connection, configs: BuildConfig) {
this.conn = conn;
this.configs = configs;
this.result = [];
}
public async build() {
if (
this.configs.excludeFilters.length > 0 &&
this.configs.includeFilters.length > 0
) {
let conflict = this.configs.excludeFilters.filter((element) =>
this.configs.includeFilters.includes(element)
);
if (conflict.length > 0) {
throw new SfdxError(
`Unable to process the request, found ${conflict} in both include and exlude list`
);
}
}
try {
await this.buildInstalledPackageRegex();
await this.describeMetadata();
this.setStandardValueset();
let packageXml = this.generateXml();
let dir = path.parse(this.configs.outputFile).dir;
if (!fs.existsSync(dir)) {
FileUtils.mkDirByPathSync(dir);
}
fs.writeFileSync(this.configs.outputFile, packageXml);
SFPowerkit.log(
`Mainfest ${this.configs.outputFile} is created successfully `,
LoggerLevel.INFO
);
return packageXml;
} catch (err) {
SFPowerkit.log(err, LoggerLevel.ERROR);
}
}
private setStandardValueset() {
if (
(this.configs.excludeFilters.length === 0 ||
!this.configs.excludeFilters.includes("StandardValueSet")) &&
(this.configs.includeFilters.length === 0 ||
this.configs.includeFilters.includes("StandardValueSet"))
) {
if (!this.packageTypes["StandardValueSet"]) {
this.packageTypes["StandardValueSet"] = [];
}
STANDARD_VALUE_SETS.forEach((member) => {
this.packageTypes["StandardValueSet"].push(member);
this.result.push({
type: "StandardValueSet",
fullName: member,
});
});
}
}
private async buildInstalledPackageRegex() {
// fetch and execute installed package promise to build regex
let ipRegexStr: string = "^(";
let instPack = await this.conn.metadata.list(
{
type: "InstalledPackage",
},
this.configs.apiVersion
);
try {
instPack.forEach((pkg) => {
ipRegexStr += pkg.namespacePrefix + "|";
});
ipRegexStr += ")+__";
this.ipRegex = RegExp(ipRegexStr);
} catch (err) {
this.ipRegex = RegExp("");
}
}
private async describeMetadata() {
const describe = await this.conn.metadata.describe(this.configs.apiVersion);
for (const object of describe.metadataObjects) {
if (
this.configs.excludeFilters.length > 0 &&
this.configs.excludeFilters.includes(object.xmlName)
) {
continue;
} else if (
this.configs.includeFilters.length > 0 &&
!this.isAvailableinIncludeList(object.xmlName)
) {
continue;
}
if (object.inFolder) {
await this.handleFolderObject(object);
} else {
await this.handleNonFolderObject(object);
}
}
}
private async handleFolderObject(object) {
const folderType = object.xmlName.replace("Template", "");
let folderdescribeRes = await this.conn.metadata.list(
{
type: `${folderType}Folder`,
},
this.configs.apiVersion
);
try {
//Handle Folder
let folderDescribeItems = this.convertToArray(folderdescribeRes);
folderDescribeItems.forEach(async (FolderMetadataEntries) => {
this.addMember(FolderMetadataEntries.type, FolderMetadataEntries);
//Handle Folder Item
let folderItemsRes = await this.conn.metadata.list(
{
type: object.xmlName,
folder: FolderMetadataEntries.fullName,
},
this.configs.apiVersion
);
try {
//Handle Folder
let folderItems = this.convertToArray(folderItemsRes);
folderItems.forEach((FolderItemMetadataEntries) => {
this.addMember(
FolderItemMetadataEntries.type,
FolderItemMetadataEntries
);
});
} catch (err) {
SFPowerkit.log(
`Error in processing Type ${object.xmlName} ${err}`,
LoggerLevel.ERROR
);
}
});
} catch (err) {
SFPowerkit.log(
`Error in processing Type ${folderType} ${err}`,
LoggerLevel.ERROR
);
}
}
private async handleNonFolderObject(object) {
let unfolderItemsRes = await this.conn.metadata.list(
{
type: object.xmlName,
},
this.configs.apiVersion
);
try {
//Handle Parent
let unfolderItems = this.convertToArray(unfolderItemsRes);
let filterunfolderItems = this.filterItems(unfolderItems);
filterunfolderItems.forEach((metadataEntries) => {
this.addMember(metadataEntries.type, metadataEntries);
});
//Handle Child
if (
object.childXmlNames &&
object.childXmlNames.length > 0 &&
this.configs.includeChilds
) {
for (let child of object.childXmlNames) {
if (child === "ManagedTopic") {
continue;
}
let unfolderChildItemsRes = await this.conn.metadata.list(
{
type: child,
},
this.configs.apiVersion
);
try {
let unfolderChilItems = this.convertToArray(unfolderChildItemsRes);
let filterunfolderChildItems = this.filterChildItems(
unfolderChilItems,
object.xmlName
);
filterunfolderChildItems.forEach((metadataEntries) => {
this.addMember(metadataEntries.type, metadataEntries);
});
} catch (err) {
SFPowerkit.log(
`Error in processing Type ${child} ${err}`,
LoggerLevel.ERROR
);
}
}
}
} catch (err) {
SFPowerkit.log(
`Error in processing Type ${object.xmlName} ${err}`,
LoggerLevel.ERROR
);
}
}
private isAvailableinIncludeList(type: string, member: string = "") {
let found = false;
for (let includeFilter of this.configs.includeFilters) {
if (!includeFilter.includes(":") && includeFilter === type) {
found = true;
break;
} else if (
includeFilter.includes(":") &&
includeFilter.split(":")[0] === type &&
(member === "" || includeFilter.split(":")[1] === member)
) {
found = true;
break;
}
}
return found;
}
private convertToArray(item) {
if (!item) {
return [];
} else if (Array.isArray(item)) {
return item;
} else {
return [item];
}
}
private filterItems(itemsArray: FileProperties[]) {
return itemsArray.filter(
(element) =>
(this.configs.excludeFilters.length === 0 ||
!this.configs.excludeFilters.includes(
element.type + ":" + element.fullName
)) &&
(this.configs.includeFilters.length === 0 ||
this.isAvailableinIncludeList(element.type, element.fullName))
);
}
private filterChildItems(itemsArray: FileProperties[], parentType) {
return itemsArray.filter(
(element) =>
((this.configs.excludeFilters.length === 0 ||
!this.configs.excludeFilters.includes(
element.type + ":" + element.fullName
)) &&
(this.configs.includeFilters.length === 0 ||
this.isAvailableinIncludeList(element.type, element.fullName))) ||
this.isAvailableinIncludeList(
parentType,
this.getParentName(element.fullName)
)
);
}
private getParentName(fullName: string) {
return fullName.includes(".") ? fullName.split(".")[0] : "";
}
private generateXml() {
const packageJson = {
$: { xmlns: "http://soap.sforce.com/2006/04/metadata" },
types: [],
version: this.configs.apiVersion,
};
let mdtypes = Object.keys(this.packageTypes);
mdtypes.sort();
mdtypes.forEach((mdtype) => {
packageJson.types.push({
name: mdtype,
members: this.packageTypes[mdtype].sort(),
});
});
const builder = new xml2js.Builder({
xmldec: { version: "1.0", encoding: "utf-8" },
});
let packageObj = {
Package: packageJson,
};
let packageXml = builder.buildObject(packageObj);
return packageXml;
}
private addMember(type: string, member: FileProperties) {
/**
* Managed package - fullName starts with 'namespacePrefix__' || namespacePrefix is not null || manageableState = installed
* Unmanaged package - manageableState = unmanaged
* Regular custom objects - manageableState = unmanaged or undefined
*/
if (type && !this.isManagePackageIgnored(member)) {
try {
//Handle Object Translation
if (member.fileName.includes("ValueSetTranslation")) {
const x =
member.fileName.split(".")[1].substring(0, 1).toUpperCase() +
member.fileName.split(".")[1].substring(1);
if (!this.packageTypes[x]) {
this.packageTypes[x] = [];
}
this.packageTypes[x].push(member.fullName);
this.result.push(member);
} else {
if (!this.packageTypes[type]) {
this.packageTypes[type] = [];
}
//Handle Layout
if (
member.type === "Layout" &&
member.namespacePrefix &&
member.manageableState === "installed"
) {
const { fullName, namespacePrefix } = member;
let objectName = fullName.substr(0, fullName.indexOf("-"));
let layoutName = fullName.substr(fullName.indexOf("-") + 1);
this.packageTypes[type].push(
objectName + "-" + namespacePrefix + "__" + layoutName
);
this.result.push(member);
} else {
this.packageTypes[type].push(member.fullName);
this.result.push(member);
}
}
} catch (ex) {
SFPowerkit.log(
`Error in adding Type ${type} ${ex.message}`,
LoggerLevel.ERROR
);
}
}
}
private isManagePackageIgnored(member: any) {
return (
this.configs.excludeManaged &&
(this.ipRegex.test(member.fullName) ||
member.namespacePrefix ||
member.manageableState === "installed")
);
}
}
export class BuildConfig {
public includeFilters: string[];
public excludeFilters: string[];
public excludeManaged: boolean;
public includeChilds: boolean;
public apiVersion: string;
public targetDir: string;
public outputFile: string;
constructor(flags: object, apiVersion: string) {
// flags always take precendence over configs from file
this.excludeManaged = flags["excludemanaged"];
this.includeChilds = flags["includechilds"];
this.apiVersion = flags["apiversion"] || apiVersion;
this.excludeFilters = flags["excludefilter"]
? flags["excludefilter"].split(",").map((elem) => {
return elem.trim();
})
: [];
if (flags["quickfilter"]) {
flags["quickfilter"].split(",").map((elem) => {
if (!this.excludeFilters.includes(elem.trim())) {
this.excludeFilters.push(elem.trim());
}
});
}
this.includeFilters = flags["includefilter"]
? flags["includefilter"].split(",").map((elem) => {
return elem.trim();
})
: [];
this.outputFile = flags["outputfile"] || "package.xml";
}
} | the_stack |
import * as uuid from 'uuid';
import { ChannelDeep, PREDEFINED_COLORS, ChannelTypes, ChannelValue, SingleTrack, Channel } from './gosling.schema';
import { validateTrack, getGenomicChannelFromTrack, getGenomicChannelKeyFromTrack } from './utils/validate';
import {
ScaleLinear,
scaleLinear,
ScaleOrdinal,
scaleOrdinal,
ScaleBand,
scaleBand,
ScaleSequential,
scaleSequential
} from 'd3-scale';
import { interpolateViridis } from 'd3-scale-chromatic';
import { min as d3min, max as d3max, sum as d3sum, group } from 'd3-array';
import { HIGLASS_AXIS_SIZE } from './higlass-model';
import { SUPPORTED_CHANNELS } from './mark';
import { PIXIVisualProperty } from './visual-property.schema';
import { rectProperty } from './mark/rect';
import { pointProperty } from './mark/point';
import { barProperty } from './mark/bar';
import { getNumericDomain } from './utils/scales';
import { logicalComparison } from './utils/semantic-zoom';
import { aggregateData } from './utils/data-transform';
import {
IsChannelDeep,
IsChannelValue,
getValueUsingChannel,
IsStackedChannel,
IsDomainArray,
PREDEFINED_COLOR_STR_MAP,
IsRangeArray
} from './gosling.schema.guards';
import { CHANNEL_DEFAULTS } from './channel';
import { CompleteThemeDeep } from './utils/theme';
export type ScaleType =
| ScaleLinear<any, any>
| ScaleOrdinal<any, any>
| ScaleBand<any>
| ScaleSequential<any>
| (() => string | number); // constant value
export class GoslingTrackModel {
private id: string;
private theme: Required<CompleteThemeDeep>;
/* spec */
private specOriginal: SingleTrack; // original spec of users
private specComplete: SingleTrack; // processed spec, being used in visualizations
/* data */
private dataOriginal: { [k: string]: number | string }[];
private dataAggregated: { [k: string]: number | string }[];
/* channel scales */
private channelScales: {
[channel: string]: ScaleType;
};
constructor(spec: SingleTrack, data: { [k: string]: number | string }[], theme: Required<CompleteThemeDeep>) {
this.id = uuid.v1();
this.theme = theme;
this.dataOriginal = JSON.parse(JSON.stringify(data));
this.dataAggregated = JSON.parse(JSON.stringify(data));
this.specOriginal = JSON.parse(JSON.stringify(spec));
this.specComplete = JSON.parse(JSON.stringify(spec));
this.channelScales = {};
const validity = this.validateSpec();
if (!validity.valid) {
console.warn('Gosling specification is not valid!', validity.errorMessages);
return;
}
// fill missing options
this.generateCompleteSpec(this.specComplete);
this.flipRanges(this.specComplete);
// generate scales based on domains and ranges
this.generateScales();
// EXPERIMENTAL: aggregate data when `aggregate` option is used
this.dataAggregated = aggregateData(this.spec(), this.dataAggregated);
// Add default specs.
// ...
// DEBUG
// console.log('corrected track', this.spec());
}
public getId(): string {
return this.id;
}
public getRenderingId(): string {
return this.spec()._renderingId ?? this.getId();
}
public originalSpec(): SingleTrack {
return this.specOriginal;
}
public spec(): SingleTrack {
return this.specComplete;
}
public data(): { [k: string]: number | string }[] {
return this.dataAggregated;
}
/**
* Fill the missing options with default values or with the values calculated based on the data.
*/
private generateCompleteSpec(spec: SingleTrack) {
if (!spec.width || !spec.height) {
// This shouldn't be reached.
console.warn('Size of track is not determined yet.');
return;
}
// If this is vertical track, switch them.
if (spec.orientation === 'vertical') {
const width = spec.width;
spec.width = spec.height;
spec.height = width;
}
// If axis presents, reserve a space to show axis
const xOrY = this.getGenomicChannelKey();
let isAxisShown = false;
if (xOrY === 'x') {
isAxisShown = IsChannelDeep(spec.x) && spec.x.axis !== undefined && spec.x.axis !== 'none';
}
if (xOrY === 'y') {
isAxisShown = IsChannelDeep(spec.y) && spec.y.axis !== undefined && spec.y.axis !== 'none';
}
if (spec.layout !== 'circular') {
if (IsChannelDeep(spec.x) && spec.x.axis !== undefined && spec.x.axis !== 'none') {
// for linear layouts, prepare a horizontal or vertical space for the axis
// we already switched the width and height in vertical tracks, so use `height`
spec.height -= HIGLASS_AXIS_SIZE;
}
// TODO: consider 2D
} else {
// for circular layouts, prepare a space in radius for the axis
if (xOrY === 'x' && isAxisShown && IsChannelDeep(spec.x) && spec.x.axis === 'top') {
spec['outerRadius'] = ((spec['outerRadius'] as number) - HIGLASS_AXIS_SIZE) as number;
} else if (xOrY === 'x' && isAxisShown && IsChannelDeep(spec.x) && spec.x.axis === 'bottom') {
spec['innerRadius'] = ((spec['innerRadius'] as number) + HIGLASS_AXIS_SIZE) as number;
}
}
// zero baseline
SUPPORTED_CHANNELS.forEach(channelKey => {
const channel = spec[channelKey];
if (IsChannelDeep(channel) && !('zeroBaseline' in channel) && channel.type === 'quantitative') {
(channel as any).zeroBaseline = true;
}
});
this.addScaleMaterials(spec);
}
/**
* TODO: This is experimental. For bar charts, for example, additional care should be taken to correctly flip the visual marks.
* Flip the y scales when `flip` options is used.
*/
private flipRanges(spec: SingleTrack) {
if (IsChannelDeep(spec.y) && spec.y.flip && Array.isArray(spec.y.range)) {
spec.y.range = spec.y.range.reverse();
}
}
/**
* Find an axis channel that is encoded with genomic coordinate and return the key (e.g., 'x').
* `undefined` if not found.
*/
public getGenomicChannelKey(): 'x' | 'xe' | 'y' | 'ye' | 'x1' | 'x1e' | 'y1' | 'y1e' | undefined {
return getGenomicChannelKeyFromTrack(this.spec());
}
/**
* Find a genomic field from the track specification.
* `undefined` if not found.
*/
public getGenomicChannel(): ChannelDeep | undefined {
return getGenomicChannelFromTrack(this.spec());
}
/**
* Replace a domain with a new one in the complete spec(s) if the original spec does not define the domain.
* A domain is replaced only when the channel is bound with data (i.e., `ChannelDeep`).
*/
public setChannelDomain(channelKey: keyof typeof ChannelTypes, domain: string[] | number[], force?: boolean) {
const channelRaw = this.originalSpec()[channelKey];
if (!force && IsChannelDeep(channelRaw) && channelRaw.domain !== undefined) {
// if domain is provided in the original spec, we do not replace the domain in the complete spec(s)
return;
}
const channel = this.specComplete[channelKey];
if (IsChannelDeep(channel)) {
channel.domain = domain;
}
}
/**
* Replace a domain with a new one in the complete spec(s).
* A domain is replaced only when the channel is bound with data (i.e., `ChannelDeep`).
*/
public setChannelRange(channelKey: keyof typeof ChannelTypes, range: string[] | number[]) {
const channel = this.specComplete[channelKey];
if (IsChannelDeep(channel)) {
channel.range = range;
}
}
/**
* Update default constant values by looking up other channels' scales.
*/
public updateChannelValue() {
if (this.originalSpec().y === undefined) {
const y = this.spec().y;
const rowCategories = this.getChannelDomainArray('row');
if (y && IsChannelValue(y) && rowCategories) {
y.value = (this.spec().height as number) / rowCategories.length / 2.0;
}
}
}
/**
* Get the encoded value using the scales already constructed.
*/
public encodedValue(channelKey: keyof typeof ChannelTypes, value?: number | string) {
if (channelKey === 'text' && value !== undefined) {
return `${+value ? ~~value : value}`;
// TODO: Better formatting?
// return `${+value ? (+value - ~~value) > 0 ? (+value).toExponential(1) : ~~value : value}`;
}
const channel = this.spec()[channelKey];
const channelFieldType = IsChannelDeep(channel)
? channel.type
: IsChannelValue(channel)
? 'constant'
: undefined;
if (!channelFieldType) {
// Shouldn't be reached. Channel should be either encoded with data or a constant value.
return undefined;
}
if (channelFieldType === 'constant') {
// Just return the constant value.
return (this.channelScales[channelKey] as () => number | string)();
}
if (value === undefined) {
// Value is undefined, so returning undefined.
return undefined;
}
if (typeof this.channelScales[channelKey] !== 'function') {
// Scale is undefined, so returning undefined.
return undefined;
}
// The type of a channel scale is determined by a { channel type, field type } pair
switch (channelKey) {
case 'x':
case 'y':
case 'x1':
case 'y1':
case 'xe':
case 'ye':
case 'x1e':
if (channelFieldType === 'quantitative' || channelFieldType === 'genomic') {
return (this.channelScales[channelKey] as ScaleLinear<any, any>)(value as number);
}
if (channelFieldType === 'nominal') {
return (this.channelScales[channelKey] as ScaleBand<any>)(value as string);
}
break;
case 'color':
case 'stroke':
if (channelFieldType === 'quantitative') {
return (this.channelScales[channelKey] as ScaleSequential<any>)(value as number);
}
if (channelFieldType === 'nominal') {
return (this.channelScales[channelKey] as ScaleOrdinal<any, any>)(value as string);
}
/* genomic is not supported */
break;
case 'size':
if (channelFieldType === 'quantitative') {
return (this.channelScales[channelKey] as ScaleLinear<any, any>)(value as number);
}
if (channelFieldType === 'nominal') {
return (this.channelScales[channelKey] as ScaleOrdinal<any, any>)(value as string);
}
/* genomic is not supported */
break;
case 'row':
/* quantitative is not supported */
if (channelFieldType === 'nominal') {
return (this.channelScales[channelKey] as ScaleBand<any>)(value as string);
}
/* genomic is not supported */
break;
case 'strokeWidth':
case 'opacity':
if (channelFieldType === 'quantitative') {
return (this.channelScales[channelKey] as ScaleLinear<any, any>)(value as number);
}
/* nominal is not supported */
/* genomic is not supported */
break;
default:
console.warn(`${channelKey} is not supported for encoding values, so returning a undefined value`);
return undefined;
}
}
public trackVisibility(currentStage: { zoomLevel?: number }): boolean {
const spec = this.spec();
if (
!spec.visibility ||
spec.visibility.length === 0 ||
spec.visibility.filter(d => d.target === 'track').length === 0
) {
// if condition is not defined, just show them.
return true;
}
// We are using a logical operation AND, so if unless all options are `true`, we hide this track.
let visibility = true;
spec.visibility
.filter(d => d.target === 'track')
.forEach(d => {
const { operation, measure, threshold } = d;
let compareValue: number | undefined;
if (measure === 'zoomLevel') {
compareValue = currentStage[measure];
} else {
compareValue = spec[measure];
}
if (compareValue !== undefined) {
// compare only when the measure is suggested
visibility = visibility && logicalComparison(compareValue, operation, threshold as number) === 1;
}
});
return visibility;
}
/**
* Check whether the visual mark should be visible or not.
* Return 0 (invisible) only when the predefined condition is correct.
*/
public markVisibility(datum: { [k: string]: string | number }, metrics?: any): number {
const spec = this.spec();
if (
!spec.visibility ||
spec.visibility.length === 0 ||
spec.visibility.filter(d => d.target === 'mark').length === 0
) {
// if condition is not defined, just show them.
return 1;
}
let visibility = 1;
// Find the lowest visibility
spec.visibility
.filter(d => d.target === 'mark')
.forEach(d => {
const { operation, threshold, conditionPadding, transitionPadding, measure } = d;
const padding = conditionPadding ?? 0;
const mark = spec.mark;
let newVisibility = 1;
if (mark === 'text' && threshold === '|xe-x|' && measure === 'width') {
// compare between the actual width and the |xe-x|
const xe = this.encodedPIXIProperty('xe', datum);
const x = this.encodedPIXIProperty('x', datum);
if (xe !== undefined && metrics?.width) {
newVisibility = logicalComparison(
metrics.width + padding,
operation,
Math.abs(xe - x),
transitionPadding
);
}
} else if (measure === 'width' && typeof threshold === 'number' && metrics?.width) {
// compare between the actual width and the constant width that user specified
newVisibility = logicalComparison(metrics.width + padding, operation, threshold, transitionPadding);
} else if (measure === 'zoomLevel' && typeof threshold === 'number' && metrics?.zoomLevel) {
newVisibility = logicalComparison(metrics.zoomLevel, operation, threshold, transitionPadding);
}
// Update only if the upcoming one is smaller
if (visibility > newVisibility) {
visibility = newVisibility;
}
});
return visibility;
}
/**
*
*/
public visualPropertyByChannel(channelKey: keyof typeof ChannelTypes, datum?: { [k: string]: string | number }) {
const value = datum !== undefined ? getValueUsingChannel(datum, this.spec()[channelKey] as Channel) : undefined; // Is this safe enough?
return this.encodedValue(channelKey, value);
}
/**
* Retrieve an encoded visual property of a visual mark.
*/
public encodedPIXIProperty(
propertyKey: PIXIVisualProperty,
datum?: { [k: string]: string | number },
additionalInfo?: any
) {
const mark = this.spec().mark;
// common visual properties, not specific to visual marks
if (
[
'text',
'color',
'row',
'stroke',
'opacity',
'strokeWidth',
'x',
'y',
'xe',
'x1',
'x1e',
'ye',
'size'
].includes(propertyKey)
) {
return this.visualPropertyByChannel(propertyKey as any, datum);
}
switch (mark) {
case 'bar':
return barProperty(this, propertyKey, datum, additionalInfo);
case 'point':
case 'text':
return pointProperty(this, propertyKey, datum);
case 'rect':
return rectProperty(this, propertyKey, datum, additionalInfo);
default:
// Mark type that is not supported yet
return undefined;
}
}
// TODO: better organize this, perhaps, by combining several if statements
/**
* Set missing `range`, `domain`, and/or `value` of each channel by looking into data.
*/
public addScaleMaterials(spec: SingleTrack) {
const data = this.data();
const genomicChannel = this.getGenomicChannel();
if (!genomicChannel || !genomicChannel.field) {
console.warn('Genomic field is not provided in the specification');
// EXPERIMENTAL: we are removing this rule in our spec.
return;
}
if (!spec.width || !spec.height) {
console.warn('Track size is not determined yet');
return;
}
// const WARN_MSG = (c: string, t: string) =>
// `The channel key and type pair {${c}, ${t}} is not supported when generating channel scales`;
SUPPORTED_CHANNELS.forEach(channelKey => {
const channel = spec[channelKey];
if (IsStackedChannel(spec, channelKey) && IsChannelDeep(channel)) {
// we need to group data before calculating scales because marks are going to be stacked
// (spec as any /* TODO: select more accurately */).x
const pivotedData = group(data, d => d[genomicChannel.field as string]);
const xKeys = [...pivotedData.keys()];
if (!channel.domain) {
// TODO: consider data ranges in negative values
const min =
'zeroBaseline' in channel && channel.zeroBaseline
? 0
: d3min(
xKeys.map(d =>
d3sum(
(pivotedData.get(d) as any).map((_d: any) =>
channel.field ? _d[channel.field] : undefined
)
)
) as number[]
);
const max = d3max(
xKeys.map(d =>
d3sum(
(pivotedData.get(d) as any).map((_d: any) =>
channel.field ? _d[channel.field] : undefined
)
)
) as number[]
);
channel.domain = [min, max] as [number, number]; // TODO: what if data ranges in negative values
}
if (!channel.range) {
const rowChannel = spec.row;
const rowField = IsChannelDeep(rowChannel) ? rowChannel.field : undefined;
const rowCategories =
this.getChannelDomainArray('row') ??
(rowField ? Array.from(new Set(data.map(d => d[rowField as string]))) : [1]);
const rowHeight = (spec.height as number) / rowCategories.length;
// `channel` here is either `x` or `y` because they only can ba stacked
switch (channelKey) {
case 'x':
channel.range = [0, spec.width] as [number, number]; // TODO: not considering vertical direction tracks
break;
case 'y':
channel.range = [0, rowHeight];
break;
}
}
} else {
const rowChannel = spec.row;
const rowField = IsChannelDeep(rowChannel) ? rowChannel.field : undefined;
const rowCategories =
this.getChannelDomainArray('row') ??
(rowField ? Array.from(new Set(data.map(d => d[rowField as string]))) : [1]);
const rowHeight = (spec.height as number) / rowCategories.length;
if (!channel) {
// this means the channel is entirely missing in the specification, so we add a default value
let value;
switch (channelKey) {
case 'x':
value = (spec.width as number) / 2.0;
break;
case 'y':
value = rowHeight / 2.0;
break;
case 'size':
// TODO: make as an object
if (spec.mark === 'line') value = this.theme.line.size;
else if (spec.mark === 'bar') value = undefined;
else if (spec.mark === 'rect') value = undefined;
else if (spec.mark === 'triangleRight') value = undefined;
else if (spec.mark === 'triangleLeft') value = undefined;
else if (spec.mark === 'triangleBottom') value = undefined;
// Points in this case are stretched from `x` to `xe`
else if (
spec.stretch &&
spec.mark === 'point' &&
IsChannelDeep(spec.x) &&
IsChannelDeep(spec.xe)
)
value = undefined;
else if (spec.mark === 'text') value = 12;
else value = this.theme.point.size;
break;
case 'color':
value = this.theme.markCommon.color;
break;
case 'row':
value = 0;
break;
case 'stroke':
// !! TODO: These should be based on themes
if (spec.mark === 'text') value = this.theme.text.stroke;
else value = this.theme.markCommon.stroke;
break;
case 'strokeWidth':
if (spec.mark === 'rule') value = this.theme.rule.strokeWidth;
else if (spec.mark === 'withinLink' || spec.mark === 'betweenLink')
value = this.theme.link.strokeWidth;
else if (spec.mark === 'text') value = this.theme.text.strokeWidth;
else value = this.theme.markCommon.strokeWidth;
break;
case 'opacity':
value = this.theme.markCommon.opacity;
break;
case 'text':
value = '';
break;
default:
// console.warn(WARN_MSG(channelKey, 'value'));
}
if (typeof value !== 'undefined') {
spec[channelKey] = { value } as ChannelValue;
}
} else if (IsChannelDeep(channel) && (channel.type === 'quantitative' || channel.type === 'genomic')) {
if (channel.domain === undefined) {
const min =
'zeroBaseline' in channel && channel.zeroBaseline
? 0
: (d3min(data.map(d => +d[channel.field as string]) as number[]) as number) ?? 0;
const max = (d3max(data.map(d => +d[channel.field as string]) as number[]) as number) ?? 0;
channel.domain = [min, max]; // TODO: what if data ranges in negative values
} else if (channel.type === 'genomic' && !IsDomainArray(channel.domain)) {
channel.domain = getNumericDomain(channel.domain);
}
if (!channel.range) {
let range;
switch (channelKey) {
case 'x':
case 'xe':
case 'x1':
case 'x1e':
range = [0, spec.width];
break;
case 'y':
case 'ye':
range = [0, rowHeight];
break;
case 'color':
case 'stroke':
range = CHANNEL_DEFAULTS.QUANTITATIVE_COLOR as PREDEFINED_COLORS;
break;
case 'size':
range = this.theme.markCommon.quantitativeSizeRange;
break;
case 'strokeWidth':
range = [1, 3];
break;
case 'opacity':
range = [0, 1];
break;
default:
// console.warn(WARN_MSG(channelKey, channel.type));
break;
}
if (range) {
channel.range = range as PREDEFINED_COLORS | number[];
}
}
} else if (IsChannelDeep(channel) && channel.type === 'nominal') {
if (channel.domain === undefined) {
channel.domain = Array.from(new Set(data.map(d => d[channel.field as string]))) as string[];
}
if (!channel.range) {
let startSize = 2;
let range;
switch (channelKey) {
case 'x':
case 'xe':
range = [0, spec.width];
break;
case 'y':
case 'ye':
range = [rowHeight, 0]; // reversed because the origin is on the top
break;
case 'color':
case 'stroke':
range = this.theme.markCommon.nominalColorRange;
break;
case 'row':
range = [0, spec.height];
break;
case 'size':
range = (channel.domain as number[]).map(() => startSize++);
break;
default:
// console.warn(WARN_MSG(channelKey, channel.type));
break;
}
if (range) {
channel.range = range as number[] | string[];
}
}
}
}
});
/* Merge domains of neighbor channels (e.g., x and xe) */
[
['x', 'xe'],
['y', 'ye']
].forEach(pair => {
const [k1, k2] = pair as [keyof typeof ChannelTypes, keyof typeof ChannelTypes];
const c1 = spec[k1],
c2 = spec[k2];
if (
IsChannelDeep(c1) &&
IsChannelDeep(c2) &&
c1.type === c2.type &&
c1.domain &&
c2.domain &&
Array.isArray(c1.domain) &&
Array.isArray(c2.domain)
) {
if (c1.type === 'genomic' || c1.type === 'quantitative') {
const min = d3min([c1.domain[0] as number, c2.domain[0] as number]) as number;
const max = d3max([c1.domain[1] as number, c2.domain[1] as number]) as number;
c1.domain = c2.domain = [min, max];
} else if (c1.type === 'nominal') {
const range = Array.from(new Set([...c1.domain, ...c2.domain])) as string[];
c1.range = c2.range = range;
}
}
});
}
/**
* Store the scale of individual visual channels based on the `complete` spec.
*/
public generateScales() {
const spec = this.spec();
/// DEBUG
// console.log(spec);
//
SUPPORTED_CHANNELS.forEach(channelKey => {
const channel = spec[channelKey];
if (IsChannelValue(channel)) {
this.channelScales[channelKey] = () => channel.value;
} else if (IsChannelDeep(channel)) {
if (channelKey === 'text') {
// We do not generate scales for 'text' marks.
return;
}
const domain = channel.domain;
const range = channel.range;
if (domain === undefined || range === undefined) {
// we do not have sufficient info to generate scales
return;
}
if (channel.type === 'quantitative' || channel.type === 'genomic') {
switch (channelKey) {
case 'x':
case 'x1':
case 'xe':
case 'x1e':
case 'y':
case 'ye':
case 'size':
case 'opacity':
case 'strokeWidth':
this.channelScales[channelKey] = scaleLinear()
.domain(domain as [number, number])
.range(range as [number, number]);
break;
case 'color':
case 'stroke':
let interpolate = interpolateViridis;
if (Object.keys(PREDEFINED_COLOR_STR_MAP).includes(range as string)) {
interpolate = PREDEFINED_COLOR_STR_MAP[range as string];
}
this.channelScales[channelKey] = scaleSequential(interpolate).domain(
domain as [number, number]
);
break;
default:
break;
// console.warn('Not supported channel for calculating scales');
}
} else if (channel.type === 'nominal') {
switch (channelKey) {
case 'x':
case 'xe':
case 'y':
case 'ye':
case 'row':
this.channelScales[channelKey] = scaleBand()
.domain(domain as string[])
.range(range as [number, number]);
break;
case 'size':
this.channelScales[channelKey] = scaleOrdinal()
.domain(domain as string[])
.range(range as number[]);
break;
case 'color':
case 'stroke':
this.channelScales[channelKey] = scaleOrdinal(range as string[]).domain(domain as string[]);
break;
default:
break;
// console.warn('Not supported channel for calculating scales');
}
}
}
});
}
/**
* Return the scale of a visual channel.
* `undefined` if we do not have the scale.
*/
public getChannelScale(channelKey: keyof typeof ChannelTypes) {
return this.channelScales[channelKey];
}
/**
* Set a new scale for a certain channel.
*/
public setChannelScale(channelKey: keyof typeof ChannelTypes, scale: ScaleType) {
this.channelScales[channelKey] = scale;
}
public addDataRows(_: { [k: string]: number | string }[]) {
this.dataAggregated = [...this.dataAggregated, ..._];
}
/**
* Return whether to show y-axis.
*/
public isShowYAxis(): boolean {
const spec = this.spec();
const yDomain = this.getChannelDomainArray('y');
const yRange = this.getChannelRangeArray('y');
return (
IsChannelDeep(spec.y) && spec.y.axis !== 'none' && spec.y.type === 'quantitative' && !!yDomain && !!yRange
);
}
/**
* Return the domain of a visual channel.
* `undefined` if we do not have domain in array.
*/
public getChannelDomainArray(channelKey: keyof typeof ChannelTypes): string[] | number[] | undefined {
const c = this.spec()[channelKey];
return IsChannelDeep(c) && IsDomainArray(c.domain) ? c.domain : undefined;
}
/**
* Return the range of a visual channel.
* `undefined` if we do not have domain in array.
*/
public getChannelRangeArray(channelKey: keyof typeof ChannelTypes): string[] | number[] | undefined {
const c = this.spec()[channelKey];
return IsChannelDeep(c) && IsRangeArray(c.range) ? c.range : undefined;
}
/**
* Validate the original spec.
*/
public validateSpec(): { valid: boolean; errorMessages: string[] } {
return validateTrack(this.originalSpec());
}
} | the_stack |
import * as React from "react"
import {
findLastIndex,
min,
max,
maxBy,
last,
flatten,
excludeUndefined,
sortBy,
sumBy,
partition,
} from "../../clientUtils/Util"
import { action, computed, observable } from "mobx"
import { observer } from "mobx-react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import {
BASE_FONT_SIZE,
EntitySelectionMode,
SeriesName,
} from "../core/GrapherConstants"
import { DualAxisComponent } from "../axis/AxisViews"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { AxisConfig } from "../axis/AxisConfig"
import { ChartInterface } from "../chart/ChartInterface"
import { OwidTable } from "../../coreTable/OwidTable"
import { autoDetectYColumnSlugs, makeSelectionArray } from "../chart/ChartUtils"
import {
HorizontalAlign,
Position,
SortBy,
SortConfig,
SortOrder,
} from "../../clientUtils/owidTypes"
import { StackedPoint, StackedSeries } from "./StackedConstants"
import { ColorSchemes } from "../color/ColorSchemes"
import {
EntityName,
LegacyOwidRow,
OwidTableSlugs,
} from "../../coreTable/OwidTableConstants"
import {
HorizontalCategoricalColorLegend,
HorizontalColorLegendManager,
} from "../horizontalColorLegend/HorizontalColorLegends"
import { CategoricalBin } from "../color/ColorScaleBin"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { TippyIfInteractive } from "../chart/Tippy"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons/faInfoCircle"
import { DualAxis, HorizontalAxis, VerticalAxis } from "../axis/Axis"
import { ColorScale, ColorScaleManager } from "../color/ColorScale"
import {
ColorScaleConfig,
ColorScaleConfigDefaults,
} from "../color/ColorScaleConfig"
import { ColorSchemeName } from "../color/ColorConstants"
import { color } from "d3-color"
import { SelectionArray } from "../selection/SelectionArray"
import { ColorScheme } from "../color/ColorScheme"
import {
MarimekkoChartManager,
EntityColorData,
SimplePoint,
SimpleChartSeries,
BarShape,
Bar,
Item,
PlacedItem,
TooltipProps,
EntityWithSize,
LabelCandidate,
LabelWithPlacement,
LabelCandidateWithElement,
MarimekkoBarProps,
} from "./MarimekkoChartConstants"
const MARKER_MARGIN: number = 4
const MARKER_AREA_HEIGHT: number = 25
function MarimekkoBar({
bar,
tooltipProps,
barWidth,
isHovered,
isSelected,
isFaint,
entityColor,
y0,
isInteractive,
dualAxis,
}: MarimekkoBarProps): JSX.Element {
const { seriesName } = bar
const isPlaceholder = bar.kind === BarShape.BarPlaceholder
const barBaseColor =
entityColor ?? (bar.kind === BarShape.Bar ? bar.color : "#555")
const barColor =
bar.kind === BarShape.BarPlaceholder
? "#555"
: isHovered
? color(barBaseColor)?.brighter(0.9).toString() ?? barBaseColor
: isSelected
? color(barBaseColor)?.brighter(0.6).toString() ?? barBaseColor
: barBaseColor
const strokeColor = barColor
const strokeWidth = isHovered || isSelected ? "1px" : "0.5px"
const strokeOpacity = isPlaceholder ? 0.8 : isFaint ? 0.2 : 1.0
const fillOpacity = isHovered
? 0.7
: isFaint
? 0.2
: isSelected
? isPlaceholder
? 0.3
: 0.7
: 0.7
const overalOpacity = isPlaceholder ? 0.2 : 1.0
let barY: number = 0
let barHeight: number = 0
if (bar.kind === BarShape.Bar) {
barY = dualAxis.verticalAxis.place(y0 + bar.yPoint.valueOffset)
barHeight =
dualAxis.verticalAxis.place(y0) -
dualAxis.verticalAxis.place(bar.yPoint.value)
} else {
barY = dualAxis.verticalAxis.place(y0)
barHeight = bar.height
}
const barX = 0
const renderedBar = (
<g key={seriesName}>
<rect
x={0}
y={0}
transform={`translate(${barX}, ${barY - barHeight})`}
width={barWidth}
height={barHeight}
fill={barColor}
fillOpacity={fillOpacity}
stroke={strokeColor}
strokeWidth={strokeWidth}
strokeOpacity={strokeOpacity}
opacity={overalOpacity}
style={{
transition: "translate 200ms ease",
}}
/>
</g>
)
if (tooltipProps) {
return (
<TippyIfInteractive
lazy
isInteractive={isInteractive}
key={seriesName}
animation={false}
visible={isHovered}
content={<MarimekkoChart.Tooltip {...tooltipProps} />}
>
{renderedBar}
</TippyIfInteractive>
)
} else return renderedBar
}
interface MarimekkoBarsProps {
entityName: string
bars: Bar[]
entityColor: EntityColorData | undefined
isFaint: boolean
isHovered: boolean
isSelected: boolean
barWidth: number
tooltipProps: TooltipProps
currentX: number
onEntityMouseOver: (entityName: string) => void
onEntityMouseLeave: () => void
onEntityClick: (entityName: string) => void
labelYOffset: number
y0: number
noDataHeight: number
dualAxis: DualAxis
isExportingToSvgOrPng: boolean | undefined
}
function MarimekkoBarsForOneEntity(props: MarimekkoBarsProps): JSX.Element {
7
const {
entityName,
bars,
entityColor,
isFaint,
isHovered,
isSelected,
barWidth,
tooltipProps,
currentX,
onEntityClick,
onEntityMouseLeave,
onEntityMouseOver,
labelYOffset,
y0,
noDataHeight,
dualAxis,
isExportingToSvgOrPng,
} = props
let content = undefined
if (bars.length) {
let lastNonZeroBarIndex = findLastIndex(
bars,
(bar) => bar.yPoint.value > 0
)
lastNonZeroBarIndex = lastNonZeroBarIndex >= 0 ? lastNonZeroBarIndex : 0 // if we don't find an item with a nonzero value it doesn't really matter which one we pick
const predecessors = bars.slice(0, lastNonZeroBarIndex)
const lastNonZero = bars[lastNonZeroBarIndex]
const successors = bars.slice(lastNonZeroBarIndex + 1, bars.length)
// This is annoying - I tried to use the tippy element around all bars instead of inside
// one single bar but then it renders at the document origin instead of at the right attach point
// since we will switch to another tooltip solution anyhow I would leave it at this for now -
// later on this splitting into allbutlast and last can be removed and tooltips just done elsewhere
const predecessorBars = predecessors.map((bar) => (
<MarimekkoBar
key={`${entityName}-${bar.seriesName}`}
bar={bar}
tooltipProps={undefined}
barWidth={barWidth}
isHovered={isHovered}
isSelected={isSelected}
isFaint={isFaint}
entityColor={entityColor?.color}
y0={y0}
isInteractive={!isExportingToSvgOrPng}
dualAxis={dualAxis}
/>
))
const lastNonZeroBar = (
<MarimekkoBar
key={`${entityName}-${lastNonZero.seriesName}`}
bar={lastNonZero}
tooltipProps={{
...tooltipProps,
highlightedSeriesName: lastNonZero.seriesName,
}}
barWidth={barWidth}
isHovered={isHovered}
isSelected={isSelected}
isFaint={isFaint}
entityColor={entityColor?.color}
y0={y0}
isInteractive={!isExportingToSvgOrPng}
dualAxis={dualAxis}
/>
)
const successorBars = successors.map((bar) => (
<MarimekkoBar
key={`${entityName}-${bar.seriesName}`}
bar={bar}
tooltipProps={undefined}
barWidth={barWidth}
isHovered={isHovered}
isSelected={isSelected}
isFaint={isFaint}
entityColor={entityColor?.color}
y0={y0}
isInteractive={!isExportingToSvgOrPng}
dualAxis={dualAxis}
/>
))
content = [...predecessorBars, lastNonZeroBar, ...successorBars]
} else {
content = (
<MarimekkoBar
key={`${entityName}-placeholder`}
tooltipProps={tooltipProps}
bar={{
kind: BarShape.BarPlaceholder,
seriesName: entityName,
height: noDataHeight,
}}
barWidth={barWidth}
isHovered={isHovered}
isSelected={isSelected}
isFaint={isFaint}
entityColor={entityColor?.color}
y0={y0}
isInteractive={!isExportingToSvgOrPng}
dualAxis={dualAxis}
/>
)
}
return (
<g
key={entityName}
className="bar"
transform={`translate(${currentX}, ${labelYOffset})`}
onMouseOver={(): void => onEntityMouseOver(entityName)}
onMouseLeave={(): void => onEntityMouseLeave()}
onClick={(): void => onEntityClick(entityName)}
>
{content}
</g>
)
}
@observer
export class MarimekkoChart
extends React.Component<{
bounds?: Bounds
manager: MarimekkoChartManager
}>
implements ChartInterface, HorizontalColorLegendManager, ColorScaleManager
{
base: React.RefObject<SVGGElement> = React.createRef()
defaultBaseColorScheme = ColorSchemeName.continents
defaultNoDataColor = "#959595"
labelAngleInDegrees = -45 // 0 is horizontal, -90 is vertical from bottom to top, ...
transformTable(table: OwidTable): OwidTable {
if (!this.yColumnSlugs.length) return table
if (!this.xColumnSlug) return table
const { excludedEntities, includedEntities } = this.manager
const { yColumnSlugs, manager, colorColumnSlug, xColumnSlug } = this
if (excludedEntities || includedEntities) {
const excludedEntityIdsSet = new Set(excludedEntities)
const includedEntityIdsSet = new Set(includedEntities)
const excludeEntitiesFilter = (entityId: any): boolean =>
!excludedEntityIdsSet.has(entityId as number)
const includedEntitiesFilter = (entityId: any): boolean =>
includedEntityIdsSet.size > 0
? includedEntityIdsSet.has(entityId as number)
: true
const filterFn = (entityId: any): boolean =>
excludeEntitiesFilter(entityId) &&
includedEntitiesFilter(entityId)
const excludedList = excludedEntities
? excludedEntities.join(", ")
: ""
const includedList = includedEntities
? includedEntities.join(", ")
: ""
table = table.columnFilter(
OwidTableSlugs.entityId,
filterFn,
`Excluded entity ids specified by author: ${excludedList} - Included entity ids specified by author: ${includedList}`
)
}
// TODO: remove this filter once we don't have mixed type columns in datasets
table = table.replaceNonNumericCellsWithErrorValues(yColumnSlugs)
yColumnSlugs.forEach((slug) => {
table = table.interpolateColumnWithTolerance(slug)
})
table = table.interpolateColumnWithTolerance(xColumnSlug)
if (colorColumnSlug) {
const tolerance =
table.get(colorColumnSlug)?.display?.tolerance ?? Infinity
table = table.interpolateColumnWithTolerance(
colorColumnSlug,
tolerance
)
if (manager.matchingEntitiesOnly) {
table = table.dropRowsWithErrorValuesForColumn(colorColumnSlug)
}
}
if (!manager.showNoDataArea)
table = table.dropRowsWithErrorValuesForAllColumns(yColumnSlugs)
table = table.dropRowsWithErrorValuesForColumn(xColumnSlug)
if (manager.isRelativeMode) {
// TODO: this should not be necessary but we sometimes get NoMatchingValuesAfterJoin if both relative and showNoDataArea are set
table = table.dropRowsWithErrorValuesForColumn(
table.timeColumn.slug
)
table = table.toPercentageFromEachEntityForEachTime(xColumnSlug)
}
return table
}
@observable private hoveredEntityName?: string
@observable focusSeriesName?: SeriesName
@computed get inputTable(): OwidTable {
return this.manager.table
}
@computed get transformedTable(): OwidTable {
return (
this.manager.transformedTable ??
this.transformTable(this.inputTable)
)
}
@computed private get unstackedSeries(): StackedSeries<EntityName>[] {
const { colorScheme, yColumns } = this
return (
yColumns
.map((col, i) => {
return {
seriesName: col.displayName,
columnSlug: col.slug,
color:
col.def.color ??
colorScheme.getColors(yColumns.length)[i],
points: col.owidRows.map((row) => ({
time: row.time,
position: row.entityName,
value: row.value,
valueOffset: 0,
})),
}
})
// Do not plot columns without data
.filter((series) => series.points.length > 0)
)
}
//@computed private get rows(): readonly
@computed get series(): readonly StackedSeries<EntityName>[] {
const valueOffsets = new Map<string, number>()
return this.unstackedSeries.map((series) => ({
...series,
points: series.points.map((point) => {
const offset = valueOffsets.get(point.position) ?? 0
const newPoint = { ...point, valueOffset: offset }
valueOffsets.set(point.position, offset + point.value)
return newPoint
}),
}))
}
@computed get xSeries(): SimpleChartSeries {
const createStackedXPoints = (
rows: LegacyOwidRow<any>[]
): SimplePoint[] => {
const points: SimplePoint[] = []
for (const row of rows) {
points.push({
time: row.time,
value: row.value,
entity: row.entityName,
})
}
return points
}
const column = this.xColumn
return {
seriesName: column.displayName,
points: createStackedXPoints(column.owidRows),
}
}
@computed protected get yColumnSlugs(): string[] {
return (
this.manager.yColumnSlugsInSelectionOrder ??
autoDetectYColumnSlugs(this.manager)
)
}
@computed protected get xColumnSlug(): string | undefined {
return this.manager.xColumnSlug
}
@computed protected get xColumn(): CoreColumn {
const columnSlugs = this.xColumnSlug ? [this.xColumnSlug] : []
if (!columnSlugs.length) console.warn("No x column slug!")
return this.transformedTable.getColumns(columnSlugs)[0]
}
@computed private get latestTime(): number | undefined {
const times =
this.manager.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter?.getTimesUniqSortedAscForColumns(
this.yColumnSlugs
)
return times ? last(times) : undefined
}
@computed private get tableAtLatestTimelineTimepoint():
| OwidTable
| undefined {
if (this.latestTime)
return this.manager.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter?.filterByTargetTimes(
[this.latestTime],
0
)
else return undefined
}
@computed protected get xColumnAtLastTimePoint(): CoreColumn | undefined {
const columnSlug = this.xColumnSlug ? [this.xColumnSlug] : []
if (this.tableAtLatestTimelineTimepoint)
return this.tableAtLatestTimelineTimepoint.getColumns(columnSlug)[0]
else return undefined
}
@computed protected get yColumnsAtLastTimePoint(): CoreColumn[] {
const columnSlugs = this.yColumnSlugs
return (
this.tableAtLatestTimelineTimepoint?.getColumns(columnSlugs) ?? []
)
}
@computed protected get yColumns(): CoreColumn[] {
return this.transformedTable.getColumns(this.yColumnSlugs)
}
@computed private get colorScheme(): ColorScheme {
return (
(this.manager.baseColorScheme
? ColorSchemes[this.manager.baseColorScheme]
: undefined) ?? ColorSchemes["owid-distinct"]
)
}
@computed private get colorColumnSlug(): string | undefined {
return this.manager.colorColumnSlug
}
@computed private get colorColumn(): CoreColumn {
return this.transformedTable.get(this.colorColumnSlug)
}
colorScale = new ColorScale(this)
@computed get colorScaleConfig(): ColorScaleConfigDefaults | undefined {
return (
ColorScaleConfig.fromDSL(this.colorColumn.def) ??
this.manager.colorScale
)
}
@computed get colorScaleColumn(): CoreColumn {
// We need to use inputTable in order to get consistent coloring for a variable across
// charts, e.g. each continent being assigned to the same color.
// inputTable is unfiltered, so it contains every value that exists in the variable.
return this.inputTable.get(this.colorColumnSlug)
}
@computed private get sortConfig(): SortConfig {
return this.manager.sortConfig ?? {}
}
@computed private get manager(): MarimekkoChartManager {
return this.props.manager
}
@computed private get bounds(): Bounds {
return (this.props.bounds ?? DEFAULT_BOUNDS).padRight(10)
}
@computed private get innerBounds(): Bounds {
// This is a workaround to get the actual width of the vertical axis - dualAxis does this
// internally but we can't access this.dualAxis here due to a dependency cycle
const axis = this.verticalAxisPart.clone()
axis.range = [0, this.bounds.height]
const verticalAxisTrueWidth = axis.width
const whiteSpaceOnLeft = this.bounds.left + verticalAxisTrueWidth
const labelLinesHeight = MARKER_AREA_HEIGHT
// only pad left by the amount the longest label would exceed whatever space the
// vertical axis needs anyhow for label and tickmarks
const marginToEnsureWidestEntityLabelFitsEvenIfAtX0 =
Math.max(whiteSpaceOnLeft, this.longestLabelWidth) -
whiteSpaceOnLeft
return this.bounds
.padBottom(this.longestLabelHeight)
.padBottom(labelLinesHeight)
.padTop(this.legend.height + this.legendPaddingTop)
.padLeft(marginToEnsureWidestEntityLabelFitsEvenIfAtX0)
}
@computed private get baseFontSize(): number {
return this.manager.baseFontSize ?? BASE_FONT_SIZE
}
@computed private get x0(): number {
return 0
}
@computed private get y0(): number {
return 0
}
@computed private get allPoints(): StackedPoint<EntityName>[] {
return flatten(this.series.map((series) => series.points))
}
@computed private get yDomainDefault(): [number, number] {
const maxValues = this.allPoints.map(
(point) => point.value + point.valueOffset
)
return [
Math.min(this.y0, min(maxValues) as number),
Math.max(this.y0, max(maxValues) as number),
]
}
@computed private get xDomainDefault(): [number, number] {
const sum = sumBy(this.xSeries.points, (point) => point.value)
return [this.x0, sum]
}
@computed private get xRange(): [number, number] {
return [this.bounds.left, this.bounds.right]
}
@computed private get yAxisConfig(): AxisConfig {
return new AxisConfig(this.manager.yAxisConfig, this)
}
@computed private get xAxisConfig(): AxisConfig {
return new AxisConfig(
{ ...this.manager.xAxisConfig, orient: Position.top },
this
)
}
@computed private get verticalAxisPart(): VerticalAxis {
const config = this.yAxisConfig
const axis = config.toVerticalAxis()
axis.updateDomainPreservingUserSettings(this.yDomainDefault)
axis.formatColumn = this.yColumns[0]
const fallbackLabel =
this.yColumns.length > 0 ? this.yColumns[0].displayName : ""
axis.label = this.isNarrow ? "" : config.label || fallbackLabel
return axis
}
@computed private get isNarrow(): boolean {
// TODO: this should probably come from grapher?
return this.bounds.width < 650 // innerBounds would lead to dependency cycle
}
@computed private get xAxisLabelBase(): string {
const xDimName = this.xColumn?.displayName
if (this.manager.xOverrideTime !== undefined)
return `${xDimName} in ${this.manager.xOverrideTime}`
return xDimName
}
@computed private get horizontalAxisPart(): HorizontalAxis {
const { manager, xAxisLabelBase, xDomainDefault, xColumn } = this
const config = this.xAxisConfig
let axis = config.toHorizontalAxis()
if (manager.isRelativeMode) {
// MobX and classes interact in an annoying way here so we have to construct a new object via
// an object copy of the AxisConfig class instance to be able to set a property without
// making MobX unhappy about a mutation originating from a computed property
axis = new HorizontalAxis(
new AxisConfig(
{ ...config.toObject(), maxTicks: 10 },
config.fontSizeManager
)
)
axis.domain = [0, 100]
} else axis.updateDomainPreservingUserSettings(xDomainDefault)
axis.formatColumn = xColumn
const label = config.label || xAxisLabelBase
axis.label = label
return axis
}
@computed private get dualAxis(): DualAxis {
return new DualAxis({
bounds: this.innerBounds,
verticalAxis: this.verticalAxisPart,
horizontalAxis: this.horizontalAxisPart,
})
}
@computed private get selectionArray(): SelectionArray {
return makeSelectionArray(this.manager)
}
@computed private get selectedItems(): Item[] {
const selectedSet = this.selectionArray.selectedSet
const { sortedItems } = this
if (selectedSet.size === 0) return []
return sortedItems.filter((item) => selectedSet.has(item.entityName))
}
@computed private get domainColorForEntityMap(): Map<
string,
EntityColorData
> {
const { colorColumn, colorScale } = this
const entityNames = this.xColumn.uniqEntityNames
const hasColorColumn = !colorColumn.isMissing
const colorRowsByEntity = hasColorColumn
? colorColumn.owidRowsByEntityName
: undefined
const domainColorMap = new Map<string, EntityColorData>()
for (const name of entityNames) {
const colorDomainValue = colorRowsByEntity?.get(name)?.[0]
if (colorDomainValue) {
const color = colorScale.getColor(colorDomainValue.value)
if (color)
domainColorMap.set(name, {
color,
colorDomainValue: colorDomainValue.value,
})
}
}
return domainColorMap
}
@computed private get items(): Item[] {
const entityNames = this.xColumn.uniqEntityNames
const { xSeries, series, domainColorForEntityMap } = this
const items: Item[] = entityNames
.map((entityName) => {
const xPoint = xSeries.points.find(
(point) => point.entity === entityName
)
if (!xPoint) return undefined
const color = domainColorForEntityMap.get(entityName)
return {
entityName,
xPoint: xPoint,
entityColor: color,
bars: excludeUndefined(
series.map((series): Bar | undefined => {
const point = series.points.find(
(point) => point.position === entityName
)
if (!point) return undefined
return {
kind: BarShape.Bar,
yPoint: point,
color: series.color,
seriesName: series.seriesName,
}
})
),
}
})
.filter((item) => item) as Item[]
return items
}
@computed private get sortedItems(): Item[] {
const { items, sortConfig } = this
let sortByFunc: (item: Item) => number | string
switch (sortConfig.sortBy) {
case SortBy.entityName:
sortByFunc = (item: Item): string => item.entityName
break
case SortBy.column:
const sortColumnSlug = sortConfig.sortColumnSlug
sortByFunc = (item: Item): number =>
item.bars.find((b) => b.seriesName === sortColumnSlug)
?.yPoint.value ?? 0
break
default:
case SortBy.total:
sortByFunc = (item: Item): number => {
const lastPoint = last(item.bars)?.yPoint
if (!lastPoint) return 0
return lastPoint.valueOffset + lastPoint.value
}
}
const sortedItems = sortBy(items, sortByFunc)
const sortOrder = sortConfig.sortOrder ?? SortOrder.desc
if (sortOrder === SortOrder.desc) sortedItems.reverse()
const [itemsWithValues, itemsWithoutValues] = partition(
sortedItems,
(item) => item.bars.length !== 0
)
return [...itemsWithValues, ...itemsWithoutValues]
}
@computed get placedItems(): PlacedItem[] {
const { sortedItems, dualAxis, x0 } = this
const placedItems: PlacedItem[] = []
let currentX = 0
for (const item of sortedItems) {
placedItems.push({ ...item, xPosition: currentX })
const preciseX =
dualAxis.horizontalAxis.place(item.xPoint.value) -
dualAxis.horizontalAxis.place(x0)
currentX += preciseX
}
return placedItems
}
@computed get placedItemsMap(): Map<string, PlacedItem> {
return new Map(this.placedItems.map((item) => [item.entityName, item]))
}
// legend props
@computed get legendPaddingTop(): number {
return this.baseFontSize
}
@computed get legendX(): number {
return this.bounds.x
}
@computed get categoryLegendY(): number {
return this.bounds.top
}
@computed get legendOpacity(): number {
return 0.7
}
@computed get legendWidth(): number {
return this.bounds.width
}
@computed get legendAlign(): HorizontalAlign {
return HorizontalAlign.left
}
@computed get fontSize(): number {
return this.baseFontSize
}
@computed get categoricalLegendData(): CategoricalBin[] {
const { colorColumnSlug, colorScale, series } = this
if (colorColumnSlug) return colorScale.categoricalLegendBins
else
return series.map((series, index) => {
return new CategoricalBin({
index,
value: series.seriesName,
label: series.seriesName,
color: series.color,
})
})
}
@action.bound onLegendMouseOver(bin: CategoricalBin): void {
this.focusSeriesName = bin.value
}
@action.bound onLegendMouseLeave(): void {
this.focusSeriesName = undefined
}
@computed private get legend(): HorizontalCategoricalColorLegend {
return new HorizontalCategoricalColorLegend({ manager: this })
}
@computed private get formatColumn(): CoreColumn {
return this.yColumns[0]
}
@action.bound private onEntityMouseOver(entityName: string): void {
this.hoveredEntityName = entityName
}
@action.bound private onEntityMouseLeave(): void {
this.hoveredEntityName = undefined
}
@action.bound private onEntityClick(entityName: string): void {
this.onSelectEntity(entityName)
}
@action.bound private onSelectEntity(entityName: string): void {
if (this.canAddCountry) this.selectionArray.toggleSelection(entityName)
}
@computed private get canAddCountry(): boolean {
const { addCountryMode } = this.manager
return (addCountryMode &&
addCountryMode !== EntitySelectionMode.Disabled) as boolean
}
render(): JSX.Element {
if (this.failMessage)
return (
<NoDataModal
manager={this.manager}
bounds={this.bounds}
message={this.failMessage}
/>
)
const { bounds, dualAxis } = this
return (
<g ref={this.base} className="MarimekkoChart">
<rect
x={bounds.left}
y={bounds.top}
width={bounds.width}
height={bounds.height}
opacity={0}
fill="rgba(255,255,255,0)"
/>
<DualAxisComponent dualAxis={dualAxis} showTickMarks={true} />
<HorizontalCategoricalColorLegend manager={this} />
{this.renderBars()}
</g>
)
}
private renderBars(): JSX.Element[] {
const normalElements: JSX.Element[] = []
const highlightedElements: JSX.Element[] = [] // highlighted elements have a thicker stroke and should be drawn last to overlap others
const {
dualAxis,
x0,
y0,
focusSeriesName,
placedLabels,
labelLines,
placedItems,
hoveredEntityName,
} = this
const selectionSet = this.selectionArray.selectedSet
const targetTime = this.manager.endTime
const timeColumn = this.inputTable.timeColumn
const yAxisColumn = this.formatColumn
const xAxisColumn = this.xColumn
const labelYOffset = 0
const hasSelection = selectionSet.size > 0
let noDataAreaElement = undefined
let noDataLabel = undefined
let patterns: JSX.Element[] = []
const noDataHeight = Bounds.forText("no data").height + 10 // dualAxis.verticalAxis.rangeSize
const firstNanValue = placedItems.findIndex((item) => !item.bars.length)
const anyNonNanAfterFirstNan =
firstNanValue >= 0
? placedItems
.slice(firstNanValue)
.some((item) => item.bars.length !== 0)
: false
if (anyNonNanAfterFirstNan)
console.error("Found Non-NAN values after NAN value!")
if (firstNanValue !== -1) {
const firstNanValueItem = placedItems[firstNanValue]
const lastItem = last(placedItems)!
const noDataRangeStartX =
firstNanValueItem.xPosition + dualAxis.horizontalAxis.place(x0)
const noDataRangeEndX =
lastItem?.xPosition +
dualAxis.horizontalAxis.place(lastItem.xPoint.value)
const yStart = dualAxis.verticalAxis.place(y0)
const noDataLabelX =
noDataRangeStartX + (noDataRangeEndX - noDataRangeStartX) / 2
const boundsForNoData = Bounds.forText("no data")
const noDataLabelY = yStart - boundsForNoData.width
noDataLabel = (
<text
key={`noDataArea-label`}
x={0}
transform={`rotate(-90, ${noDataLabelX}, ${noDataLabelY})
translate(${noDataLabelX}, ${noDataLabelY})`}
y={0}
width={noDataRangeEndX - noDataRangeStartX}
height={noDataHeight}
fontWeight={700}
fill="#666"
opacity={1}
fontSize="0.8em"
textAnchor="middle"
dominantBaseline="middle"
style={{ pointerEvents: "none" }}
>
no data
</text>
)
noDataAreaElement = (
<rect
key="noDataArea"
x={noDataRangeStartX}
y={yStart - noDataHeight}
//transform={`translate(${barX}, ${barY - barHeight})`}
width={noDataRangeEndX - noDataRangeStartX}
height={noDataHeight}
fill={"url(#diagonalHatch)"}
// stroke={strokeColor}
// strokeWidth={strokeWidth}
opacity={0.5}
></rect>
)
patterns = [
<pattern
id="diagonalHatch"
key="diagonalHatch"
patternUnits="userSpaceOnUse"
width="4"
height="4"
patternTransform="rotate(-45 2 2)"
>
<path d="M -1,2 l 6,0" stroke="#ccc" strokeWidth="1" />
</pattern>,
]
}
for (const item of placedItems) {
const { entityName, bars, xPoint, entityColor } = item
const currentX = dualAxis.horizontalAxis.place(x0) + item.xPosition
const tooltipProps = {
item,
targetTime,
timeColumn,
yAxisColumn,
xAxisColumn,
}
const barWidth =
dualAxis.horizontalAxis.place(xPoint.value) -
dualAxis.horizontalAxis.place(x0)
const isSelected = selectionSet.has(entityName)
const isHovered = entityName === hoveredEntityName
const isFaint =
(focusSeriesName !== undefined &&
entityColor?.colorDomainValue !== focusSeriesName) ||
(hasSelection && !isSelected)
const barsProps = {
entityName,
bars,
xPoint,
entityColor,
isFaint,
isHovered,
isSelected,
barWidth,
tooltipProps,
currentX,
onEntityClick: this.onEntityClick,
onEntityMouseLeave: this.onEntityMouseLeave,
onEntityMouseOver: this.onEntityMouseOver,
labelYOffset,
y0,
noDataHeight,
dualAxis,
isExportingToSvgOrPng: this.manager.isExportingtoSvgOrPng,
}
const result = (
<MarimekkoBarsForOneEntity key={entityName} {...barsProps} />
)
if (isSelected || isHovered) highlightedElements.push(result)
else normalElements.push(result)
}
return ([] as JSX.Element[]).concat(
patterns,
noDataAreaElement ? [noDataAreaElement] : [],
normalElements,
placedLabels,
labelLines,
highlightedElements,
noDataLabel ? [noDataLabel] : []
)
}
private paddingInPixels = 5
private static labelCandidateFromItem(
item: EntityWithSize,
baseFontSize: number,
isSelected: boolean
): LabelCandidate {
return {
item: item,
bounds: Bounds.forText(item.entityName, {
fontSize: 0.7 * baseFontSize,
}),
isPicked: isSelected,
isSelected,
}
}
/** This function splits label candidates into N groups so that each group has approximately
the same sum of x value metric. This is useful for picking labels because we want to have e.g.
20 labels relatively evenly spaced (in x domain space) and this function gives us 20 groups that
are roughly of equal size and then we can pick the largest of each group */
private static splitIntoEqualDomainSizeChunks(
candidates: LabelCandidate[],
numChunks: number
): LabelCandidate[][] {
const chunks: LabelCandidate[][] = []
let currentChunk: LabelCandidate[] = []
let domainSizeOfChunk = 0
const domainSizeThreshold = Math.ceil(
sumBy(candidates, (candidate) => candidate.item.xValue) / numChunks
)
for (const candidate of candidates) {
while (domainSizeOfChunk > domainSizeThreshold) {
chunks.push(currentChunk)
currentChunk = []
domainSizeOfChunk -= domainSizeThreshold
}
domainSizeOfChunk += candidate.item.xValue
currentChunk.push(candidate)
}
chunks.push(currentChunk)
return chunks.filter((chunk) => chunk.length > 0)
}
@computed private get pickedLabelCandidates(): LabelCandidate[] {
const {
xColumnAtLastTimePoint,
yColumnsAtLastTimePoint,
selectedItems,
xRange,
baseFontSize,
paddingInPixels,
} = this
if (!xColumnAtLastTimePoint || yColumnsAtLastTimePoint.length === 0)
return []
// Measure the labels (before any rotation, just normal horizontal labels)
const selectedItemsSet = new Set(
selectedItems.map((item) => item.entityName)
)
// This is similar to what we would get with .sortedItems but
// we want this for the last year to pick all labels there - sortedItems
// changes with the time point the user selects
const ySizeMap: Map<string, number> = new Map(
yColumnsAtLastTimePoint[0].owidRows.map((row) => [
row.entityName,
row.value,
])
)
const labelCandidates: LabelCandidate[] =
xColumnAtLastTimePoint.owidRows.map((row) =>
MarimekkoChart.labelCandidateFromItem(
{
entityName: row.entityName,
xValue: row.value,
ySortValue: ySizeMap.get(row.entityName),
},
baseFontSize,
selectedItemsSet.has(row.entityName)
)
)
labelCandidates.sort((a, b) => {
const yRowsForA = a.item.ySortValue
const yRowsForB = b.item.ySortValue
if (yRowsForA !== undefined && yRowsForB !== undefined)
return yRowsForB - yRowsForA
else if (yRowsForA === undefined && yRowsForB !== undefined)
return -1
else if (yRowsForA !== undefined && yRowsForB === undefined)
return 1
// (yRowsForA === undefined && yRowsForB === undefined)
else return 0
})
const averageCharacterCount =
sumBy(labelCandidates, (item) => item.item.entityName.length) /
labelCandidates.length
const firstDefined = labelCandidates.find(
(item) => item.item.ySortValue !== undefined
)
const labelCharacterCountThreshold = 1.4 * averageCharacterCount
// Always pick the first and last element and the first one that is not undefined for y
// but only if it is less than 1.4 times as long in character count as the average label (avoid
// picking "Democratic Republic of Congo" for this reason and thus needing lots of space)
if (
firstDefined &&
firstDefined.item.entityName.length < labelCharacterCountThreshold
)
firstDefined.isPicked = true
const labelHeight = labelCandidates[0].bounds.height
if (
labelCandidates[labelCandidates.length - 1].item.entityName.length <
labelCharacterCountThreshold
)
labelCandidates[labelCandidates.length - 1].isPicked = true
const availablePixels = xRange[1] - xRange[0]
const numLabelsToAdd = Math.floor(
Math.min(availablePixels / (labelHeight + paddingInPixels) / 4, 20) // factor 4 is arbitrary to taste
)
const chunks = MarimekkoChart.splitIntoEqualDomainSizeChunks(
labelCandidates,
numLabelsToAdd
)
const picks = chunks.flatMap((chunk) => {
const picked = chunk.filter((candidate) => candidate.isPicked)
if (picked.length > 0) return picked
else {
return maxBy(chunk, (candidate) => candidate.item.xValue)
}
})
for (const max of picks) {
if (max) max.isPicked = true
}
const picked = labelCandidates.filter((candidate) => candidate.isPicked)
return picked
}
@computed private get labelsWithPlacementInfo(): LabelWithPlacement[] {
const {
dualAxis,
x0,
placedItemsMap,
labels,
unrotatedLongestLabelWidth,
unrotatedHighestLabelHeight,
labelAngleInDegrees,
} = this
const labelsYPosition = dualAxis.verticalAxis.place(0)
const labelsWithPlacements: LabelWithPlacement[] = labels
.map(({ candidate, labelElement }) => {
const item = placedItemsMap.get(candidate.item.entityName)
const xPoint = item?.xPoint.value ?? 0
const barWidth =
dualAxis.horizontalAxis.place(xPoint) -
dualAxis.horizontalAxis.place(x0)
const labelId = candidate.item.entityName
if (!item) {
console.error(
"Could not find item",
candidate.item.entityName
)
return null
} else {
const currentX =
dualAxis.horizontalAxis.place(x0) + item.xPosition
const labelWithPlacement = {
label: (
<g
transform={`translate(${0}, ${labelsYPosition})`}
>
{labelElement}
</g>
),
preferredPlacement: currentX + barWidth / 2,
correctedPlacement: currentX + barWidth / 2,
labelKey: labelId,
}
return labelWithPlacement
}
})
.filter(
(item: LabelWithPlacement | null): item is LabelWithPlacement =>
item !== null
)
// This collision detection code is optimized for the particular
// case of distributing items in 1D, knowing that we picked a low
// enough number of labels that we will be able to fit all labels.
// The algorithm iterates the list twice, i.e. works in linear time
// with the number of labels to show
// The logic in pseudo code:
// for current, next in iterate-left-to-right-pairs:
// if next.x < current.x + label-width:
// next.x = current.x + label-width
// last.x = Math.min(last.x, max-x)
// for current, prev in iterate-right-to-left-pairs:
// if prev.x > current.x - label-width:
// prev.x = current.x - label-width
// The label width is uniform for now and starts with
// the height of a label when printed in normal horizontal layout
// Since labels are rotated we need to make a bit more space so that they
// stack correctly. Consider:
// ╱---╱ ╱---╱
// ╱ ╱ ╱ ╱
// ╱ ╱ ╱ ╱
// ╱---╱ ╱---╱
// If we would just use exactly the label width then the flatter the angle
// the more they would actually overlap so we need a correction factor. It turns
// out than tan(angle) is the correction factor we want, although for horizontal
// labels we don't want to use +infinity :) so we Math.min it with the longest label width
if (labelsWithPlacements.length === 0) return []
labelsWithPlacements.sort(
(a, b) => a.preferredPlacement - b.preferredPlacement
)
const labelWidth = unrotatedHighestLabelHeight
const correctionFactor =
1 +
Math.min(
unrotatedLongestLabelWidth / labelWidth,
Math.abs(Math.tan(labelAngleInDegrees))
)
const correctedLabelWidth = labelWidth * correctionFactor
for (let i = 0; i < labelsWithPlacements.length - 1; i++) {
const current = labelsWithPlacements[i]
const next = labelsWithPlacements[i + 1]
const minNextX = current.correctedPlacement + correctedLabelWidth
if (next.correctedPlacement < minNextX)
next.correctedPlacement = minNextX
}
labelsWithPlacements[
labelsWithPlacements.length - 1
].correctedPlacement = Math.min(
labelsWithPlacements[labelsWithPlacements.length - 1]
.correctedPlacement,
dualAxis.horizontalAxis.rangeSize
)
for (let i = labelsWithPlacements.length - 1; i > 0; i--) {
const current = labelsWithPlacements[i]
const previous = labelsWithPlacements[i - 1]
const maxPreviousX =
current.correctedPlacement - correctedLabelWidth
if (previous.correctedPlacement > maxPreviousX)
previous.correctedPlacement = maxPreviousX
}
return labelsWithPlacements
}
@computed private get labelLines(): JSX.Element[] {
const { labelsWithPlacementInfo, dualAxis, selectedItems } = this
const shiftedGroups: LabelWithPlacement[][] = []
const unshiftedElements: LabelWithPlacement[] = []
const selectedItemsKeys = new Set(
selectedItems.map((item) => item.entityName)
)
let startNewGroup = true
const barEndpointY = dualAxis.verticalAxis.place(0)
for (const labelWithPlacement of labelsWithPlacementInfo) {
if (
labelWithPlacement.preferredPlacement ===
labelWithPlacement.correctedPlacement
) {
unshiftedElements.push(labelWithPlacement)
startNewGroup = true
} else {
if (startNewGroup) {
shiftedGroups.push([labelWithPlacement])
startNewGroup = false
} else {
shiftedGroups[shiftedGroups.length - 1].push(
labelWithPlacement
)
}
}
}
// If we wanted to hide the label lines if all lines are straight
// then we could do this but this makes it jumpy over time
// if (shiftedGroups.length === 0) return []
// else {
const labelLines: JSX.Element[] = []
for (const group of shiftedGroups) {
let indexInGroup = 0
for (const item of group) {
const lineColor = selectedItemsKeys.has(item.labelKey)
? "#999"
: "#bbb"
const markerBarEndpointX = item.preferredPlacement
const markerTextEndpointX = item.correctedPlacement
const markerBarEndpointY = barEndpointY + MARKER_MARGIN
const markerTextEndpointY =
barEndpointY + MARKER_AREA_HEIGHT - MARKER_MARGIN
const markerNetHeight = MARKER_AREA_HEIGHT - 2 * MARKER_MARGIN
const markerStepSize = markerNetHeight / (group.length + 1)
const directionUnawareMakerYMid =
(indexInGroup + 1) * markerStepSize
const markerYMid =
markerBarEndpointX > markerTextEndpointX
? directionUnawareMakerYMid
: markerNetHeight - directionUnawareMakerYMid
labelLines.push(
<g className="indicator" key={`labelline-${item.labelKey}`}>
<path
d={`M${markerBarEndpointX},${markerBarEndpointY} v${markerYMid} H${markerTextEndpointX} V${markerTextEndpointY}`}
stroke={lineColor}
strokeWidth={1}
fill="none"
/>
</g>
)
indexInGroup++
}
}
for (const item of unshiftedElements) {
const lineColor = selectedItemsKeys.has(item.labelKey)
? "#555"
: "#bbb"
const markerBarEndpointX = item.preferredPlacement
const markerBarEndpointY = barEndpointY + MARKER_MARGIN
const markerTextEndpointY =
barEndpointY + MARKER_AREA_HEIGHT - MARKER_MARGIN
labelLines.push(
<g className="indicator" key={`labelline-${item.labelKey}`}>
<path
d={`M${markerBarEndpointX},${markerBarEndpointY} V${markerTextEndpointY}`}
stroke={lineColor}
strokeWidth={1}
fill="none"
/>
</g>
)
}
return labelLines
//}
}
@computed private get placedLabels(): JSX.Element[] {
const labelOffset = MARKER_AREA_HEIGHT
// old logic tried to hide labellines but that is too jumpy
// labelLines.length
// ? MARKER_AREA_HEIGHT
// : this.baseFontSize / 2
const placedLabels = this.labelsWithPlacementInfo.map((item) => (
<g
key={`label-${item.labelKey}`}
className="bar-label"
transform={`translate(${item.correctedPlacement}, ${labelOffset})`}
>
{item.label}
</g>
))
return placedLabels
}
@computed private get unrotatedLongestLabelWidth(): number {
const widths = this.pickedLabelCandidates.map(
(candidate) => candidate.bounds.width
)
const maxWidth = Math.max(...widths)
return maxWidth
}
@computed private get unrotatedHighestLabelHeight(): number {
const heights = this.pickedLabelCandidates.map(
(candidate) => candidate.bounds.height
)
return Math.max(...heights)
}
@computed private get longestLabelHeight(): number {
// This takes the angle of rotation of the entity labels into account
// This is somewhat simplified as we treat this as a one-dimensional
// entity whereas in reality the textbox if of course 2D. To account
// for that we do max(fontSize, rotatedLabelHeight) in the end
// as a rough proxy
const rotatedLabelHeight =
this.unrotatedLongestLabelWidth *
Math.abs(Math.sin((this.labelAngleInDegrees * Math.PI) / 180))
return Math.max(this.fontSize, rotatedLabelHeight)
}
@computed private get longestLabelWidth(): number {
// This takes the angle of rotation of the entity labels into account
// This is somewhat simplified as we treat this as a one-dimensional
// entity whereas in reality the textbox if of course 2D. To account
// for that we do max(fontSize, rotatedLabelHeight) in the end
// as a rough proxy
const rotatedLabelWidth =
this.unrotatedLongestLabelWidth *
Math.abs(Math.cos((this.labelAngleInDegrees * Math.PI) / 180))
return Math.max(this.fontSize, rotatedLabelWidth)
}
@computed private get labels(): LabelCandidateWithElement[] {
const { labelAngleInDegrees, series, domainColorForEntityMap } = this
return this.pickedLabelCandidates.map((candidate) => {
const labelX = candidate.bounds.width
const domainColor = domainColorForEntityMap.get(
candidate.item.entityName
)
const seriesColor = series[0].color
const color = domainColor?.color ?? seriesColor ?? "#000"
return {
candidate,
labelElement: (
<text
key={`${candidate.item.entityName}-label`}
x={-labelX}
y={0}
width={candidate.bounds.width}
height={candidate.bounds.height}
fontWeight={candidate.isSelected ? 700 : 400}
fill={color}
transform={`rotate(${labelAngleInDegrees}, 0, 0)`}
opacity={1}
fontSize="0.7em"
textAnchor="right"
dominantBaseline="middle"
onMouseOver={(): void =>
this.onEntityMouseOver(candidate.item.entityName)
}
onMouseLeave={(): void => this.onEntityMouseLeave()}
onClick={(): void =>
this.onEntityClick(candidate.item.entityName)
}
>
{candidate.item.entityName}
</text>
),
}
})
}
static Tooltip(props: TooltipProps): JSX.Element {
const isSingleVariable = props.item.bars.length === 1
// shouldShowXTimeNoitice is a bit of a lie since at the moment we don't include
// entities that don't have x values for the current year. This might change though
// and then the mechanism is already in place
const shouldShowXTimeNotice =
props.item.xPoint.time !== props.targetTime
let hasTimeNotice = shouldShowXTimeNotice
const header = isSingleVariable ? (
<tr>
<td>
<div
style={{
width: "10px",
height: "10px",
backgroundColor: props.item.entityColor?.color,
display: "inline-block",
}}
/>
</td>
<td colSpan={3} style={{ color: "#111" }}>
<strong>{props.item.entityName}</strong>
</td>
</tr>
) : (
<tr>
<td colSpan={4} style={{ color: "#111" }}>
<strong>{props.item.entityName}</strong>
</td>
</tr>
)
return (
<table
style={{
lineHeight: "1em",
whiteSpace: "normal",
borderSpacing: "0.5em",
}}
>
<tbody>
{header}
{props.item.bars.map((bar) => {
const { highlightedSeriesName } = props
const squareColor = bar.color
const isHighlighted =
bar.seriesName === highlightedSeriesName
const isFaint =
highlightedSeriesName !== undefined &&
!isHighlighted
const shouldShowYTimeNotice =
bar.yPoint.value !== undefined &&
bar.yPoint.time !== props.targetTime
hasTimeNotice ||= shouldShowYTimeNotice
const colorSquare = isSingleVariable ? null : (
<div
style={{
width: "10px",
height: "10px",
backgroundColor: squareColor,
display: "inline-block",
}}
/>
)
return (
<tr
key={`${bar.seriesName}`}
style={{
color: isHighlighted
? "#000"
: isFaint
? "#707070"
: "#444",
}}
>
<td>{colorSquare}</td>
<td
style={{
paddingRight: "0.8em",
fontSize: "0.9em",
}}
>
{bar.seriesName}
</td>
<td
style={{
textAlign: "right",
whiteSpace: "nowrap",
}}
>
{bar.yPoint.value === undefined
? "No data"
: props.yAxisColumn.formatValueShort(
bar.yPoint.value,
{
noTrailingZeroes: false,
}
)}
</td>
{shouldShowYTimeNotice && (
<td
style={{
fontWeight: "normal",
color: "#707070",
fontSize: "0.8em",
whiteSpace: "nowrap",
paddingLeft: "8px",
}}
>
<span className="icon">
<FontAwesomeIcon
icon={faInfoCircle}
style={{
marginRight: "0.25em",
}}
/>{" "}
</span>
{props.timeColumn.formatValue(
bar.yPoint.time
)}
</td>
)}
</tr>
)
})}
<tr>
<td></td>
<td>{props.xAxisColumn.displayName}</td>
<td
style={{
textAlign: "right",
whiteSpace: "nowrap",
}}
>
{props.xAxisColumn.formatValueShort(
props.item.xPoint.value
)}
{shouldShowXTimeNotice && (
<td
style={{
fontWeight: "normal",
color: "#707070",
fontSize: "0.8em",
whiteSpace: "nowrap",
paddingLeft: "8px",
}}
>
<span className="icon">
<FontAwesomeIcon
icon={faInfoCircle}
style={{
marginRight: "0.25em",
}}
/>{" "}
</span>
{props.timeColumn.formatValue(
props.item.xPoint.time
)}
</td>
)}
</td>
<td></td>
</tr>
{hasTimeNotice && (
<tr>
<td
colSpan={4}
style={{
color: "#707070",
fontSize: "0.8em",
paddingTop: "10px",
}}
>
<div style={{ display: "flex" }}>
<span
className="icon"
style={{ marginRight: "0.5em" }}
>
<FontAwesomeIcon icon={faInfoCircle} />{" "}
</span>
<span>
No data available for{" "}
{props.timeColumn.formatValue(
props.targetTime
)}
. Showing closest available data point
instead.
</span>
</div>
</td>
</tr>
)}
</tbody>
</table>
)
}
@computed get failMessage(): string {
const column = this.yColumns[0]
const { yColumns, yColumnSlugs, xColumn } = this
if (!column) return "No Y column to chart"
if (!xColumn) return "No X column to chart"
return yColumns.every((col) => col.isEmpty)
? `No matching data in columns ${yColumnSlugs.join(", ")}`
: ""
}
} | the_stack |
module powerbi.extensibility.visual {
import valueFormatter = powerbi.extensibility.utils.formatting.valueFormatter;
export abstract class Layer {
protected parent: MapboxMap;
protected source: data.Datasource;
protected id: string;
protected prevLabelPositionSetting: string;
protected colorStops: ColorStops;
constructor(map: MapboxMap) {
this.parent = map;
this.prevLabelPositionSetting = map.getSettings().api.labelPosition;
}
updateSource(features, roleMap, settings) {
if (settings[this.id].show) {
this.source.update(this.parent.getMap(), features, roleMap, settings);
}
}
getBounds(settings) : any[] {
if (settings[this.id].show) {
return this.source.getBounds();
}
return null;
}
getId() {
return this.id
}
abstract getLayerIDs()
updateSelection(features, roleMap) {
}
hoverHighLight(e) {
}
removeHighlight(roleMap) {
}
public getColorStops(): ColorStops {
return this.colorStops;
}
static mapValuesToColorStops(colorInterval: string[], method: ClassificationMethod, classCount:number, values: number[]): ColorStops {
if (!values || values.length == 0) {
return []
}
if (values.length == 1) {
const colorStop = values[0];
const color = colorInterval[0];
return [{colorStop, color}];
}
const domain: number[] = classCount ? mapboxUtils.getBreaks(values, method, classCount) : values;
const colors = chroma.scale(colorInterval).colors(domain.length)
return domain.map((colorStop, idx) => {
const color = colors[idx].toString();
return {colorStop, color};
});
}
generateColorStops(settings: CircleSettings | ChoroplethSettings | ClusterSettings, isGradient: boolean, colorLimits: mapboxUtils.Limits, colorPalette: Palette): ColorStops {
if (!isGradient) {
return colorLimits.values.map(value => {
const colorStop = value.toString();
const color = colorPalette.getColor(colorStop);
return { colorStop, color };
});
}
if ( settings instanceof ClusterSettings || !settings.diverging) {
const classCount = mapboxUtils.getClassCount(colorLimits.values);
return Layer.mapValuesToColorStops([settings.minColor, settings.maxColor], this.getClassificationMethod(), classCount, colorLimits.values)
}
const { minValue, midValue, maxValue, minColor, midColor, maxColor} = settings
const filteredValues = mapboxUtils.filterValues(colorLimits.values, minValue, maxValue)
// Split the interval into two halves when there is a middle value
if (midValue != null) {
const lowerHalf = []
const upperHalf = []
if (minValue != null) {
lowerHalf.push(minValue)
}
filteredValues.forEach(value => {
if (value < midValue) {
lowerHalf.push(value)
}
else {
upperHalf.push(value)
}
})
if (maxValue != null) {
upperHalf.push(maxValue)
}
// Add midValue to both interval
lowerHalf.push(midValue)
upperHalf.unshift(midValue)
// Divide the colorstops between the two intervals (halve them)
const lowerHalfClassCount = mapboxUtils.getClassCount(lowerHalf) >> 1;
const upperHalfClassCount = mapboxUtils.getClassCount(upperHalf) >> 1;
const lowerColorStops = Layer.mapValuesToColorStops([minColor, midColor], this.getClassificationMethod(), lowerHalfClassCount, lowerHalf)
const upperColorStops = Layer.mapValuesToColorStops([midColor, maxColor], this.getClassificationMethod(), upperHalfClassCount, upperHalf)
// Make sure the midValue included only once
lowerColorStops.pop()
return lowerColorStops.concat(upperColorStops)
}
if (minValue != null) {
filteredValues.push(minValue)
}
if (maxValue != null) {
filteredValues.push(maxValue)
}
const classCount = mapboxUtils.getClassCount(filteredValues);
return Layer.mapValuesToColorStops([minColor, midColor, maxColor], this.getClassificationMethod(), classCount, filteredValues)
}
getClassificationMethod(): ClassificationMethod {
return ClassificationMethod.Quantile
}
applySettings(settings: MapboxSettings, roleMap) {
const map = this.parent.getMap();
if (settings[this.id].show) {
if (this.prevLabelPositionSetting === settings.api.labelPosition) {
if (!this.layerExists()) {
let firstSymbolId = this.calculateLabelPosition(settings, map)
this.addLayer(settings, firstSymbolId, roleMap);
}
} else {
const firstSymbolId = this.calculateLabelPosition(settings, map)
this.moveLayer(firstSymbolId)
}
} else {
if (this.layerExists()) {
this.removeLayer();
}
}
if (this.prevLabelPositionSetting !== settings.api.labelPosition) {
this.prevLabelPositionSetting = settings.api.labelPosition;
}
}
addLayer(settings, beforeLayerId: string, roleMap) {}
moveLayer(beforeLayerId: string) {}
abstract removeLayer()
layerExists() {
const map = this.parent.getMap();
const layer = map.getLayer(this.id);
return layer != null;
}
getSource(settings) {
if (settings[this.id].show) {
this.source.ensure(this.parent.getMap(), this.id, settings);
return this.source;
}
return null;
}
handleZoom(settings) : boolean {
if (settings[this.id].show) {
return this.source.handleZoom(this.parent.getMap(), settings);
}
return false;
}
hasTooltip(tooltips) {
if (!tooltips) {
// Do not show tooltip if no property is pulled into 'tooltips' data role
return false;
}
return true;
}
getFormattedTooltipValue(roleMap, data): string {
const displayName = data.displayName
const tooltipData = roleMap.tooltips[displayName];
let value = data.value
if (tooltipData && tooltipData.format) {
const { format, type } = tooltipData
if (type.dateTime) {
value = new Date(data.value);
if (isNaN(value)) {
// Print original text if the date string is invalid.
value = data.value;
}
} else if (type.numeric) {
value = Number(data.value);
}
value = valueFormatter.format(value, format);
}
return value;
}
/*
Override this method and implement the custom logic to show tooltips for a custom layer
*/
handleTooltip(tooltipEvent: TooltipEventArgs<number>, roleMap, settings): VisualTooltipDataItem[] {
return [];
}
calculateLabelPosition(settings: MapboxSettings, map: mapboxgl.Map) {
// If there is no firstSymbolId specified, it adds the data as the last element.
let firstSymbolId = null;
if (settings.api.labelPosition === 'above') {
// For default styles place data under waterway-label layer
firstSymbolId = 'waterway-label';
if (settings.api.style == 'mapbox://styles/mapbox/satellite-v9?optimize=true' ||
settings.api.style == 'custom') {
// For custom style find the lowest symbol layer to place data underneath
firstSymbolId = '';
let layers = map.getStyle().layers;
for (let i = 0; i < layers.length; i++) {
if (layers[i].type === 'symbol') {
firstSymbolId = layers[i].id;
break;
}
}
}
}
return firstSymbolId;
}
static getTooltipData(value: any): VisualTooltipDataItem[] {
if (!value) {
return [];
}
// Flatten the multiple properties or multiple datapoints
return [].concat.apply([], value.map(properties => {
// This mapping is needed to copy the value with the toString
// call as otherwise some caching logic causes to be the same
// tooltip displayed for all datapoints.
return properties.map(prop => {
return {
displayName: prop.key,
value: prop.value.toString(),
};
});
}));
}
showLegend(settings: MapboxSettings, roleMap: RoleMap) {
return this.layerExists()
}
addLegend(
legend: LegendControl,
roleMap: RoleMap,
settings: MapboxSettings,
): void
{
const id = this.getId();
const title = roleMap.color.displayName;
const colorStops = this.getColorStops();
const format = roleMap.color.format;
legend.addLegend(id, title, colorStops, format);
}
}
} | the_stack |
import Point from "ol/geom/Point";
import LineString from "ol/geom/LineString";
import Circle from "ol/geom/Circle";
import Polygon, { fromCircle } from "ol/geom/Polygon";
import LinearRing from "ol/geom/LinearRing";
import MultiLineString from "ol/geom/MultiLineString";
import MultiPoint from "ol/geom/MultiPoint";
import MultiPolygon from "ol/geom/MultiPolygon";
import Geometry from "ol/geom/Geometry";
import GeometryCollection from "ol/geom/GeometryCollection";
import Overlay, { Options as OverlayOptions } from "ol/Overlay";
import * as olExtent from "ol/extent";
import * as olProj from "ol/proj";
import Projection, { Options as ProjectionOptions } from "ol/proj/Projection";
import { Options as VectorLayerOptions } from "ol/layer/BaseVector";
import VectorLayer from "ol/layer/Vector";
import VectorSource, { Options as VectorOptions } from "ol/source/Vector";
import Collection from "ol/Collection";
import Feature from "ol/Feature";
import ExtentInteraction, { Options as ExtentOptions } from "ol/interaction/Extent";
import SnapInteraction, { Options as SnapOptions } from "ol/interaction/Snap";
import DrawInteraction, { Options as DrawOptions } from "ol/interaction/Draw";
import TranslateInteraction, { Options as TranslateOptions } from "ol/interaction/Translate";
import ModifyInteraction, { Options as ModifyOptions } from "ol/interaction/Modify";
import SelectInteraction, { Options as SelectOptions } from "ol/interaction/Select";
import GeoJSONFormat, { Options as GeoJSONOptions } from "ol/format/GeoJSON";
import WKTFormat, { Options as WKTOptions } from "ol/format/WKT";
import Style, { Options as StyleOptions } from "ol/style/Style";
import IconStyle, { Options as IconOptions } from "ol/style/Icon";
import RegularShapeStyle, { Options as RegularShapeOptions } from "ol/style/RegularShape";
import TextStyle, { Options as TextOptions } from "ol/style/Text";
import FillStyle, { Options as FillOptions } from "ol/style/Fill";
import StrokeStyle, { Options as StrokeOptions } from "ol/style/Stroke";
import CircleStyle, { Options as CircleOptions } from "ol/style/Circle";
import { Bounds, Coordinate2D } from './common';
import { ProjectionLike } from 'ol/proj';
import { OLVectorLayer, OLVectorLayerOptions } from "./ol-types";
/**
* Creates various OpenLayers types used by the viewer
*
* @export
* @interface IOLFactory
*/
export interface IOLFactory {
/**
*
* @param options
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyle(options?: StyleOptions): Style;
/**
*
* @param options
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyleFill(options?: FillOptions): FillStyle;
/**
*
* @param options
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyleStroke(options?: StrokeOptions): StrokeStyle;
/**
*
* @param options
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyleCircle(options?: CircleOptions): CircleStyle;
/**
* @since 0.12.6
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyleIcon(options?: IconOptions): IconStyle;
/**
* @since 0.12.6
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyleRegularShape(options: RegularShapeOptions): RegularShapeStyle;
/**
* @since 0.12.6
* @deprecated Will be removed in favor of the IVectorFeatureStyle as that better integrates with the external layer manager component
*/
createStyleText(options?: TextOptions): TextStyle;
createFeatureCollection(): Collection<Feature<Geometry>>;
extentContainsXY(extent: Bounds, x: number, y: number): boolean;
extendExtent(extent: Bounds, other: Bounds): Bounds;
createProjection(options: ProjectionOptions): Projection;
transformCoordinateFromLonLat(lonlat: Coordinate2D, proj?: ProjectionLike): Coordinate2D;
transformCoordinate(coordinate: Coordinate2D, source: ProjectionLike, target: ProjectionLike): Coordinate2D;
transformExtent(extent: Bounds, source: ProjectionLike, target: ProjectionLike): Bounds;
createGeomPoint(coordinates: Coordinate2D): Point;
createGeomLineString(coordinates: Coordinate2D[]): LineString;
createGeomCircle(center: Coordinate2D, radius: number | undefined): Circle;
createGeomLinearRing(coordinates: Coordinate2D[]): LinearRing;
createGeomPolygon(coordinates: Coordinate2D[][]): Polygon;
createGeomPolygonFromCircle(circle: Circle): Polygon;
createGeomMultiLineString(coordinates: Coordinate2D[][]): MultiLineString;
createGeomMultiPoint(coordinates: Coordinate2D[]): MultiPoint;
createGeomMultiPolygon(coordinates: Coordinate2D[][][]): MultiPolygon;
createGeomCollection(geometries: Geometry[]): GeometryCollection;
createVectorSource(options?: VectorOptions): VectorSource<Geometry>;
createVectorLayer(options?: OLVectorLayerOptions | undefined): OLVectorLayer;
createOverlay(options: OverlayOptions): Overlay;
createInteractionDraw(options: DrawOptions): DrawInteraction;
/**
*
* @since 0.11
* @param {ModifyOptions} options
* @returns {ModifyInteraction}
* @memberof IOLFactory
*/
createInteractionModify(options: ModifyOptions): ModifyInteraction;
/**
*
* @since 0.11
* @param {SelectOptions} options
* @returns {SelectInteraction}
* @memberof IOLFactory
*/
createInteractionSelect(options: SelectOptions): SelectInteraction;
createInteractionExtent(options: ExtentOptions): ExtentInteraction;
createInteractionSnap(options: SnapOptions): SnapInteraction;
createInteractionTranslate(options: TranslateOptions): TranslateInteraction;
createFeature(geomOrProps?: Geometry | { [key: string]: any }): Feature<Geometry>;
createFormatGeoJSON(options?: GeoJSONOptions | undefined): GeoJSONFormat;
createFormatWKT(options?: WKTOptions | undefined): WKTFormat;
}
/**
* Creates various OpenLayers types used by the viewer
*
* @export
* @class OLFactory
* @implements {IOLFactory}
*/
export class OLFactory implements IOLFactory {
public createStyle(options?: StyleOptions): Style {
return new Style(options);
}
public createStyleFill(options?: FillOptions): FillStyle {
return new FillStyle(options);
}
public createStyleStroke(options?: StrokeOptions): StrokeStyle {
return new StrokeStyle(options);
}
public createStyleCircle(options?: CircleOptions): CircleStyle {
return new CircleStyle(options);
}
public createFeatureCollection(): Collection<Feature<Geometry>> {
return new Collection<Feature<Geometry>>();
}
public extentContainsXY(extent: Bounds, x: number, y: number): boolean {
return olExtent.containsXY(extent, x, y);
}
public extendExtent(extent: Bounds, other: Bounds): Bounds {
return olExtent.extend(extent, other) as Bounds;
}
public createProjection(options: ProjectionOptions): Projection {
return new Projection(options);
}
public transformCoordinateFromLonLat(lonlat: Coordinate2D, proj?: ProjectionLike): Coordinate2D {
return olProj.fromLonLat(lonlat, proj) as Coordinate2D;
}
public transformCoordinate(coordinate: Coordinate2D, source: ProjectionLike, target: ProjectionLike): Coordinate2D {
return olProj.transform(coordinate, source, target) as Coordinate2D;
}
public transformExtent(extent: Bounds, source: ProjectionLike, target: ProjectionLike): Bounds {
return olProj.transformExtent(extent, source, target) as Bounds;
}
public createGeomPoint(coordinates: Coordinate2D): Point {
return new Point(coordinates);
}
public createGeomLineString(coordinates: Coordinate2D[]): LineString {
return new LineString(coordinates);
}
public createGeomCircle(center: Coordinate2D, radius: number | undefined): Circle {
return new Circle(center, radius);
}
public createGeomLinearRing(coordinates: Coordinate2D[]): LinearRing {
return new LinearRing(coordinates);
}
public createGeomPolygon(coordinates: Coordinate2D[][]): Polygon {
return new Polygon(coordinates);
}
public createGeomPolygonFromCircle(circle: Circle): Polygon {
return fromCircle(circle);
}
public createGeomMultiLineString(coordinates: Coordinate2D[][]): MultiLineString {
return new MultiLineString(coordinates);
}
public createGeomMultiPoint(coordinates: Coordinate2D[]): MultiPoint {
return new MultiPoint(coordinates);
}
public createGeomMultiPolygon(coordinates: Coordinate2D[][][]): MultiPolygon {
return new MultiPolygon(coordinates);
}
public createGeomCollection(geometries: Geometry[]): GeometryCollection {
return new GeometryCollection(geometries);
}
public createVectorSource(options?: VectorOptions): VectorSource<Geometry> {
return new VectorSource(options);
}
public createVectorLayer(options?: OLVectorLayerOptions | undefined): OLVectorLayer {
return new VectorLayer(options);
}
public createOverlay(options: OverlayOptions): Overlay {
return new Overlay(options);
}
public createInteractionDraw(options: DrawOptions): DrawInteraction {
return new DrawInteraction(options);
}
public createInteractionExtent(options: ExtentOptions): ExtentInteraction {
return new ExtentInteraction(options);
}
public createInteractionTranslate(options: TranslateOptions): TranslateInteraction {
return new TranslateInteraction(options);
}
public createInteractionSnap(options: SnapOptions): SnapInteraction {
return new SnapInteraction(options);
}
public createInteractionModify(options: ModifyOptions): ModifyInteraction {
return new ModifyInteraction(options);
}
public createInteractionSelect(options: SelectOptions): SelectInteraction {
return new SelectInteraction(options);
}
public createFeature(geomOrProps?: Geometry | { [key: string]: any }): Feature<Geometry> {
return new Feature(geomOrProps);
}
public createFormatGeoJSON(options?: GeoJSONOptions | undefined): GeoJSONFormat {
return new GeoJSONFormat(options);
}
public createFormatWKT(options?: WKTOptions | undefined): WKTFormat {
return new WKTFormat(options);
}
/**
* @since 0.12.6
*/
public createStyleIcon(options?: IconOptions | undefined): IconStyle {
return new IconStyle(options);
}
/**
* @since 0.12.6
*/
public createStyleRegularShape(options: RegularShapeOptions): RegularShapeStyle {
return new RegularShapeStyle(options);
}
/**
* @since 0.12.6
*/
public createStyleText(options?: TextOptions | undefined): TextStyle {
return new TextStyle(options);
}
} | the_stack |
import * as detectIndent from "detect-indent"
import * as types from "vscode-languageserver-types"
import * as Oni from "oni-api"
import * as Log from "oni-core-logging"
import { Event, IEvent } from "oni-types"
import { OniSnippet, OniSnippetPlaceholder } from "./OniSnippet"
import { BufferIndentationInfo, IBuffer } from "./../../Editor/BufferManager"
import { SnippetVariableResolver } from "./SnippetVariableResolver"
export const splitLineAtPosition = (line: string, position: number): [string, string] => {
const prefix = line.substring(0, position)
const post = line.substring(position, line.length)
return [prefix, post]
}
export const getFirstPlaceholder = (
placeholders: OniSnippetPlaceholder[],
): OniSnippetPlaceholder => {
return placeholders.reduce((prev: OniSnippetPlaceholder, curr: OniSnippetPlaceholder) => {
if (!prev || prev.isFinalTabstop) {
return curr
}
if (curr.index < prev.index && !curr.isFinalTabstop) {
return curr
}
return prev
}, null)
}
export const getPlaceholderByIndex = (
placeholders: OniSnippetPlaceholder[],
index: number,
): OniSnippetPlaceholder | null => {
const matchingPlaceholders = placeholders.filter(p => p.index === index)
if (matchingPlaceholders.length === 0) {
return null
}
return matchingPlaceholders[0]
}
export const getFinalPlaceholder = (
placeholders: OniSnippetPlaceholder[],
): OniSnippetPlaceholder | null => {
const matchingPlaceholders = placeholders.filter(p => p.isFinalTabstop)
if (matchingPlaceholders.length === 0) {
return null
}
return matchingPlaceholders[0]
}
export interface IMirrorCursorUpdateEvent {
mode: Oni.Vim.Mode
cursors: types.Range[]
}
export const makeSnippetConsistentWithExistingWhitespace = (
snippet: string,
info: BufferIndentationInfo,
) => {
return snippet.split("\t").join(info.indent)
}
export const makeSnippetIndentationConsistent = (snippet: string, info: BufferIndentationInfo) => {
return snippet
.split("\n")
.map((line, index) => {
if (index === 0) {
return line
} else {
return info.indent + line
}
})
.join("\n")
}
export class SnippetSession {
private _buffer: IBuffer
private _snippet: OniSnippet
private _position: types.Position
private _onCancelEvent: Event<void> = new Event<void>()
private _onCursorMovedEvent: Event<IMirrorCursorUpdateEvent> = new Event<
IMirrorCursorUpdateEvent
>()
// Get state of line where we inserted
private _prefix: string
private _suffix: string
private _currentPlaceholder: OniSnippetPlaceholder = null
private _lastCursorMovedEvent: IMirrorCursorUpdateEvent = {
mode: null,
cursors: [],
}
public get buffer(): IBuffer {
return this._buffer
}
public get onCancel(): IEvent<void> {
return this._onCancelEvent
}
public get onCursorMoved(): IEvent<IMirrorCursorUpdateEvent> {
return this._onCursorMovedEvent
}
public get position(): types.Position {
return this._position
}
public get lines(): string[] {
return this._snippet.getLines()
}
constructor(private _editor: Oni.Editor, private _snippetString: string) {}
public async start(): Promise<void> {
this._buffer = this._editor.activeBuffer as IBuffer
const cursorPosition = await this._buffer.getCursorPosition()
const [currentLine] = await this._buffer.getLines(
cursorPosition.line,
cursorPosition.line + 1,
)
this._position = cursorPosition
const [prefix, suffix] = splitLineAtPosition(currentLine, cursorPosition.character)
const currentIndent = detectIndent(currentLine)
this._prefix = prefix
this._suffix = suffix
const whitespaceSettings = await this._buffer.detectIndentation()
const normalizedSnippet = makeSnippetConsistentWithExistingWhitespace(
this._snippetString,
whitespaceSettings,
)
const indentedSnippet = makeSnippetIndentationConsistent(normalizedSnippet, currentIndent)
this._snippet = new OniSnippet(indentedSnippet, new SnippetVariableResolver(this._buffer))
const snippetLines = this._snippet.getLines()
const lastIndex = snippetLines.length - 1
snippetLines[0] = this._prefix + snippetLines[0]
snippetLines[lastIndex] = snippetLines[lastIndex] + this._suffix
// If there are no placeholders, add an implicit one at the end
if (this._snippet.getPlaceholders().length === 0) {
this._snippet = new OniSnippet(
// tslint:disable-next-line
indentedSnippet + "${0}",
new SnippetVariableResolver(this._buffer),
)
}
await this._buffer.setLines(cursorPosition.line, cursorPosition.line + 1, snippetLines)
const placeholders = this._snippet.getPlaceholders()
if (!placeholders || placeholders.length === 0) {
// If no placeholders, we're done with the session
this._finish()
return
}
await this.nextPlaceholder()
await this.updateCursorPosition()
}
public async nextPlaceholder(): Promise<void> {
const placeholders = this._snippet.getPlaceholders()
if (!this._currentPlaceholder) {
const newPlaceholder = getFirstPlaceholder(placeholders)
this._currentPlaceholder = newPlaceholder
} else {
if (this._currentPlaceholder.isFinalTabstop) {
this._finish()
return
}
const nextPlaceholder = getPlaceholderByIndex(
placeholders,
this._currentPlaceholder.index + 1,
)
this._currentPlaceholder = nextPlaceholder || getFinalPlaceholder(placeholders)
}
await this._highlightPlaceholder(this._currentPlaceholder)
}
public async previousPlaceholder(): Promise<void> {
const placeholders = this._snippet.getPlaceholders()
const nextPlaceholder = getPlaceholderByIndex(
placeholders,
this._currentPlaceholder.index - 1,
)
this._currentPlaceholder = nextPlaceholder || getFirstPlaceholder(placeholders)
await this._highlightPlaceholder(this._currentPlaceholder)
}
public async setPlaceholderValue(index: number, val: string): Promise<void> {
const previousValue = this._snippet.getPlaceholderValue(index)
if (previousValue === val) {
Log.verbose(
"[SnippetSession::setPlaceHolderValue] Skipping because new placeholder value is same as previous",
)
return
}
await this._snippet.setPlaceholder(index, val)
// Update current placeholder
this._currentPlaceholder = getPlaceholderByIndex(this._snippet.getPlaceholders(), index)
await this._updateSnippet()
}
// Update the cursor position relative to all placeholders
public async updateCursorPosition(): Promise<void> {
const pos = await this._buffer.getCursorPosition()
const mode = this._editor.mode as Oni.Vim.Mode
if (
!this._currentPlaceholder ||
pos.line !== this._currentPlaceholder.line + this._position.line
) {
return
}
const boundsForPlaceholder = this._getBoundsForPlaceholder()
const offset = pos.character - boundsForPlaceholder.start
const allPlaceholdersAtIndex = this._snippet
.getPlaceholders()
.filter(
f =>
f.index === this._currentPlaceholder.index &&
!(
f.line === this._currentPlaceholder.line &&
f.character === this._currentPlaceholder.character
),
)
const cursorPositions: types.Range[] = allPlaceholdersAtIndex.map(p => {
if (mode === "visual") {
const bounds = this._getBoundsForPlaceholder(p)
return types.Range.create(
bounds.line,
bounds.start,
bounds.line,
bounds.start + bounds.length,
)
} else {
const bounds = this._getBoundsForPlaceholder(p)
return types.Range.create(
bounds.line,
bounds.start + offset,
bounds.line,
bounds.start + offset,
)
}
})
this._lastCursorMovedEvent = {
mode,
cursors: cursorPositions,
}
this._onCursorMovedEvent.dispatch(this._lastCursorMovedEvent)
}
public getLatestCursors(): IMirrorCursorUpdateEvent {
return this._lastCursorMovedEvent
}
// Helper method to query the value of the current placeholder,
// propagate that to any other placeholders, and update the snippet
public async synchronizeUpdatedPlaceholders(): Promise<void> {
// Get current cursor position
const cursorPosition = await this._buffer.getCursorPosition()
if (!this._currentPlaceholder) {
return
}
const bounds = this._getBoundsForPlaceholder()
if (cursorPosition.line !== bounds.line) {
Log.info(
"[SnippetSession::synchronizeUpdatedPlaceholder] Cursor outside snippet, cancelling snippet session",
)
this._onCancelEvent.dispatch()
return
}
// Check substring of placeholder start / placeholder finish
const [currentLine] = await this._buffer.getLines(bounds.line, bounds.line + 1)
const startPosition = bounds.start
const endPosition = currentLine.length - bounds.distanceFromEnd
if (
cursorPosition.character < startPosition ||
cursorPosition.character > endPosition + 2
) {
return
}
// Set placeholder value
const newPlaceholderValue = currentLine.substring(startPosition, endPosition)
await this.setPlaceholderValue(bounds.index, newPlaceholderValue)
}
private _finish(): void {
this._onCancelEvent.dispatch()
}
private _getBoundsForPlaceholder(
currentPlaceholder: OniSnippetPlaceholder = this._currentPlaceholder,
): {
index: number
line: number
start: number
length: number
distanceFromEnd: number
} {
const currentSnippetLines = this._snippet.getLines()
const start =
currentPlaceholder.line === 0
? this._prefix.length + currentPlaceholder.character
: currentPlaceholder.character
const length = currentPlaceholder.value.length
const distanceFromEnd =
currentSnippetLines[currentPlaceholder.line].length -
(currentPlaceholder.character + length)
const line = currentPlaceholder.line + this._position.line
return { index: currentPlaceholder.index, line, start, length, distanceFromEnd }
}
private async _updateSnippet(): Promise<void> {
const snippetLines = this._snippet.getLines()
const lastIndex = snippetLines.length - 1
snippetLines[0] = this._prefix + snippetLines[0]
snippetLines[lastIndex] = snippetLines[lastIndex] + this._suffix
await this._buffer.setLines(
this._position.line,
this._position.line + snippetLines.length,
snippetLines,
)
}
private async _highlightPlaceholder(currentPlaceholder: OniSnippetPlaceholder): Promise<void> {
if (!currentPlaceholder) {
return
}
const adjustedLine = currentPlaceholder.line + this._position.line
const adjustedCharacter =
currentPlaceholder.line === 0
? this._position.character + currentPlaceholder.character
: currentPlaceholder.character
const placeHolderLength = currentPlaceholder.value.length
if (placeHolderLength === 0) {
await (this._editor as any).clearSelection()
await this._editor.activeBuffer.setCursorPosition(adjustedLine, adjustedCharacter)
} else {
await this._editor.setSelection(
types.Range.create(
adjustedLine,
adjustedCharacter,
adjustedLine,
adjustedCharacter + placeHolderLength - 1,
),
)
}
}
} | the_stack |
import * as _ from 'lodash';
import {Component, ElementRef, Injector, Input, OnInit, ViewChild} from '@angular/core';
import {AbstractComponent} from '@common/component/abstract.component';
import {GridComponent} from '@common/component/grid/grid.component';
import {Header, SlickGridHeader} from '@common/component/grid/grid.header';
import {GridOption} from '@common/component/grid/grid.option';
import {Datasource, Field, FieldFormatType, LogicalType} from '@domain/datasource/datasource';
import {MetadataSource} from '@domain/meta-data-management/metadata-source';
import {Metadata} from '@domain/meta-data-management/metadata';
import {Type} from '../../../shared/datasource-metadata/domain/type';
import {ConstantService} from '../../../shared/datasource-metadata/service/constant.service';
import {TimezoneService} from '../../../data-storage/service/timezone.service';
import {MetadataService} from '../../../meta-data-management/metadata/service/metadata.service';
@Component({
selector: 'explore-metadata-sample-data',
templateUrl: './metadata-sample-data.component.html',
})
export class MetadataSampleDataComponent extends AbstractComponent implements OnInit {
@Input() readonly metadata;
// filters
roleTypeFilterList = this.constantService.getRoleTypeFilters();
logicalTypeFilterList = this.constantService.getTypeFilters();
selectedRoleTypeFilter = this.constantService.getRoleTypeFilterFirst();
selectedLogicalTypeFilter = this.constantService.getTypeFiltersFirst();
searchTextKeyword: string;
// grid data
fieldList;
fieldRowList: { [key: string]: string }[];
gridDataLimit: number = 50;
isExistCreatedField: boolean;
@ViewChild(GridComponent)
private readonly _gridComponent: GridComponent;
constructor(private constantService: ConstantService,
private timezoneService: TimezoneService,
private metadataService: MetadataService,
protected element: ElementRef,
protected injector: Injector) {
super(element, injector);
}
ngOnInit() {
this._setMetadataSampleData();
}
isDatasourceTypeMetadata(): boolean {
return !_.isNil(this.metadata.source) && Metadata.isSourceTypeIsEngine(this.metadata.sourceType);
}
isLinkedSourceType(): boolean {
return MetadataSource.isNotEmptySource(this.metadata.source) && Datasource.isLinkedDatasource(this.metadata.source.source as Datasource);
}
/**
* Extend grid header
* @param args
*/
extendGridHeader(args: any): void {
// #2172 name -> physicalName, logicalName -> name
$(`<div class="slick-data">${_.find(this.fieldList, {physicalName: args.column.id})['name'] || ''}</div>`).appendTo(args.node);
}
private _isCreatedField(field): boolean {
return !_.isNil(field.additionals) && field.additionals.derived === true;
}
private _setMetadataSampleData(): void {
this.loadingShow();
this.metadataService.getMetadataSampleData(this.metadata.id, this.gridDataLimit)
.then((result: { size: number, data }) => {
// if exist data
if (!_.isNil(result.data)) {
// set isExistCreatedField flag
if (result.data.columnDescriptions.length > 0) {
this.isExistCreatedField = result.data.columnDescriptions.some(col => !_.isNil(col.additionals) && col.additionals.derived === true);
}
// set field list
this._setFieldList(result.data.columnNames, result.data.columnDescriptions);
// set field data list
this._setFieldRowList(result.data.columnNames, result.data.rows);
// create grid
this._updateGrid();
}
this.loadingHide();
})
.catch(error => {
this.fieldList = [];
this.commonExceptionHandler(error);
});
}
private _setFieldList(colNames: string[], colDescs): void {
this.fieldList = colDescs.map((col, index) => {
return {
...col,
colName: colNames[index]
};
});
}
private _setFieldRowList(colNames: string[], rows) {
this.fieldRowList = rows.reduce((result, row) => {
result.push(row.values.reduce((mappingRow, data, index) => {
// #2172 if null or undefined, init empty string
mappingRow[colNames[index]] = data || '';
return mappingRow;
}, {}));
return result;
}, []);
}
/**
* Get grid header name
* @param {Field} field
* @param {string} headerName
* @return {string}
* @private
*/
private _getGridHeaderName(field, headerName: string): string {
return field.type === LogicalType.TIMESTAMP && (this.timezoneService.isEnableTimezoneInDateFormat(field.format) || field.format && field.format.type === FieldFormatType.UNIX_TIME)
? `<span style="padding-left:20px;"><em class="${this.getFieldTypeIconClass(this._getConvertedType(field.type, field.physicalType).toString())}"></em>${headerName}<div class="slick-column-det" title="${this._getTimezoneLabel(field.format)}">${this._getTimezoneLabel(field.format)}</div></span>`
: `<span style="padding-left:20px;"><em class="${this.getFieldTypeIconClass(this._getConvertedType(field.type, field.physicalType).toString())}"></em>${headerName}</span>`;
}
private _getConvertedType(type: Type.Logical, logicalType: Type.Logical): Type.Logical {
if (type === Type.Logical.LONG) {
return Type.Logical.INTEGER;
} else if (type === Type.Logical.STRUCT) {
return logicalType;
} else {
return type;
}
}
private _getFilteredFieldList(fieldList) {
// if is datasource type metadata, enable role filter
if (this.isDatasourceTypeMetadata()) {
return this._getRoleFilteredFieldList(this._getTypeFilteredFieldList(fieldList));
} else { // disable role filter
return this._getTypeFilteredFieldList(fieldList);
}
}
private _getRoleFilteredFieldList(fieldList) {
// if selected ALL filter
if (this.selectedRoleTypeFilter.value === Type.Role.ALL) {
return fieldList;
} else if (this.selectedRoleTypeFilter.value === Type.Role.DIMENSION) { // if selected DIMENSION filter
return fieldList.filter(field => field.additionals.role === Type.Role.DIMENSION || field.additionals.role === Type.Role.TIMESTAMP);
} else { // if selected MEASURE filter
return fieldList.filter(field => field.additionals.role === Type.Role.MEASURE);
}
}
private _getTypeFilteredFieldList(fieldList) {
if (this.selectedLogicalTypeFilter.value === Type.Logical.ALL) {
return fieldList;
} else {
return fieldList.filter(field => this._getConvertedType(field.type, field.physicalType) === this.selectedLogicalTypeFilter.value);
}
}
/**
* Get timezone label
* @param {FieldFormat} format
* @return {string}
* @private
*/
private _getTimezoneLabel(format): string {
if (format.type === FieldFormatType.UNIX_TIME) {
return 'Unix time';
} else {
return this.timezoneService.getConvertedTimezoneUTCLabel(this.timezoneService.getTimezoneObject(format).utc);
}
}
/**
* 그리드 header 리스트 생성
* @param {Field[]} fields
* @returns {header[]}
* @private
*/
private _getGridHeader(fields): Header[] {
// if exist created field list
if (this.isExistCreatedField) {
// Style
const defaultStyle: string = 'line-height:30px;';
const nullStyle: string = 'color:#b6b9c1;';
const noPreviewGuideMessage: string = this.translateService.instant('msg.dp.ui.no.preview');
// #2172 name -> physicalName, logicalName -> name
return fields.map((field) => {
const headerName: string = field.headerKey || field.physicalName;
return new SlickGridHeader()
.Id(headerName)
.Name(this._getGridHeaderName(field, headerName))
.Field(headerName)
.Behavior('select')
.Selectable(false)
.CssClass('cell-selection')
.Width(10 * (headerName.length) + 20)
.MinWidth(100)
.CannotTriggerInsert(true)
.Resizable(true)
.Unselectable(true)
.Sortable(true)
.Formatter((_row, _cell, value) => {
// if derived expression type or LINK geo type
if (this._isCreatedField(field) && (field.type === LogicalType.STRING || this.isLinkedSourceType())) {
return '<div style="' + defaultStyle + nullStyle + '">' + noPreviewGuideMessage + '</div>';
} else {
return value;
}
})
.build();
});
} else {
return fields.map((field: Field) => {
const headerName: string = field.headerKey || field.physicalName;
return new SlickGridHeader()
.Id(headerName)
.Name(this._getGridHeaderName(field, headerName))
.Field(headerName)
.Behavior('select')
.Selectable(false)
.CssClass('cell-selection')
.Width(10 * (headerName.length) + 20)
.MinWidth(100)
.CannotTriggerInsert(true)
.Resizable(true)
.Unselectable(true)
.Sortable(true)
.build();
});
}
}
/**
* 그리드 업데이트
* @private
*/
private _updateGrid(): void {
// 헤더정보 생성
const headers: Header[] = this._getGridHeader(this._getFilteredFieldList(this.fieldList));
// rows
let rows: any[] = this.fieldRowList;
// row and headers가 있을 경우에만 그리드 생성
if (rows && 0 < headers.length) {
if (rows.length > 0 && !rows[0].hasOwnProperty('id')) {
rows = rows.map((row: any, idx: number) => {
row.id = idx;
return row;
});
}
// if grid data limit bigger than rows length
if (this.gridDataLimit > rows.length) {
// set grid data limit
this.gridDataLimit = rows.length;
}
// dom 이 모두 로드되었을때 작동
this.changeDetect.detectChanges();
// 그리드 생성
this._gridComponent.create(headers, rows, new GridOption()
.SyncColumnCellResize(true)
.MultiColumnSort(true)
.RowHeight(32)
.ShowHeaderRow(true)
.HeaderRowHeight(32)
.ExplicitInitialization(true)
.build());
// search
this._gridComponent.search(this.searchTextKeyword || '');
// ExplicitInitialization 을 true 로 줬기 떄문에 init해줘야 한다.
!_.isNil(this.metadata) && this._gridComponent.grid.init();
} else {
this._gridComponent.destroy();
}
}
} | the_stack |
import {
Mark,
Channels,
ChannelHandler,
MarkEncoding,
MarkEncodings,
MarkEncodingKey,
Facet,
Gradient,
MarkType,
StrokeCap,
StrokeJoin,
Orientation,
Interpolation,
HorizontalAlignment,
VerticalAlignment,
VerticalTextAlignment,
SymbolType,
FontWeight,
TextDirection,
ItemIdGenerator,
Metadata,
} from '@chart-parts/interfaces'
import { Subject, Subscription } from 'rxjs'
import { MarkSpec } from '../spec/MarkSpec'
import { SceneNodeBuilder } from './SceneNodeBuilder'
/**
* A builder component for mark specifications
* @category Builder
*/
export class MarkBuilder {
public readonly onChange = new Subject()
public readonly spec: MarkSpec
private _child?: SceneNodeBuilder
private _childSubscription?: Subscription
public constructor(public readonly type: MarkType) {
this.spec = new MarkSpec(type)
}
public table(table: string | undefined): MarkBuilder {
this.spec.table = table
this.onChange.next('mark table changed')
return this
}
public role(role: string | undefined): MarkBuilder {
this.spec.role = role
this.onChange.next('mark role changed')
return this
}
public name(name: string | undefined): MarkBuilder {
this.spec.name = name
this.onChange.next('mark name changed')
return this
}
public idGenerator(generator: ItemIdGenerator): MarkBuilder {
this.spec.idGenerator = generator
this.onChange.next('mark idGenerator changed')
return this
}
public handle(
name: string,
handler: ChannelHandler<any> | undefined,
): MarkBuilder
public handle(channels: Channels): MarkBuilder
public handle(
name: string | Channels,
handler?: ChannelHandler<any>,
): MarkBuilder {
if (typeof name === 'string') {
this.spec.applyHandler(name, handler)
} else {
Object.entries(name as Channels).forEach(([nameVal, handlerVal]) =>
this.spec.applyHandler(nameVal, handlerVal),
)
}
this.onChange.next('mark handlers changed')
return this
}
// #region Mark Encoding
public encode(
key: MarkEncodingKey.x,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.x2,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.xc,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.width,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.y,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.y2,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.yc,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.height,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.opacity,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.fill,
encoding: undefined | MarkEncoding<string | Gradient>,
): MarkBuilder
public encode(
key: MarkEncodingKey.fillOpacity,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.stroke,
encoding: undefined | MarkEncoding<string | Gradient>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeOpacity,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeWidth,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeCap,
encoding: undefined | MarkEncoding<StrokeCap>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeDash,
encoding: undefined | MarkEncoding<[number, number]>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeDashOffset,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeJoin,
encoding: undefined | MarkEncoding<StrokeJoin>,
): MarkBuilder
public encode(
key: MarkEncodingKey.strokeMiterLimit,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.cursor,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.href,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.tooltip,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.zIndex,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.startAngle,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.endAngle,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.padAngle,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.innerRadius,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.outerRadius,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.cornerRadius,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.orient,
encoding: undefined | MarkEncoding<Orientation>,
): MarkBuilder
public encode(
key: MarkEncodingKey.interpolate,
encoding: undefined | MarkEncoding<Interpolation>,
): MarkBuilder
public encode(
key: MarkEncodingKey.tension,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.defined,
encoding: undefined | MarkEncoding<boolean>,
): MarkBuilder
public encode(
key: MarkEncodingKey.clip,
encoding: undefined | MarkEncoding<boolean>,
): MarkBuilder
public encode(
key: MarkEncodingKey.url,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.aspect,
encoding: undefined | MarkEncoding<boolean>,
): MarkBuilder
public encode(
key: MarkEncodingKey.align,
encoding: undefined | MarkEncoding<HorizontalAlignment>,
): MarkBuilder
public encode(
key: MarkEncodingKey.baseline,
encoding:
| undefined
| MarkEncoding<VerticalAlignment | VerticalTextAlignment>,
): MarkBuilder
public encode(
key: MarkEncodingKey.path,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.size,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.shape,
encoding: undefined | MarkEncoding<SymbolType | string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.angle,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.dir,
encoding: undefined | MarkEncoding<TextDirection>,
): MarkBuilder
public encode(
key: MarkEncodingKey.dx,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.dy,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.ellipsis,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.font,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.fontSize,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.fontWeight,
encoding: undefined | MarkEncoding<FontWeight>,
): MarkBuilder
public encode(
key: MarkEncodingKey.fontVariant,
encoding: undefined | MarkEncoding<string | number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.fontStyle,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.limit,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.radius,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.text,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.theta,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.ariaTitle,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.ariaDescription,
encoding: undefined | MarkEncoding<string>,
): MarkBuilder
public encode(
key: MarkEncodingKey.tabIndex,
encoding: undefined | MarkEncoding<number>,
): MarkBuilder
public encode(
key: MarkEncodingKey.metadata,
encoding: undefined | MarkEncoding<Metadata>,
): MarkBuilder
public encode(key: MarkEncodingKey, encoding: MarkEncoding<any>): MarkBuilder
public encode(encodings: MarkEncodings): MarkBuilder
// #endregion
// Polymorphic function definition
public encode(
first: MarkEncodingKey | MarkEncodings,
encoding?: MarkEncoding<any>,
): MarkBuilder {
if (typeof first === 'string') {
// Handle encode(key, encoding) invocations
this.spec.applyEncoding(first as string, encoding)
} else {
// Handle encode(map) invocations
Object.entries(first as MarkEncodings).forEach(
([name, entryEncoding]) => {
this.spec.applyEncoding(name, entryEncoding)
},
)
}
this.onChange.next('mark encoders changed')
return this
}
public facet(facet: Facet | undefined): MarkBuilder {
if (facet !== undefined && this.type !== MarkType.Group) {
throw new Error('faceting can only be applied to "group" type marks')
}
this.spec.facet = facet
this.onChange.next('mark facet changed')
return this
}
/**
* Pushes a new scene node onto the graph
*/
public child(callback: (b: SceneNodeBuilder) => void): MarkBuilder {
if (this.spec.child) {
console.warn(`MarkBuilder may only have one child at a time`)
}
// in case this was set, clear out any existing subscriptinos
if (this._childSubscription) {
this._childSubscription.unsubscribe()
}
this._child = new SceneNodeBuilder()
this.spec.child = this._child.spec
callback(this._child)
this._childSubscription = this._child.onChange.subscribe(cause =>
this.onChange.next(cause),
)
this.onChange.next('mark child changed')
return this
}
public build(): Mark {
if (!this.spec.type) {
throw new Error('mark type must be set')
}
return this.spec
}
} | the_stack |
import * as assert from "power-assert";
import {
ingressTemplate,
upsertIngress,
} from "../../../../lib/pack/k8s/kubernetes/ingress";
import {
KubernetesApplication,
KubernetesResourceRequest,
KubernetesSdm,
} from "../../../../lib/pack/k8s/kubernetes/request";
describe("core/pack/k8s/kubernetes/ingress", () => {
describe("ingressTemplate", () => {
it("should create a wildcard ingress spec", async () => {
const r: KubernetesApplication & KubernetesSdm = {
workspaceId: "KAT3BU5H",
ns: "hounds-of-love",
name: "cloudbusting",
image: "gcr.io/kate-bush/hounds-of-love/cloudbusting:5.5.10",
port: 5510,
path: "/bush/kate/hounds-of-love/cloudbusting",
sdmFulfiller: "EMI",
};
const i = await ingressTemplate(r);
const e = {
apiVersion: "networking.k8s.io/v1beta1",
kind: "Ingress",
metadata: {
name: "cloudbusting",
namespace: "hounds-of-love",
labels: {
"app.kubernetes.io/managed-by": "EMI",
"app.kubernetes.io/name": "cloudbusting",
"app.kubernetes.io/part-of": "cloudbusting",
"atomist.com/workspaceId": "KAT3BU5H",
},
},
spec: {
rules: [
{
http: {
paths: [
{
backend: {
serviceName: "cloudbusting",
servicePort: "http",
},
path: "/bush/kate/hounds-of-love/cloudbusting",
},
],
},
},
],
},
};
assert.deepStrictEqual(i, e);
});
it("should merge in provided ingress spec", async () => {
const r: KubernetesApplication & KubernetesSdm = {
workspaceId: "KAT3BU5H",
ns: "hounds-of-love",
name: "cloudbusting",
image: "gcr.io/kate-bush/hounds-of-love/cloudbusting:5.5.10",
port: 5510,
path: "/bush/kate/hounds-of-love/cloudbusting",
sdmFulfiller: "EMI",
ingressSpec: {
metadata: {
annotations: {
"kubernetes.io/ingress.class": "nginx",
"nginx.ingress.kubernetes.io/client-body-buffer-size": "512k",
"nginx.ingress.kubernetes.io/limit-connections": "100",
"nginx.ingress.kubernetes.io/limit-rps": "25",
"nginx.ingress.kubernetes.io/rewrite-target": "/cb",
},
},
spec: {
rules: [{ host: "emi.com" }],
tls: [{ hosts: ["emi.com"], secretName: "emi-com" }],
},
} as any,
};
const s = await ingressTemplate(r);
const e = {
apiVersion: "networking.k8s.io/v1beta1",
kind: "Ingress",
metadata: {
annotations: {
"kubernetes.io/ingress.class": "nginx",
"nginx.ingress.kubernetes.io/rewrite-target": "/cb",
"nginx.ingress.kubernetes.io/client-body-buffer-size": "512k",
"nginx.ingress.kubernetes.io/limit-connections": "100",
"nginx.ingress.kubernetes.io/limit-rps": "25",
},
labels: {
"app.kubernetes.io/managed-by": "EMI",
"app.kubernetes.io/name": "cloudbusting",
"app.kubernetes.io/part-of": "cloudbusting",
"atomist.com/workspaceId": "KAT3BU5H",
},
name: "cloudbusting",
namespace: "hounds-of-love",
},
spec: {
rules: [
{
host: "emi.com",
http: {
paths: [
{
backend: {
serviceName: "cloudbusting",
servicePort: "http",
},
path: "/bush/kate/hounds-of-love/cloudbusting",
},
],
},
},
],
tls: [
{
hosts: ["emi.com"],
secretName: "emi-com",
},
],
},
};
assert.deepStrictEqual(s, e);
});
it("should correct API version and kind in provided spec", async () => {
const r: KubernetesApplication & KubernetesSdm = {
workspaceId: "KAT3BU5H",
ns: "hounds-of-love",
name: "cloudbusting",
image: "gcr.io/kate-bush/hounds-of-love/cloudbusting:5.5.10",
port: 5510,
path: "/bush/kate/hounds-of-love/cloudbusting",
sdmFulfiller: "EMI",
ingressSpec: {
apiVersion: "v1",
kind: "Egress",
} as any,
};
const s = await ingressTemplate(r);
const e = {
apiVersion: "networking.k8s.io/v1beta1",
kind: "Ingress",
metadata: {
labels: {
"app.kubernetes.io/managed-by": r.sdmFulfiller,
"app.kubernetes.io/name": r.name,
"app.kubernetes.io/part-of": r.name,
"atomist.com/workspaceId": r.workspaceId,
},
name: "cloudbusting",
namespace: "hounds-of-love",
},
spec: {
rules: [
{
http: {
paths: [
{
backend: {
serviceName: r.name,
servicePort: "http",
},
path: r.path,
},
],
},
},
],
},
};
assert.deepStrictEqual(s, e);
});
it("should allow overriding name but not namespace", async () => {
const r: KubernetesApplication & KubernetesSdm = {
workspaceId: "KAT3BU5H",
ns: "hounds-of-love",
name: "cloudbusting",
image: "gcr.io/kate-bush/hounds-of-love/cloudbusting:5.5.10",
port: 5510,
path: "/bush/kate/hounds-of-love/cloudbusting",
sdmFulfiller: "EMI",
ingressSpec: {
metadata: {
name: "wuthering-heights",
namespace: "the-kick-inside",
},
} as any,
};
const s = await ingressTemplate(r);
const e = {
apiVersion: "networking.k8s.io/v1beta1",
kind: "Ingress",
metadata: {
labels: {
"app.kubernetes.io/managed-by": r.sdmFulfiller,
"app.kubernetes.io/name": r.name,
"app.kubernetes.io/part-of": r.name,
"atomist.com/workspaceId": r.workspaceId,
},
name: "wuthering-heights",
namespace: "hounds-of-love",
},
spec: {
rules: [
{
http: {
paths: [
{
backend: {
serviceName: r.name,
servicePort: "http",
},
path: r.path,
},
],
},
},
],
},
};
assert.deepStrictEqual(s, e);
});
});
describe("upsertIngress", () => {
it("should not do anything if port is not defined", async () => {
const a: KubernetesResourceRequest = {
name: "brotherhood",
ns: "new-order",
path: "blue-monday",
} as any;
const i = await upsertIngress(a);
assert(i === undefined);
});
it("should not do anything if path is not defined", async () => {
const a: KubernetesResourceRequest = {
name: "brotherhood",
ns: "new-order",
port: 1986,
} as any;
const i = await upsertIngress(a);
assert(i === undefined);
});
});
}); | the_stack |
import { map, mapValues, repeat, lowerCase, camelCase, reduce, maxBy } from "lodash-es";
import { i18n } from "@/i18n";
import { ProtoWeapon, Zoom, WeaponMode } from "./weapon.i";
import Axios from "axios";
import base64arraybuffer from "base64-arraybuffer";
// build from riven-mirror-data
import data from "../../../data/dist/weapons.data";
import proto from "../../../data/src/proto/weapon.proto";
import { strSimilarity } from "../util";
import { RivenDatabase, KitgunChamberData, ZawStrikeData } from ".";
export enum MainTag {
Rifle,
Shotgun,
Secondary,
Kitgun,
Melee,
Zaw,
"Arch-Gun",
"Arch-Melee",
Amp,
}
export class WeaponTag {
private _set: Set<string>;
mainTag: MainTag;
constructor(init?: string[]) {
this._set = new Set(init || []);
this.mainTag = MainTag[init.find(v => v != "Primary" && v != "Robotic Weapon")];
}
has(...tags: string[]) {
return tags.every(v => {
if (v === "Gun") return ![MainTag.Melee, MainTag.Zaw, MainTag.Amp, MainTag["Arch-Melee"]].includes(this.mainTag);
return this._set.has(v);
});
}
toArray() {
return Array.from(this._set);
}
}
export interface CoreWeaponMode extends Omit<WeaponMode, "damage"> {
/** 本地化名称 */
locName: string;
/** 伤害 */
damage: [string, number][];
}
export class Weapon {
// 裂罅基础名称
base?: string;
// base
name: string;
/** MOD中可能出现的词缀 */
tags: WeaponTag;
/** 次要tag Tenno/G/C/I/Prime 等 */
traits?: string[];
/** 段位 */
mastery?: number;
/** 极性 */
polarities?: string;
/** 裂罅倾向 */
disposition: number = 0;
/** 主Tag Rifle/Melee 等 */
mod: MainTag;
get modText() {
return MainTag[this.mod];
}
// gun
reload?: number;
magazine?: number;
maxAmmo?: number;
reloadStyle?: number; // Normal=0 Regenerate=1 ByRound=2
// deep extra
sniperComboMin?: number;
sniperComboReset?: number;
/** 缩放 */
zoom?: Zoom[]; // "3x (+20% Critical Chance)"
/** 最大开镜等级 */
get maxZoomLevel() {
return (this.zoom && this.zoom.length) || 0;
}
// melee
stancePolarity?: string;
comboDur?: number;
followThrough?: number;
meleeRange?: number;
slamAttack?: number;
slamRadialDmg?: number;
slamRadius?: number;
heavyAttack?: number;
windUp?: number;
heavySlamAttack?: number;
heavyRadialDmg?: number;
heavySlamRadius?: number;
slideAttack?: number;
// attack
modes: CoreWeaponMode[];
constructor(data: ProtoWeapon, base?: ProtoWeapon) {
// 修复过高精度
const fixBuf = <T>(v: T) => {
if (typeof v === "number") return +v.toFixed(3);
if (Array.isArray(v)) return map(v, fixBuf);
if (typeof v === "object") return mapValues(v as any, fixBuf);
return v;
};
if (data) {
// 国服切换回老版本
const { variants, modes, tags, ...weapon } = data;
Object.assign(this, fixBuf(weapon));
if (tags) {
this.tags = new WeaponTag(tags);
this.mod = this.tags.mainTag;
}
if (modes) {
const defaultMode = modes[0];
// 根据默认补全属性
this.modes = modes.map(({ damage, ...mode }) => {
const newMode = {
damage: map(damage, (vv, vn) => [vn, fixBuf(vv)] as [string, number]),
...mode,
} as CoreWeaponMode;
if (mode.name || mode.type) {
const locKey = `weaponmode.${camelCase(mode.name || mode.type || "default")}`;
if (i18n.te(locKey)) {
newMode.locName = i18n.t(locKey);
} else {
console.log("missing", locKey);
newMode.locName = mode.name;
}
} else newMode.locName = i18n.t("weaponmode.default");
if (newMode.chargeTime) newMode.fireRate = (1 / newMode.chargeTime) * 60;
if (!newMode.fireRate) {
if (newMode.chargeTime) newMode.fireRate = 1 / newMode.chargeTime;
else newMode.fireRate = defaultMode.fireRate || 60;
}
if (typeof newMode.critChance === "undefined") newMode.critChance = defaultMode.critChance || 0;
if (typeof newMode.critMul === "undefined") newMode.critMul = defaultMode.critMul || 2;
if (typeof newMode.procChance === "undefined") newMode.procChance = defaultMode.procChance || 0;
return newMode;
});
}
}
if (base) {
this.base = base.name;
}
// this.disposition = RivenDatabase.getRatio(this.name) || 0;
}
/** proto名 */
get baseName() {
return this.base || this.name;
}
// 辅助函数
/** URL */
get url() {
return this.name.replace(/ /g, "_").replace(" (Atmosphere)", "");
}
get baseurl() {
return this.baseName.replace(/ /g, "_").replace(" (Atmosphere)", "");
}
/** WM URL */
get wmurl() {
const setlist = ["Lato Vandal", "Braton Vandal"];
if (this.name.includes(" Prime") || setlist.includes(this.name)) return this.name.toLowerCase().replace(/ /g, "_") + "_set";
const slist = ["Prisma ", "Secura ", "Vaykor ", "Sancti ", "Synoid ", "Telos ", "Mara ", " Vandal"];
if (slist.some(v => this.name.includes(v))) return this.name.toLowerCase().replace(/ /g, "_");
return "";
}
/** WM RIEVN URL */
get wmrivenurl() {
const name = lowerCase(this.baseName.replace(/&/g, "and"));
const tpl = `https://warframe.market/auctions/search?type=riven&weapon_url_name=${name}&polarity=any&sort_by=price_desc`;
return tpl;
}
/** i18n的key */
get id() {
return `messages.${camelCase(this.name)}`;
}
get baseId() {
return `messages.${camelCase(this.baseName)}`;
}
get locName() {
return i18n.te(this.id) ? i18n.t(this.id) : this.name;
}
/** 是否是陆地用 */
get isAtmosphere() {
return this.name.endsWith(" (Atmosphere)");
}
get displayName() {
if (i18n.te(this.id)) return i18n.t(this.id);
else {
console.warn(`missing i18n: ${this.id}:"${this.name}"`);
return this.name;
}
}
/** 武器倾向星数 */
get star() {
return [0.1, 0.7, 0.875, 1.125, 1.305, Infinity].findIndex(v => this.disposition < v);
}
get starText() {
return repeat("●", this.star) + repeat("○", 5 - this.star);
}
/** 是否是Gun */
get isGun() {
return this.mod !== MainTag.Melee && this.mod !== MainTag.Zaw && this.mod !== MainTag["Arch-Melee"];
}
/** 是否是Melee */
get isMelee() {
return this.mod === MainTag.Melee || this.mod === MainTag.Zaw;
}
/** 是否是Pistol */
get isPistol() {
return this.mod === MainTag.Secondary || this.mod === MainTag.Kitgun;
}
/** 是否是Rifle */
get isRifle() {
return this.mod === MainTag.Rifle;
}
/** 是否是Sniper */
get isSniper() {
return this.isRifle && this.tags.has("Sniper");
}
/** 是否是Zaw */
get isZaw() {
return this.mod === MainTag.Zaw;
}
/** 是否是Kitgun */
get isKitgun() {
return this.mod === MainTag.Kitgun;
}
/** 是否是Amp */
get isAmp() {
return this.mod === MainTag.Amp;
}
/** 是否是Virtual */
get isVirtual() {
return this.tags.has("Virtual");
}
/** 是否是Exalted */
get isExalted() {
return this.tags.has("Exalted");
}
/** 获取武器对应紫卡属性范围 */
getPropBaseValue(prop: string) {
return RivenDatabase.getPropBaseValue(this.disposition, this.modText, prop);
}
/** 获取全部变种 */
get variants() {
return WeaponDatabase.getWeaponsByBase(this.base || this.name);
}
/** 获取攻击模式 */
getMode(mode: number | string = 0) {
return new WeaponBuildMode(this, mode);
}
/** 默认攻击模式 */
get defaultMode() {
return this.getMode();
}
// melee
/** 滑砍伤害 */
get slideDmg() {
return this.defaultMode.panelDamage * this.slideAttack;
}
}
/**
* 包含某一种射击模式中全部数据的类
*/
export class WeaponBuildMode implements CoreWeaponMode {
weapon: Weapon;
mode: number;
constructor(weapon: Weapon, mode: number | string = 0) {
this.weapon = weapon;
if (typeof mode === "number") this.mode = mode;
else {
this.mode = this.weapon.modes.findIndex(v => v.type === mode || v.name === mode);
}
}
get url() {
if (this.mode) return this.weapon.url + `_(${this.weapon.modes[this.mode].name})`;
return this.weapon.url;
}
//### weapon 数据获取
get reload() {
return this.weapon.reload;
}
get magazine() {
return this.weapon.magazine;
}
get maxAmmo() {
return this.weapon.maxAmmo;
}
get reloadStyle() {
return this.weapon.reloadStyle;
}
get comboDur() {
return this.weapon.comboDur;
}
get followThrough() {
return this.weapon.followThrough;
}
get meleeRange() {
return this.weapon.meleeRange;
}
get slamAttack() {
return this.weapon.slamAttack;
}
get slamRadialDmg() {
return this.weapon.slamRadialDmg;
}
get slamRadius() {
return this.weapon.slamRadius;
}
get heavyAttack() {
return this.weapon.heavyAttack;
}
get windUp() {
return this.weapon.windUp;
}
get heavySlamAttack() {
return this.weapon.heavySlamAttack;
}
get heavyRadialDmg() {
return this.weapon.heavyRadialDmg;
}
get heavySlamRadius() {
return this.weapon.heavySlamRadius;
}
get slideAttack() {
return this.weapon.slideAttack;
}
//### mode 数据获取
/** 类型 default/secondary/charge/chargedThrow/throw/area/secondaryArea */
get type() {
return this.weapon.modes[this.mode].type || "default";
}
/** 名字 */
get name() {
return this.weapon.modes[this.mode].name;
}
/** 本地化名字 */
get locName() {
return this.weapon.modes[this.mode].locName;
}
/** 伤害 {Heat:100} */
get damage() {
return this.weapon.modes[this.mode].damage;
}
// 隐性必填
/** 射速 */
get fireRate() {
return this.weapon.modes[this.mode].fireRate;
}
/** 暴击 */
get critChance() {
return this.weapon.modes[this.mode].critChance;
}
/** 暴伤 */
get critMul() {
return this.weapon.modes[this.mode].critMul;
}
/** 触发 */
get procChance() {
return this.weapon.modes[this.mode].procChance;
}
/** 精准 xx (100 when aimed) */
get accuracy() {
return this.weapon.modes[this.mode].accuracy;
}
/** 自带穿透 */
get punchThrough() {
return this.weapon.modes[this.mode].punchThrough;
}
/** 弹片数 */
get pellets() {
return this.weapon.modes[this.mode].pellets || 1;
}
/** 溅射半径 */
get radius() {
return this.weapon.modes[this.mode].radius;
}
/** 射程 */
get range() {
return this.weapon.modes[this.mode].range;
}
/** 子弹消耗 */
get ammoCost() {
return this.weapon.modes[this.mode].ammoCost;
}
/** 蓄力时间 */
get chargeTime() {
return this.weapon.modes[this.mode].chargeTime;
}
/** 扳机 Semi-Auto/Held/Auto/Charge*/
get trigger() {
return this.weapon.modes[this.mode].trigger;
}
/** 点射数量 */
get burstCount() {
return this.weapon.modes[this.mode].burstCount;
}
/** 投射物速度 */
get prjSpeed() {
return this.weapon.modes[this.mode].prjSpeed;
}
/** 启动子弹数 */
get spool() {
return this.weapon.modes[this.mode].spool;
}
/** 静音 */
get silent() {
return this.weapon.modes[this.mode].silent;
}
/** 衰减 [起始,中止,最大衰减] */
get falloff() {
return this.weapon.modes[this.mode].falloff;
}
/** 面板伤害 */
get panelDamage() {
return reduce(this.damage, (a, b) => a + b[1], 0);
}
}
/** split variants format to normal format */
export class WeaponDatabase {
static weapons: Weapon[];
static weaponMap = new Map<string, Weapon>();
static protos: Weapon[];
static variantsMap = new Map<string, Weapon[]>();
static async loadDataOnline() {
// 缓存
const cache = localStorage.getItem("weapons.data");
let bin: ArrayBuffer;
if (cache) {
bin = base64arraybuffer.decode(cache);
}
try {
const rst = await Axios.get(data || "https://api.riven.im/data/weapons.data", { responseType: "arraybuffer" });
bin = rst.data;
localStorage.setItem("weapons.data", base64arraybuffer.encode(bin));
} catch {}
const msg = proto.Weapons.decode(new Uint8Array(bin));
const decoded = proto.Weapons.toObject(msg);
this.load(decoded.weapons as ProtoWeapon[]);
}
static load(weapons: ProtoWeapon[]) {
const extraDispositionTable = [
// kitguns
...KitgunChamberData.map(v => [v.name, "Kitgun", v.disposition[0]]),
// zaw
...ZawStrikeData.map(v => [v.name, "Zaw", v.disposition]),
// Amp
["Amp", "Amp", 0],
] as [string, string, number][];
let rst: Weapon[] = [];
this.protos = [];
weapons.forEach(root => {
const { variants, ...weapon } = root;
const p = new Weapon(weapon);
rst.push(p);
this.protos.push(p);
if (variants) {
const variantsWeapons = variants.map(subweapon => {
const v = new Weapon(subweapon, weapon);
rst.push(v);
return v;
});
this.variantsMap.set(p.name, [p, ...variantsWeapons]);
} else {
this.variantsMap.set(p.name, [p]);
}
});
extraDispositionTable.forEach(weapon => {
const [name, tag, disposition] = weapon;
const p = new Weapon({ name, tags: [tag], disposition });
rst.push(p);
this.protos.push(p);
this.variantsMap.set(p.name, [p]);
});
// 按倾向性排序
this.protos.sort((a, b) => b.disposition - a.disposition);
rst.forEach(weapon => {
this.weaponMap.set(weapon.name, weapon);
});
return (this.weapons = rst);
}
/**
* 查询是否有这个武器
* @param name 武器通用名称
*/
static hasWeapon(name: string) {
return this.weaponMap.has(name);
}
/**
* 获取武器
* @param name 武器通用名称
*/
static getWeaponByName(name: string) {
return this.weaponMap.get(name);
}
/**
* 模糊识别武器名称
* @param name 模糊匹配的名称
*/
static findMostSimRivenWeapon(name: string) {
name = name.trim();
if (this.hasWeapon(name)) return this.getWeaponByName(name);
let weaponFinded = maxBy(this.weapons, v => Math.max(strSimilarity(name, v.locName), strSimilarity(name, v.name)));
return weaponFinded;
}
/**
* 通过武器具体名称获取武器实例
* @param name 武器具体名称
*/
static getWeaponsByTags(tags: (string | number)[]) {
return WeaponDatabase.weapons.filter(v => tags.every(tag => v.tags.has(typeof tag === "number" ? MainTag[tag] : tag)));
}
/**
* 通过武器标签(OR)获取武器实例
* @param name 武器具体名称
*/
static getProtosByMultiTags(tags: (string | number)[]) {
return WeaponDatabase.protos.filter(v => tags.some(tag => v.tags.has(typeof tag === "number" ? MainTag[tag] : tag)));
}
/**
* 通过武器标签(AND)获取武器实例
* @param name 武器具体名称
*/
static getProtosByTags(tags: (string | number)[]) {
return WeaponDatabase.protos.filter(v => tags.every(tag => v.tags.has(typeof tag === "number" ? MainTag[tag] : tag)));
}
/**
* 通过武器通用名称获取武器实例
* @param base 武器通用名称
*/
static getWeaponsByBase(base: string) {
return this.variantsMap.get(base) || [];
}
}
window["WeaponDatabase"] = WeaponDatabase; | the_stack |
import { isIterable } from "@esfx/internal-guards";
import { deprecateProperty } from "@esfx/internal-deprecate";
export interface ReadonlyCollection<T> extends Iterable<T> {
/**
* Gets the number of elements in the collection.
*/
readonly [ReadonlyCollection.size]: number;
/**
* Tests whether an element is present in the collection.
*/
[ReadonlyCollection.has](value: T): boolean;
}
export namespace ReadonlyCollection {
// #region ReadonlyCollection<T>
/**
* A well-known symbol used to define the `ReadonlyCollection#[ReadonlyCollection.size]` property.
*/
export const size = Symbol.for("@esfx/collection-core!ReadonlyCollection.size");
/**
* A well-known symbol used to define the `ReadonlyCollection#[ReadonlyCollection.has]` method.
*/
export const has = Symbol.for("@esfx/collection-core!ReadonlyCollection.has");
// #endregion ReadonlyCollection<T>
/**
* Tests whether a value supports the minimal representation of a `ReadonlyCollection`.
* @deprecated Use `ReadonlyCollection.hasInstance` instead.
*/
export function isReadonlyCollection<T>(value: Iterable<T>): value is ReadonlyCollection<T>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyCollection`.
* @deprecated Use `ReadonlyCollection.hasInstance` instead.
*/
export function isReadonlyCollection(value: any): value is ReadonlyCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyCollection`.
* @deprecated Use `ReadonlyCollection.hasInstance` instead.
*/
export function isReadonlyCollection(value: any): value is ReadonlyCollection<unknown> {
return isIterable(value)
&& ReadonlyCollection.size in value
&& ReadonlyCollection.has in value;
}
export const name = "ReadonlyCollection";
/**
* Tests whether a value supports the minimal representation of a `ReadonlyCollection`.
*/
export function hasInstance<T>(value: Iterable<T>): value is ReadonlyCollection<T>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyCollection`.
*/
export function hasInstance(value: any): value is ReadonlyCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyCollection`.
*/
export function hasInstance(value: any): value is ReadonlyCollection<unknown> {
return isIterable(value)
&& ReadonlyCollection.size in value
&& ReadonlyCollection.has in value;
}
}
export interface Collection<T> extends ReadonlyCollection<T> {
/**
* Adds an element to the collection.
*/
[Collection.add](value: T): void;
/**
* Deletes an element from the collection.
*/
[Collection.delete](value: T): boolean;
/**
* Clears the collection.
*/
[Collection.clear](): void;
}
export namespace Collection {
// #region ReadonlyCollection<T>
export import size = ReadonlyCollection.size;
export import has = ReadonlyCollection.has;
export import isReadonlyCollection = ReadonlyCollection.isReadonlyCollection;
// #endregion ReadonlyCollection<T>
// #region Collection<T>
/**
* A well-known symbol used to define the `Collection#[Collection.add]` method.
*/
export const add = Symbol.for("@esfx/collection-core!Collection.add");
Collection.delete = Symbol.for("@esfx/collection-core!Collection.delete") as typeof Collection.delete;
/**
* A well-known symbol used to define the `Collection#[Collection.clear]` method.
*/
export const clear = Symbol.for("@esfx/collection-core!Collection.clear");
// #endregion Collection<T>
/**
* Tests whether a value supports the minimal representation of a `Collection`.
* @deprecated Use `Collection.hasInstance` instead.
*/
export function isCollection<T>(value: Iterable<T>): value is Collection<T>;
/**
* Tests whether a value supports the minimal representation of a `Collection`.
* @deprecated Use `Collection.hasInstance` instead.
*/
export function isCollection(value: any): value is Collection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `Collection`.
* @deprecated Use `Collection.hasInstance` instead.
*/
export function isCollection(value: any): value is Collection<unknown> {
return Collection.hasInstance(value);
}
export const name = "Collection";
/**
* Tests whether a value supports the minimal representation of a `Collection`.
*/
export function hasInstance<T>(value: Iterable<T>): value is Collection<T>;
/**
* Tests whether a value supports the minimal representation of a `Collection`.
*/
export function hasInstance(value: any): value is Collection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `Collection`.
*/
export function hasInstance(value: any): value is Collection<unknown> {
return ReadonlyCollection.hasInstance(value)
&& Collection.add in value
&& Collection.delete in value
&& Collection.clear in value;
}
}
export declare namespace Collection {
/**
* A well-known symbol used to define the `Collection#[Collection.delete]` method.
*/
const _delete: unique symbol;
export { _delete as delete };
}
export interface ReadonlyIndexedCollection<T> extends ReadonlyCollection<T> {
/**
* Gets the index for a value in the collection, or `-1` if the value was not found.
*/
[ReadonlyIndexedCollection.indexOf](value: T, fromIndex?: number): number;
/**
* Gets the value at the specified index in the collection, or `undefined` if the index was outside of the bounds of the collection.
*/
[ReadonlyIndexedCollection.getAt](index: number): T | undefined;
}
export namespace ReadonlyIndexedCollection {
// #region ReadonlyCollection<T>
export import size = ReadonlyCollection.size;
export import has = ReadonlyCollection.has;
export import isReadonlyCollection = ReadonlyCollection.isReadonlyCollection;
// #endregion ReadonlyCollection<T>
// #region ReadonlyIndexedCollection<T>
/**
* A well-known symbol used to define the `ReadonlyIndexedCollection#[ReadonlyIndexedCollection.indexOf]` method.
*/
export const indexOf = Symbol.for("@esfx/collection-core!ReadonlyIndexedCollection.indexOf");
/**
* A well-known symbol used to define the `ReadonlyIndexedCollection#[ReadonlyIndexedCollection.getAt]` method.
*/
export const getAt = Symbol.for("@esfx/collection-core!ReadonlyIndexedCollection.getAt");
// #endregion ReadonlyIndexedCollection<T>
/**
* Tests whether a value supports the minimal representation of a `ReadonlyIndexedCollection`.
* @deprecated Use `ReadonlyIndexedCollection.hasInstance` instead.
*/
export function isReadonlyIndexedCollection<T>(value: Iterable<T>): value is ReadonlyIndexedCollection<T>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyIndexedCollection`.
* @deprecated Use `ReadonlyIndexedCollection.hasInstance` instead.
*/
export function isReadonlyIndexedCollection(value: unknown): value is ReadonlyIndexedCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyIndexedCollection`.
* @deprecated Use `ReadonlyIndexedCollection.hasInstance` instead.
*/
export function isReadonlyIndexedCollection(value: unknown): value is ReadonlyIndexedCollection<unknown> {
return ReadonlyIndexedCollection.hasInstance(value);
}
export const name = "ReadonlyIndexedCollection";
/**
* Tests whether a value supports the minimal representation of a `ReadonlyIndexedCollection`.
*/
export function hasInstance<T>(value: Iterable<T>): value is ReadonlyIndexedCollection<T>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyIndexedCollection`.
*/
export function hasInstance(value: unknown): value is ReadonlyIndexedCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyIndexedCollection`.
*/
export function hasInstance(value: unknown): value is ReadonlyIndexedCollection<unknown> {
return ReadonlyCollection.hasInstance(value)
&& ReadonlyIndexedCollection.indexOf in value
&& ReadonlyIndexedCollection.getAt in value;
}
}
export interface FixedSizeIndexedCollection<T> extends ReadonlyIndexedCollection<T> {
/**
* Sets a value at the specified index in the collection.
* @returns `true` if the value was set at the provided index, otherwise `false`.
*/
[FixedSizeIndexedCollection.setAt](index: number, value: T): boolean;
}
export namespace FixedSizeIndexedCollection {
// #region ReadonlyCollection<T>
export import size = ReadonlyCollection.size;
export import has = ReadonlyCollection.has;
export import isReadonlyCollection = ReadonlyCollection.isReadonlyCollection;
// #endregion ReadonlyCollection<T>
// #region ReadonlyIndexedCollection<T>
export import indexOf = ReadonlyIndexedCollection.indexOf;
export import getAt = ReadonlyIndexedCollection.getAt;
export import isReadonlyIndexedCollection = ReadonlyIndexedCollection.isReadonlyIndexedCollection;
// #endregion ReadonlyIndexedCollection<T>
// #region FixedSizeIndexedCollection<T>
/**
* A well-known symbol used to define the `FixedSizeIndexedCollection#[FixedSizeIndexedCollection.setAt]` method.
*/
export const setAt = Symbol.for("@esfx/collection-core!FixedSizeIndexedCollection.setAt");
// #endregion FixedSizeIndexedCollection<T>
/**
* Tests whether a value supports the minimal representation of a `FixedSizeIndexedCollection`.
* @deprecated Use `FixedSizeIndexedCollection.hasInstance` instead.
*/
export function isFixedSizeIndexedCollection<T>(value: Iterable<T>): value is FixedSizeIndexedCollection<T>;
/**
* Tests whether a value supports the minimal representation of a `FixedSizeIndexedCollection`.
* @deprecated Use `FixedSizeIndexedCollection.hasInstance` instead.
*/
export function isFixedSizeIndexedCollection(value: unknown): value is FixedSizeIndexedCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `FixedSizeIndexedCollection`.
* @deprecated Use `FixedSizeIndexedCollection.hasInstance` instead.
*/
export function isFixedSizeIndexedCollection(value: unknown): value is FixedSizeIndexedCollection<unknown> {
return FixedSizeIndexedCollection.hasInstance(value);
}
export const name = "FixedSizeIndexedCollection";
/**
* Tests whether a value supports the minimal representation of a `FixedSizeIndexedCollection`.
*/
export function hasInstance<T>(value: Iterable<T>): value is FixedSizeIndexedCollection<T>;
/**
* Tests whether a value supports the minimal representation of a `FixedSizeIndexedCollection`.
*/
export function hasInstance(value: unknown): value is FixedSizeIndexedCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of a `FixedSizeIndexedCollection`.
*/
export function hasInstance(value: unknown): value is FixedSizeIndexedCollection<unknown> {
return ReadonlyIndexedCollection.hasInstance(value)
&& FixedSizeIndexedCollection.setAt in value;
}
}
export interface IndexedCollection<T> extends FixedSizeIndexedCollection<T>, Collection<T> {
/**
* Inserts a value at the specified index in the collection, shifting any following elements to the right one position.
*/
[IndexedCollection.insertAt](index: number, value: T): void;
/**
* Removes the value at the specified index in the collection, shifting any following elements to the left one position.
*/
[IndexedCollection.removeAt](index: number): void;
}
export namespace IndexedCollection {
// #region ReadonlyCollection<T>
export import size = ReadonlyCollection.size;
export import has = ReadonlyCollection.has;
export import isReadonlyCollection = ReadonlyCollection.isReadonlyCollection;
// #endregion ReadonlyCollection<T>
// #region ReadonlyIndexedCollection<T>
export import indexOf = ReadonlyIndexedCollection.indexOf;
export import getAt = ReadonlyIndexedCollection.getAt;
export import isReadonlyIndexedCollection = ReadonlyIndexedCollection.isReadonlyIndexedCollection;
// #endregion ReadonlyIndexedCollection<T>
// #region FixedSizeIndexedCollection<T>
export import setAt = FixedSizeIndexedCollection.setAt;
export import isFixedSizeIndexedCollection = FixedSizeIndexedCollection.isFixedSizeIndexedCollection;
// #endregion FixedSizeIndexedCollection<T>
// #region Collection<T>
export import add = Collection.add;
IndexedCollection.delete = Collection.delete;
export import clear = Collection.clear;
export import isCollection = Collection.isCollection;
// #endregion Collection<T>
// #region IndexedCollection<T>
/**
* A well-known symbol used to define the `IndexedCollection#[IndexedCollection.insertAt]` method.
*/
export const insertAt = Symbol.for("@esfx/collection-core!IndexedCollection.insertAt");
/**
* A well-known symbol used to define the `IndexedCollection#[IndexedCollection.removeAt]` method.
*/
export const removeAt = Symbol.for("@esfx/collection-core!IndexedCollection.removeAt");
// #endregion IndexedCollection<T>
/**
* Tests whether a value supports the minimal representation of an `IndexedCollection`.
* @deprecated Use `IndexedCollection.hasInstance` instead.
*/
export function isIndexedCollection<T>(value: Iterable<T>): value is IndexedCollection<T>;
/**
* Tests whether a value supports the minimal representation of an `IndexedCollection`.
* @deprecated Use `IndexedCollection.hasInstance` instead.
*/
export function isIndexedCollection(value: unknown): value is IndexedCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of an `IndexedCollection`.
* @deprecated Use `IndexedCollection.hasInstance` instead.
*/
export function isIndexedCollection(value: unknown): value is IndexedCollection<unknown> {
return IndexedCollection.hasInstance(value);
}
export const name = "IndexedCollection";
/**
* Tests whether a value supports the minimal representation of an `IndexedCollection`.
*/
export function hasInstance<T>(value: Iterable<T>): value is IndexedCollection<T>;
/**
* Tests whether a value supports the minimal representation of an `IndexedCollection`.
*/
export function hasInstance(value: unknown): value is IndexedCollection<unknown>;
/**
* Tests whether a value supports the minimal representation of an `IndexedCollection`.
*/
export function hasInstance(value: unknown): value is IndexedCollection<unknown> {
return FixedSizeIndexedCollection.hasInstance(value)
&& IndexedCollection.insertAt in value
&& IndexedCollection.removeAt in value;
}
}
export declare namespace IndexedCollection {
const _delete: typeof Collection.delete;
export { _delete as delete };
}
export interface ReadonlyKeyedCollection<K, V> extends Iterable<[K, V]> {
/**
* Gets the number of elements in the collection.
*/
readonly [ReadonlyKeyedCollection.size]: number;
/**
* Tests whether a key is present in the collection.
*/
[ReadonlyKeyedCollection.has](key: K): boolean;
/**
* Gets the value in the collection associated with the provided key, if it exists.
*/
[ReadonlyKeyedCollection.get](key: K): V | undefined;
/**
* Gets an `IterableIterator` for the keys present in the collection.
*/
[ReadonlyKeyedCollection.keys](): IterableIterator<K>;
/**
* Gets an `IterableIterator` for the values present in the collection.
*/
[ReadonlyKeyedCollection.values](): IterableIterator<V>;
}
export namespace ReadonlyKeyedCollection {
// #region ReadonlyKeyedCollection<K, V>
/**
* A well-known symbol used to define the `ReadonlyKeyedCollection#[ReadonlyKeyedCollection.size]` property.
*/
export const size = Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.size");
/**
* A well-known symbol used to define the `ReadonlyKeyedCollection#[ReadonlyKeyedCollection.has]` method.
*/
export const has = Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.has");
/**
* A well-known symbol used to define the `ReadonlyKeyedCollection#[ReadonlyKeyedCollection.get]` method.
*/
export const get = Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.get");
/**
* A well-known symbol used to define the `ReadonlyKeyedCollection#[ReadonlyKeyedCollection.keys]` method.
*/
export const keys = Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.keys");
/**
* A well-known symbol used to define the `ReadonlyKeyedCollection#[ReadonlyKeyedCollection.values]` method.
*/
export const values = Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.values");
// #endregion ReadonlyKeyedCollection<K, V>
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedCollection`.
* @deprecated Use `ReadonlyKeyedCollection.hasInstance` instead.
*/
export function isReadonlyKeyedCollection<K, V>(value: Iterable<[K, V]>): value is ReadonlyKeyedCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedCollection`.
* @deprecated Use `ReadonlyKeyedCollection.hasInstance` instead.
*/
export function isReadonlyKeyedCollection(value: unknown): value is ReadonlyKeyedCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedCollection`.
* @deprecated Use `ReadonlyKeyedCollection.hasInstance` instead.
*/
export function isReadonlyKeyedCollection(value: unknown): value is ReadonlyKeyedCollection<unknown, unknown> {
return ReadonlyKeyedCollection.hasInstance(value);
}
export const name = "ReadonlyKeyedCollection";
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedCollection`.
*/
export function hasInstance<K, V>(value: Iterable<[K, V]>): value is ReadonlyKeyedCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedCollection`.
*/
export function hasInstance(value: unknown): value is ReadonlyKeyedCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedCollection`.
*/
export function hasInstance(value: unknown): value is ReadonlyKeyedCollection<unknown, unknown> {
return isIterable(value)
&& ReadonlyKeyedCollection.size in value
&& ReadonlyKeyedCollection.has in value
&& ReadonlyKeyedCollection.get in value
&& ReadonlyKeyedCollection.keys in value
&& ReadonlyKeyedCollection.values in value;
}
}
export interface KeyedCollection<K, V> extends ReadonlyKeyedCollection<K, V> {
/**
* Sets a value in the collection for the provided key.
*/
[KeyedCollection.set](key: K, value: V): void;
/**
* Deletes a key and its associated value from the collection.
* @returns `true` if the key was found and removed; otherwise, `false`.
*/
[KeyedCollection.delete](key: K): boolean;
/**
* Clears the collection.
*/
[KeyedCollection.clear](): void;
}
export namespace KeyedCollection {
// #region ReadonlyKeyedCollection<K, V>
export import size = ReadonlyKeyedCollection.size;
export import has = ReadonlyKeyedCollection.has;
export import get = ReadonlyKeyedCollection.get;
export import keys = ReadonlyKeyedCollection.keys;
export import values = ReadonlyKeyedCollection.values;
export import isReadonlyKeyedCollection = ReadonlyKeyedCollection.isReadonlyKeyedCollection;
// #endregion ReadonlyKeyedCollection<K, V>
// #region KeyedCollection<K, V>
/**
* A well-known symbol used to define the `KeyedCollection#[KeyedCollection.set]` method.
*/
export const set = Symbol.for("@esfx/collection-core!KeyedCollection.set");
KeyedCollection.delete = Symbol.for("@esfx/collection-core!KeyedCollection.delete") as typeof KeyedCollection.delete;
/**
* A well-known symbol used to define the `KeyedCollection#[KeyedCollection.clear]` method.
*/
export const clear = Symbol.for("@esfx/collection-core!KeyedCollection.clear");
// #endregion KeyedCollection<K, V>
/**
* Tests whether a value supports the minimal representation of a `KeyedCollection`.
* @deprecated Use `KeyedCollection.hasInstance` instead.
*/
export function isKeyedCollection<K, V>(value: Iterable<[K, V]>): value is KeyedCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `KeyedCollection`.
* @deprecated Use `KeyedCollection.hasInstance` instead.
*/
export function isKeyedCollection(value: unknown): value is KeyedCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `KeyedCollection`.
* @deprecated Use `KeyedCollection.hasInstance` instead.
*/
export function isKeyedCollection(value: unknown): value is KeyedCollection<unknown, unknown> {
return KeyedCollection.hasInstance(value);
}
export const name = "KeyedCollection";
/**
* Tests whether a value supports the minimal representation of a `KeyedCollection`.
*/
export function hasInstance<K, V>(value: Iterable<[K, V]>): value is KeyedCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `KeyedCollection`.
*/
export function hasInstance(value: unknown): value is KeyedCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `KeyedCollection`.
*/
export function hasInstance(value: unknown): value is KeyedCollection<unknown, unknown> {
return ReadonlyKeyedCollection.hasInstance(value)
&& KeyedCollection.set in value
&& KeyedCollection.delete in value
&& KeyedCollection.clear in value;
}
}
export declare namespace KeyedCollection {
/**
* A well-known symbol used to define the `KeyedCollection#[KeyedCollection.delete]` method.
*/
const _delete: unique symbol;
export { _delete as delete };
}
export interface ReadonlyKeyedMultiCollection<K, V> extends Iterable<[K, V]> {
/**
* Gets the number of elements in the collection.
*/
readonly [ReadonlyKeyedMultiCollection.size]: number;
/**
* Tests whether a key is present in the collection.
*/
[ReadonlyKeyedMultiCollection.has](key: K): boolean;
/**
* Tests whether a key and value is present in the collection.
*/
[ReadonlyKeyedMultiCollection.hasValue](key: K, value: V): boolean;
/**
* Gets the value in the collection associated with the provided key, if it exists.
*/
[ReadonlyKeyedMultiCollection.get](key: K): Iterable<V> | undefined;
/**
* Gets an `IterableIterator` for the keys present in the collection.
*/
[ReadonlyKeyedMultiCollection.keys](): IterableIterator<K>;
/**
* Gets an `IterableIterator` for the values present in the collection.
*/
[ReadonlyKeyedMultiCollection.values](): IterableIterator<V>;
}
export namespace ReadonlyKeyedMultiCollection {
// #region ReadonlyKeyedMultiCollection<K, V>
/**
* A well-known symbol used to define the `ReadonlyKeyedMultiCollection#[ReadonlyKeyedMultiCollection.size]` property.
*/
export const size = Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.size");
/**
* A well-known symbol used to define the `ReadonlyKeyedMultiCollection#[ReadonlyKeyedMultiCollection.has]` method.
*/
export const has = Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.has");
/**
* A well-known symbol used to define the `ReadonlyKeyedMultiCollection#[ReadonlyKeyedMultiCollection.hasValue]` method.
*/
export const hasValue = Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.hasValue");
/**
* A well-known symbol used to define the `ReadonlyKeyedMultiCollection#[ReadonlyKeyedMultiCollection.get]` method.
*/
export const get = Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.get");
/**
* A well-known symbol used to define the `ReadonlyKeyedMultiCollection#[ReadonlyKeyedMultiCollection.keys]` method.
*/
export const keys = Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.keys");
/**
* A well-known symbol used to define the `ReadonlyKeyedMultiCollection#[ReadonlyKeyedMultiCollection.values]` method.
*/
export const values = Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.values");
// #endregion ReadonlyKeyedMultiCollection<K, V>
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedMultiCollection`.
* @deprecated Use `ReadonlyKeyedMultiCollection.hasInstance` instead.
*/
export function isReadonlyKeyedMultiCollection<K, V>(value: Iterable<[K, V]>): value is ReadonlyKeyedMultiCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedMultiCollection`.
* @deprecated Use `ReadonlyKeyedMultiCollection.hasInstance` instead.
*/
export function isReadonlyKeyedMultiCollection(value: unknown): value is ReadonlyKeyedMultiCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedMultiCollection`.
* @deprecated Use `ReadonlyKeyedMultiCollection.hasInstance` instead.
*/
export function isReadonlyKeyedMultiCollection(value: unknown): value is ReadonlyKeyedMultiCollection<unknown, unknown> {
return ReadonlyKeyedMultiCollection.hasInstance(value);
}
export const name = "ReadonlyKeyedMultiCollection";
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedMultiCollection`.
*/
export function hasInstance<K, V>(value: Iterable<[K, V]>): value is ReadonlyKeyedMultiCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedMultiCollection`.
*/
export function hasInstance(value: unknown): value is ReadonlyKeyedMultiCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `ReadonlyKeyedMultiCollection`.
*/
export function hasInstance(value: unknown): value is ReadonlyKeyedMultiCollection<unknown, unknown> {
return isIterable(value)
&& ReadonlyKeyedMultiCollection.size in value
&& ReadonlyKeyedMultiCollection.has in value
&& ReadonlyKeyedMultiCollection.hasValue in value
&& ReadonlyKeyedMultiCollection.get in value
&& ReadonlyKeyedMultiCollection.keys in value
&& ReadonlyKeyedMultiCollection.values in value;
}
}
export interface KeyedMultiCollection<K, V> extends ReadonlyKeyedMultiCollection<K, V> {
/**
* Adds a value to the collection for the provided key.
*/
[KeyedMultiCollection.add](key: K, value: V): void;
/**
* Deletes a key and its associated values from the collection.
* @returns The number of values removed when the key was deleted.
*/
[KeyedMultiCollection.delete](key: K): number;
/**
* Deletes a key and its associated value from the collection.
* @returns `true` if the key and value were found and removed; otherwise, `false`.
*/
[KeyedMultiCollection.deleteValue](key: K, value: V): boolean;
/**
* Clears the collection.
*/
[KeyedMultiCollection.clear](): void;
}
export namespace KeyedMultiCollection {
// #region ReadonlyKeyedMultiCollection<K, V>
export import size = ReadonlyKeyedMultiCollection.size;
export import has = ReadonlyKeyedMultiCollection.has;
export import hasValue = ReadonlyKeyedMultiCollection.hasValue;
export import get = ReadonlyKeyedMultiCollection.get;
export import keys = ReadonlyKeyedMultiCollection.keys;
export import values = ReadonlyKeyedMultiCollection.values;
export import isReadonlyKeyedMultiCollection = ReadonlyKeyedMultiCollection.isReadonlyKeyedMultiCollection;
// #endregion ReadonlyKeyedMultiCollection<K, V>
// #region KeyedMultiCollection<K, V>
/**
* A well-known symbol used to define the `KeyedMultiCollection#[KeyedMultiCollection.add]` method.
*/
export const add = Symbol.for("@esfx/collection-core!KeyedMultiCollection.add");
KeyedMultiCollection.delete = Symbol.for("@esfx/collection-core!KeyedMultiCollection.delete") as typeof KeyedMultiCollection.delete;
/**
* A well-known symbol used to define the `KeyedMultiCollection#[KeyedMultiCollection.deleteValue]` method.
*/
export const deleteValue = Symbol.for("@esfx/collection-core!KeyedMultiCollection.deleteValue");
/**
* A well-known symbol used to define the `KeyedMultiCollection#[KeyedMultiCollection.clear]` method.
*/
export const clear = Symbol.for("@esfx/collection-core!KeyedMultiCollection.clear");
// #endregion KeyedMultiCollection<K, V>
/**
* Tests whether a value supports the minimal representation of a `KeyedMultiCollection`.
* @deprecated Use `KeyedMultiCollection.hasInstance` instead.
*/
export function isKeyedMultiCollection<K, V>(value: Iterable<[K, V]>): value is KeyedMultiCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `KeyedMultiCollection`.
* @deprecated Use `KeyedMultiCollection.hasInstance` instead.
*/
export function isKeyedMultiCollection(value: unknown): value is KeyedMultiCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `KeyedMultiCollection`.
* @deprecated Use `KeyedMultiCollection.hasInstance` instead.
*/
export function isKeyedMultiCollection(value: unknown): value is KeyedMultiCollection<unknown, unknown> {
return KeyedMultiCollection.hasInstance(value);
}
export const name = "KeyedMultiCollection";
/**
* Tests whether a value supports the minimal representation of a `KeyedMultiCollection`.
*/
export function hasInstance<K, V>(value: Iterable<[K, V]>): value is KeyedMultiCollection<K, V>;
/**
* Tests whether a value supports the minimal representation of a `KeyedMultiCollection`.
*/
export function hasInstance(value: unknown): value is KeyedMultiCollection<unknown, unknown>;
/**
* Tests whether a value supports the minimal representation of a `KeyedMultiCollection`.
*/
export function hasInstance(value: unknown): value is KeyedMultiCollection<unknown, unknown> {
return ReadonlyKeyedMultiCollection.hasInstance(value)
&& KeyedMultiCollection.add in value
&& KeyedMultiCollection.delete in value
&& KeyedMultiCollection.deleteValue in value
&& KeyedMultiCollection.clear in value;
}
}
export declare namespace KeyedMultiCollection {
/**
* A well-known symbol used to define the `KeyedMultiCollection#[KeyedMultiCollection.delete]` method.
*/
const _delete: unique symbol;
export { _delete as delete };
}
deprecateProperty(ReadonlyCollection, "isReadonlyCollection", "Use 'ReadonlyCollection.hasInstance' instead.");
deprecateProperty(Collection, "isReadonlyCollection", "Use 'ReadonlyCollection.hasInstance' instead.");
deprecateProperty(Collection, "isCollection", "Use 'Collection.hasInstance' instead.");
deprecateProperty(ReadonlyIndexedCollection, "isReadonlyCollection", "Use 'ReadonlyCollection.hasInstance' instead.");
deprecateProperty(ReadonlyIndexedCollection, "isReadonlyIndexedCollection", "Use 'ReadonlyIndexedCollection.hasInstance' instead.");
deprecateProperty(FixedSizeIndexedCollection, "isReadonlyCollection", "Use 'ReadonlyCollection.hasInstance' instead.");
deprecateProperty(FixedSizeIndexedCollection, "isReadonlyIndexedCollection", "Use 'ReadonlyIndexedCollection.hasInstance' instead.");
deprecateProperty(FixedSizeIndexedCollection, "isFixedSizeIndexedCollection", "Use 'FixedSizeIndexedCollection.hasInstance' instead.");
deprecateProperty(IndexedCollection, "isReadonlyCollection", "Use 'ReadonlyCollection.hasInstance' instead.");
deprecateProperty(IndexedCollection, "isReadonlyIndexedCollection", "Use 'ReadonlyIndexedCollection.hasInstance' instead.");
deprecateProperty(IndexedCollection, "isFixedSizeIndexedCollection", "Use 'FixedSizeIndexedCollection.hasInstance' instead.");
deprecateProperty(IndexedCollection, "isCollection", "Use 'Collection.hasInstance' instead.");
deprecateProperty(IndexedCollection, "isIndexedCollection", "Use 'IndexedCollection.hasInstance' instead.");
deprecateProperty(ReadonlyKeyedCollection, "isReadonlyKeyedCollection", "Use 'ReadonlyKeyedCollection.hasInstance' instead.");
deprecateProperty(KeyedCollection, "isReadonlyKeyedCollection", "Use 'ReadonlyKeyedCollection.hasInstance' instead.");
deprecateProperty(KeyedCollection, "isKeyedCollection", "Use 'KeyedCollection.hasInstance' instead.");
deprecateProperty(ReadonlyKeyedMultiCollection, "isReadonlyKeyedMultiCollection", "Use 'ReadonlyKeyedMultiCollection.hasInstance' instead.");
deprecateProperty(KeyedMultiCollection, "isReadonlyKeyedMultiCollection", "Use 'ReadonlyKeyedMultiCollection.hasInstance' instead.");
deprecateProperty(KeyedMultiCollection, "isKeyedMultiCollection", "Use 'KeyedMultiCollection.hasInstance' instead."); | the_stack |
import { RuntimeContext } from '../../mol-task';
import { NumberArray } from '../type-helpers';
import { _hufTree } from './huffman';
import { U, revCodes, makeCodes } from './util';
function DeflateContext(data: Uint8Array, out: Uint8Array, opos: number, lvl: number) {
const { lits, strt, prev } = U;
return {
data,
out,
opt: Opts[lvl],
i: 0,
pos: opos << 3,
cvrd: 0,
dlen: data.length,
li: 0,
lc: 0,
bs: 0,
ebits: 0,
c: 0,
nc: 0,
lits,
strt,
prev
};
}
type DeflateContext = ReturnType<typeof DeflateContext>
function deflateChunk(ctx: DeflateContext, count: number) {
const { data, dlen, out, opt } = ctx;
let { i, pos, cvrd, li, lc, bs, ebits, c, nc } = ctx;
const { lits, strt, prev } = U;
const end = Math.min(i + count, dlen);
for (; i < end; i++) {
c = nc;
if (i + 1 < dlen - 2) {
nc = _hash(data, i + 1);
const ii = ((i + 1) & 0x7fff);
prev[ii] = strt[nc];
strt[nc] = ii;
}
if (cvrd <= i) {
if ((li > 14000 || lc > 26697) && (dlen - i) > 100) {
if (cvrd < i) {
lits[li] = i - cvrd;
li += 2;
cvrd = i;
}
pos = _writeBlock(((i === dlen - 1) || (cvrd === dlen)) ? 1 : 0, lits, li, ebits, data, bs, i - bs, out, pos);
li = lc = ebits = 0;
bs = i;
}
let mch = 0;
if (i < dlen - 2) {
mch = _bestMatch(data, i, prev, c, Math.min(opt[2], dlen - i), opt[3]);
}
if (mch !== 0) {
const len = mch >>> 16, dst = mch & 0xffff;
const lgi = _goodIndex(len, U.of0); U.lhst[257 + lgi]++;
const dgi = _goodIndex(dst, U.df0); U.dhst[dgi]++; ebits += U.exb[lgi] + U.dxb[dgi];
lits[li] = (len << 23) | (i - cvrd); lits[li + 1] = (dst << 16) | (lgi << 8) | dgi; li += 2;
cvrd = i + len;
} else {
U.lhst[data[i]]++;
}
lc++;
}
}
ctx.i = i;
ctx.pos = pos;
ctx.cvrd = cvrd;
ctx.li = li;
ctx.lc = lc;
ctx.bs = bs;
ctx.ebits = ebits;
ctx.c = c;
ctx.nc = nc;
}
/**
* - good_length: reduce lazy search above this match length;
* - max_lazy: do not perform lazy search above this match length;
* - nice_length: quit search above this match length;
*/
const Opts = [
/* good lazy nice chain */
/* 0 */ [0, 0, 0, 0, 0], /* store only */
/* 1 */ [4, 4, 8, 4, 0], /* max speed, no lazy matches */
/* 2 */ [4, 5, 16, 8, 0],
/* 3 */ [4, 6, 16, 16, 0],
/* 4 */ [4, 10, 16, 32, 0], /* lazy matches */
/* 5 */ [8, 16, 32, 32, 0],
/* 6 */ [8, 16, 128, 128, 0],
/* 7 */ [8, 32, 128, 256, 0],
/* 8 */ [32, 128, 258, 1024, 1],
/* 9 */ [32, 258, 258, 4096, 1] /* max compression */
] as const;
export async function _deflateRaw(runtime: RuntimeContext, data: Uint8Array, out: Uint8Array, opos: number, lvl: number) {
const ctx = DeflateContext(data, out, opos, lvl);
const { dlen } = ctx;
if (lvl === 0) {
let { i, pos } = ctx;
while (i < dlen) {
const len = Math.min(0xffff, dlen - i);
_putsE(out, pos, (i + len === dlen ? 1 : 0));
pos = _copyExact(data, i, len, out, pos + 8);
i += len;
}
return pos >>> 3;
}
if (dlen > 2) {
ctx.nc = _hash(data, 0);
ctx.strt[ctx.nc] = 0;
}
while (ctx.i < dlen) {
if (runtime.shouldUpdate) {
await runtime.update({ message: 'Deflating...', current: ctx.i, max: dlen });
}
deflateChunk(ctx, 1024 * 1024);
}
let { li, cvrd, pos } = ctx;
const { i, lits, bs, ebits } = ctx;
if (bs !== i || data.length === 0) {
if (cvrd < i) {
lits[li] = i - cvrd;
li += 2;
cvrd = i;
}
pos = _writeBlock(1, lits, li, ebits, data, bs, i - bs, out, pos);
}
while ((pos & 7) !== 0) pos++;
return pos >>> 3;
}
function _bestMatch(data: Uint8Array, i: number, prev: Uint16Array, c: number, nice: number, chain: number) {
let ci = (i & 0x7fff), pi = prev[ci];
// console.log("----", i);
let dif = ((ci - pi + (1 << 15)) & 0x7fff);
if (pi === ci || c !== _hash(data, i - dif)) return 0;
let tl = 0, td = 0; // top length, top distance
const dlim = Math.min(0x7fff, i);
while (dif <= dlim && --chain !== 0 && pi !== ci /* && c==UZIP.F._hash(data,i-dif)*/) {
if (tl === 0 || (data[i + tl] === data[i + tl - dif])) {
let cl = _howLong(data, i, dif);
if (cl > tl) {
tl = cl; td = dif; if (tl >= nice) break; //*
if (dif + 2 < cl) cl = dif + 2;
let maxd = 0; // pi does not point to the start of the word
for (let j = 0; j < cl - 2; j++) {
const ei = (i - dif + j + (1 << 15)) & 0x7fff;
const li = prev[ei];
const curd = (ei - li + (1 << 15)) & 0x7fff;
if (curd > maxd) { maxd = curd; pi = ei; }
}
}
}
ci = pi; pi = prev[ci];
dif += ((ci - pi + (1 << 15)) & 0x7fff);
}
return (tl << 16) | td;
}
function _howLong(data: Uint8Array, i: number, dif: number) {
if (data[i] !== data[i - dif] || data[i + 1] !== data[i + 1 - dif] || data[i + 2] !== data[i + 2 - dif]) return 0;
const oi = i, l = Math.min(data.length, i + 258);
i += 3;
// while(i+4<l && data[i]==data[i-dif] && data[i+1]==data[i+1-dif] && data[i+2]==data[i+2-dif] && data[i+3]==data[i+3-dif]) i+=4;
while (i < l && data[i] === data[i - dif]) i++;
return i - oi;
}
function _hash(data: Uint8Array, i: number) {
return (((data[i] << 8) | data[i + 1]) + (data[i + 2] << 4)) & 0xffff;
// var hash_shift = 0, hash_mask = 255;
// var h = data[i+1] % 251;
// h = (((h << 8) + data[i+2]) % 251);
// h = (((h << 8) + data[i+2]) % 251);
// h = ((h<<hash_shift) ^ (c) ) & hash_mask;
// return h | (data[i]<<8);
// return (data[i] | (data[i+1]<<8));
}
function _writeBlock(BFINAL: number, lits: Uint32Array, li: number, ebits: number, data: Uint8Array, o0: number, l0: number, out: Uint8Array, pos: number) {
U.lhst[256]++;
const [ML, MD, MH, numl, numd, numh, lset, dset] = getTrees();
const cstSize = (((pos + 3) & 7) === 0 ? 0 : 8 - ((pos + 3) & 7)) + 32 + (l0 << 3);
const fxdSize = ebits + contSize(U.fltree, U.lhst) + contSize(U.fdtree, U.dhst);
let dynSize = ebits + contSize(U.ltree, U.lhst) + contSize(U.dtree, U.dhst);
dynSize += 14 + 3 * numh + contSize(U.itree, U.ihst) + (U.ihst[16] * 2 + U.ihst[17] * 3 + U.ihst[18] * 7);
for (let j = 0; j < 286; j++) U.lhst[j] = 0;
for (let j = 0; j < 30; j++) U.dhst[j] = 0;
for (let j = 0; j < 19; j++) U.ihst[j] = 0;
const BTYPE = (cstSize < fxdSize && cstSize < dynSize) ? 0 : (fxdSize < dynSize ? 1 : 2);
_putsF(out, pos, BFINAL);
_putsF(out, pos + 1, BTYPE);
pos += 3;
// let opos = pos;
if (BTYPE === 0) {
while ((pos & 7) !== 0) pos++;
pos = _copyExact(data, o0, l0, out, pos);
} else {
let ltree: number[], dtree: number[];
if (BTYPE === 1) {
ltree = U.fltree; dtree = U.fdtree;
} else if (BTYPE === 2) {
makeCodes(U.ltree, ML); revCodes(U.ltree, ML);
makeCodes(U.dtree, MD); revCodes(U.dtree, MD);
makeCodes(U.itree, MH); revCodes(U.itree, MH);
ltree = U.ltree; dtree = U.dtree;
_putsE(out, pos, numl - 257); pos += 5; // 286
_putsE(out, pos, numd - 1); pos += 5; // 30
_putsE(out, pos, numh - 4); pos += 4; // 19
for (let i = 0; i < numh; i++) _putsE(out, pos + i * 3, U.itree[(U.ordr[i] << 1) + 1]);
pos += 3 * numh;
pos = _codeTiny(lset, U.itree, out, pos);
pos = _codeTiny(dset, U.itree, out, pos);
} else {
throw new Error(`unknown BTYPE ${BTYPE}`);
}
let off = o0;
for (let si = 0; si < li; si += 2) {
const qb = lits[si], len = (qb >>> 23), end = off + (qb & ((1 << 23) - 1));
while (off < end) pos = _writeLit(data[off++], ltree, out, pos);
if (len !== 0) {
const qc = lits[si + 1], dst = (qc >> 16), lgi = (qc >> 8) & 255, dgi = (qc & 255);
pos = _writeLit(257 + lgi, ltree, out, pos);
_putsE(out, pos, len - U.of0[lgi]); pos += U.exb[lgi];
pos = _writeLit(dgi, dtree, out, pos);
_putsF(out, pos, dst - U.df0[dgi]); pos += U.dxb[dgi]; off += len;
}
}
pos = _writeLit(256, ltree, out, pos);
}
// console.log(pos-opos, fxdSize, dynSize, cstSize);
return pos;
}
function _copyExact(data: Uint8Array, off: number, len: number, out: Uint8Array, pos: number) {
let p8 = (pos >>> 3);
out[p8] = (len);
out[p8 + 1] = (len >>> 8);
out[p8 + 2] = 255 - out[p8];
out[p8 + 3] = 255 - out[p8 + 1];
p8 += 4;
out.set(new Uint8Array(data.buffer, off, len), p8);
// for(var i=0; i<len; i++) out[p8+i]=data[off+i];
return pos + ((len + 4) << 3);
}
/*
Interesting facts:
- decompressed block can have bytes, which do not occur in a Huffman tree (copied from the previous block by reference)
*/
function getTrees() {
const ML = _hufTree(U.lhst, U.ltree, 15);
const MD = _hufTree(U.dhst, U.dtree, 15);
const lset: number[] = [];
const numl = _lenCodes(U.ltree, lset);
const dset: number[] = [];
const numd = _lenCodes(U.dtree, dset);
for (let i = 0; i < lset.length; i += 2) U.ihst[lset[i]]++;
for (let i = 0; i < dset.length; i += 2) U.ihst[dset[i]]++;
const MH = _hufTree(U.ihst, U.itree, 7);
let numh = 19;
while (numh > 4 && U.itree[(U.ordr[numh - 1] << 1) + 1] === 0) numh--;
return [ML, MD, MH, numl, numd, numh, lset, dset] as const;
}
function contSize(tree: number[], hst: NumberArray) {
let s = 0;
for (let i = 0; i < hst.length; i++) s += hst[i] * tree[(i << 1) + 1];
return s;
}
function _codeTiny(set: number[], tree: number[], out: Uint8Array, pos: number) {
for (let i = 0; i < set.length; i += 2) {
const l = set[i], rst = set[i + 1]; // console.log(l, pos, tree[(l<<1)+1]);
pos = _writeLit(l, tree, out, pos);
const rsl = l === 16 ? 2 : (l === 17 ? 3 : 7);
if (l > 15) {
_putsE(out, pos, rst);
pos += rsl;
}
}
return pos;
}
function _lenCodes(tree: number[], set: number[]) {
let len = tree.length;
while (len !== 2 && tree[len - 1] === 0) len -= 2; // when no distances, keep one code with length 0
for (let i = 0; i < len; i += 2) {
const l = tree[i + 1], nxt = (i + 3 < len ? tree[i + 3] : -1), nnxt = (i + 5 < len ? tree[i + 5] : -1), prv = (i === 0 ? -1 : tree[i - 1]);
if (l === 0 && nxt === l && nnxt === l) {
let lz = i + 5;
while (lz + 2 < len && tree[lz + 2] === l) lz += 2;
const zc = Math.min((lz + 1 - i) >>> 1, 138);
if (zc < 11) set.push(17, zc - 3);
else set.push(18, zc - 11);
i += zc * 2 - 2;
} else if (l === prv && nxt === l && nnxt === l) {
let lz = i + 5;
while (lz + 2 < len && tree[lz + 2] === l) lz += 2;
const zc = Math.min((lz + 1 - i) >>> 1, 6);
set.push(16, zc - 3);
i += zc * 2 - 2;
} else {
set.push(l, 0);
}
}
return len >>> 1;
}
function _goodIndex(v: number, arr: number[]) {
let i = 0;
if (arr[i | 16] <= v) i |= 16;
if (arr[i | 8] <= v) i |= 8;
if (arr[i | 4] <= v) i |= 4;
if (arr[i | 2] <= v) i |= 2;
if (arr[i | 1] <= v) i |= 1;
return i;
}
function _writeLit(ch: number, ltree: number[], out: Uint8Array, pos: number) {
_putsF(out, pos, ltree[ch << 1]);
return pos + ltree[(ch << 1) + 1];
}
function _putsE(dt: NumberArray, pos: number, val: number) {
val = val << (pos & 7);
const o = (pos >>> 3);
dt[o] |= val;
dt[o + 1] |= (val >>> 8);
}
function _putsF(dt: NumberArray, pos: number, val: number) {
val = val << (pos & 7);
const o = (pos >>> 3);
dt[o] |= val;
dt[o + 1] |= (val >>> 8);
dt[o + 2] |= (val >>> 16);
} | the_stack |
import * as BaseView from 'app/client/components/BaseView';
import {CursorPos} from 'app/client/components/Cursor';
import {KoArray} from 'app/client/lib/koArray';
import {ColumnRec, TableRec, ViewFieldRec, ViewRec} from 'app/client/models/DocModel';
import {DocModel, IRowModel, recordSet, refRecord} from 'app/client/models/DocModel';
import * as modelUtil from 'app/client/models/modelUtil';
import {RowId} from 'app/client/models/rowset';
import {getWidgetTypes} from 'app/client/ui/widgetTypes';
import {Computed} from 'grainjs';
import * as ko from 'knockout';
import defaults = require('lodash/defaults');
// Represents a section of user views, now also known as a "page widget" (e.g. a view may contain
// a grid section and a chart section).
export interface ViewSectionRec extends IRowModel<"_grist_Views_section"> {
viewFields: ko.Computed<KoArray<ViewFieldRec>>;
optionsObj: modelUtil.SaveableObjObservable<any>;
customDef: CustomViewSectionDef;
themeDef: modelUtil.KoSaveableObservable<string>;
chartTypeDef: modelUtil.KoSaveableObservable<string>;
view: ko.Computed<ViewRec>;
table: ko.Computed<TableRec>;
tableTitle: ko.Computed<string>;
titleDef: modelUtil.KoSaveableObservable<string>;
borderWidthPx: ko.Computed<string>;
layoutSpecObj: modelUtil.ObjObservable<any>;
// Helper metadata item which indicates whether any of the section's fields have unsaved
// changes to their filters. (True indicates unsaved changes)
filterSpecChanged: Computed<boolean>;
// Array of fields with an active filter
filteredFields: Computed<ViewFieldRec[]>;
// Customizable version of the JSON-stringified sort spec. It may diverge from the saved one.
activeSortJson: modelUtil.CustomComputed<string>;
// is an array (parsed from JSON) of colRefs (i.e. rowIds into the columns table), with a
// twist: a rowId may be positive or negative, for ascending or descending respectively.
activeSortSpec: modelUtil.ObjObservable<number[]>;
// Modified sort spec to take into account any active display columns.
activeDisplaySortSpec: ko.Computed<number[]>;
// Evaluates to an array of column models, which are not referenced by anything in viewFields.
hiddenColumns: ko.Computed<ColumnRec[]>;
hasFocus: ko.Computed<boolean>;
activeLinkSrcSectionRef: modelUtil.CustomComputed<number>;
activeLinkSrcColRef: modelUtil.CustomComputed<number>;
activeLinkTargetColRef: modelUtil.CustomComputed<number>;
// Whether current linking state is as saved. It may be different during editing.
isActiveLinkSaved: ko.Computed<boolean>;
// Section-linking affects table if linkSrcSection is set. The controller value of the
// link is the value of srcCol at activeRowId of linkSrcSection, or activeRowId itself when
// srcCol is unset. If targetCol is set, we filter for all rows whose targetCol is equal to
// the controller value. Otherwise, the controller value determines the rowId of the cursor.
linkSrcSection: ko.Computed<ViewSectionRec>;
linkSrcCol: ko.Computed<ColumnRec>;
linkTargetCol: ko.Computed<ColumnRec>;
activeRowId: ko.Observable<RowId|null>; // May be null when there are no rows.
// If the view instance for section is instantiated, it will be accessible here.
viewInstance: ko.Observable<BaseView|null>;
// Describes the most recent cursor position in the section. Only rowId and fieldIndex are used.
lastCursorPos: CursorPos;
// Describes the most recent scroll position.
lastScrollPos: {
rowIndex: number; // Used for scrolly sections. Indicates the index of the first visible row.
offset: number; // Pixel distance past the top of row indicated by rowIndex.
scrollLeft: number; // Used for grid sections. Indicates the scrollLeft value of the scroll pane.
};
disableAddRemoveRows: ko.Computed<boolean>;
isSorted: ko.Computed<boolean>;
disableDragRows: ko.Computed<boolean>;
activeFilterBar: modelUtil.CustomComputed<boolean>;
// Number of frozen columns
rawNumFrozen: modelUtil.CustomComputed<number>;
// Number for frozen columns to display.
// We won't freeze all the columns on a grid, it will leave at least 1 column unfrozen.
numFrozen: ko.Computed<number>;
// Save all filters of fields in the section.
saveFilters(): Promise<void>;
// Revert all filters of fields in the section.
revertFilters(): void;
// Clear and save all filters of fields in the section.
clearFilters(): void;
}
export interface CustomViewSectionDef {
/**
* The mode.
*/
mode: ko.Observable<"url"|"plugin">;
/**
* The url.
*/
url: ko.Observable<string>;
/**
* Access granted to url.
*/
access: ko.Observable<string>;
/**
* The plugin id.
*/
pluginId: ko.Observable<string>;
/**
* The section id.
*/
sectionId: ko.Observable<string>;
}
export function createViewSectionRec(this: ViewSectionRec, docModel: DocModel): void {
this.viewFields = recordSet(this, docModel.viewFields, 'parentId', {sortBy: 'parentPos'});
const defaultOptions = {
verticalGridlines: true,
horizontalGridlines: true,
zebraStripes: false,
customView: '',
filterBar: false,
numFrozen: 0
};
this.optionsObj = modelUtil.jsonObservable(this.options,
(obj: any) => defaults(obj || {}, defaultOptions));
const customViewDefaults = {
mode: 'url',
url: '',
access: '',
pluginId: '',
sectionId: ''
};
const customDefObj = modelUtil.jsonObservable(this.optionsObj.prop('customView'),
(obj: any) => defaults(obj || {}, customViewDefaults));
this.customDef = {
mode: customDefObj.prop('mode'),
url: customDefObj.prop('url'),
access: customDefObj.prop('access'),
pluginId: customDefObj.prop('pluginId'),
sectionId: customDefObj.prop('sectionId')
};
this.themeDef = modelUtil.fieldWithDefault(this.theme, 'form');
this.chartTypeDef = modelUtil.fieldWithDefault(this.chartType, 'bar');
this.view = refRecord(docModel.views, this.parentId);
this.table = refRecord(docModel.tables, this.tableRef);
this.tableTitle = this.autoDispose(ko.pureComputed(() => this.table().tableTitle()));
this.titleDef = modelUtil.fieldWithDefault(
this.title,
() => this.table().tableTitle() + (
(this.parentKey() === 'record') ? '' : ` ${getWidgetTypes(this.parentKey.peek() as any).label}`
)
);
this.borderWidthPx = ko.pureComputed(function() { return this.borderWidth() + 'px'; }, this);
this.layoutSpecObj = modelUtil.jsonObservable(this.layoutSpec);
// Helper metadata item which indicates whether any of the section's fields have unsaved
// changes to their filters. (True indicates unsaved changes)
this.filterSpecChanged = Computed.create(this, use =>
use(use(this.viewFields).getObservable()).some(field => !use(field.activeFilter.isSaved)));
this.filteredFields = Computed.create(this, use =>
use(use(this.viewFields).getObservable()).filter(field => use(field.isFiltered)));
// Save all filters of fields in the section.
this.saveFilters = () => {
return docModel.docData.bundleActions(`Save all filters in ${this.titleDef()}`,
async () => { await Promise.all(this.viewFields().all().map(field => field.activeFilter.save())); }
);
};
// Revert all filters of fields in the section.
this.revertFilters = () => {
this.viewFields().all().forEach(field => { field.activeFilter.revert(); });
};
// Reset all filters of fields in the section to their default (i.e. unset) values.
this.clearFilters = () => this.viewFields().all().forEach(field => field.activeFilter(''));
// Customizable version of the JSON-stringified sort spec. It may diverge from the saved one.
this.activeSortJson = modelUtil.customValue(this.sortColRefs);
// This is an array (parsed from JSON) of colRefs (i.e. rowIds into the columns table), with a
// twist: a rowId may be positive or negative, for ascending or descending respectively.
// TODO: This method of ignoring columns which are deleted is inefficient and may cause conflicts
// with sharing.
this.activeSortSpec = modelUtil.jsonObservable(this.activeSortJson, (obj: any) => {
return (obj || []).filter((sortRef: number) => {
const colModel = docModel.columns.getRowModel(Math.abs(sortRef));
return !colModel._isDeleted() && colModel.getRowId();
});
});
// Modified sort spec to take into account any active display columns.
this.activeDisplaySortSpec = this.autoDispose(ko.computed(() => {
return this.activeSortSpec().map(directionalColRef => {
const colRef = Math.abs(directionalColRef);
const field = this.viewFields().all().find(f => f.column().origColRef() === colRef);
const effectiveColRef = field ? field.displayColRef() : colRef;
return directionalColRef > 0 ? effectiveColRef : -effectiveColRef;
});
}));
// Evaluates to an array of column models, which are not referenced by anything in viewFields.
this.hiddenColumns = this.autoDispose(ko.pureComputed(() => {
const included = new Set(this.viewFields().all().map((f) => f.column().origColRef()));
return this.table().columns().all().filter(function(col) {
return !included.has(col.getRowId()) && !col.isHiddenCol();
});
}));
this.hasFocus = ko.pureComputed({
// Read may occur for recently disposed sections, must check condition first.
read: () => !this.isDisposed() && this.view().activeSectionId() === this.id() && !this.view().isLinking(),
write: (val) => { if (val) { this.view().activeSectionId(this.id()); } }
});
this.activeLinkSrcSectionRef = modelUtil.customValue(this.linkSrcSectionRef);
this.activeLinkSrcColRef = modelUtil.customValue(this.linkSrcColRef);
this.activeLinkTargetColRef = modelUtil.customValue(this.linkTargetColRef);
// Whether current linking state is as saved. It may be different during editing.
this.isActiveLinkSaved = this.autoDispose(ko.pureComputed(() =>
this.activeLinkSrcSectionRef.isSaved() &&
this.activeLinkSrcColRef.isSaved() &&
this.activeLinkTargetColRef.isSaved()));
// Section-linking affects this table if linkSrcSection is set. The controller value of the
// link is the value of srcCol at activeRowId of linkSrcSection, or activeRowId itself when
// srcCol is unset. If targetCol is set, we filter for all rows whose targetCol is equal to
// the controller value. Otherwise, the controller value determines the rowId of the cursor.
this.linkSrcSection = refRecord(docModel.viewSections, this.activeLinkSrcSectionRef);
this.linkSrcCol = refRecord(docModel.columns, this.activeLinkSrcColRef);
this.linkTargetCol = refRecord(docModel.columns, this.activeLinkTargetColRef);
this.activeRowId = ko.observable();
// If the view instance for this section is instantiated, it will be accessible here.
this.viewInstance = ko.observable(null);
// Describes the most recent cursor position in the section.
this.lastCursorPos = {
rowId: 0,
fieldIndex: 0
};
// Describes the most recent scroll position.
this.lastScrollPos = {
rowIndex: 0, // Used for scrolly sections. Indicates the index of the first visible row.
offset: 0, // Pixel distance past the top of row indicated by rowIndex.
scrollLeft: 0 // Used for grid sections. Indicates the scrollLeft value of the scroll pane.
};
this.disableAddRemoveRows = ko.pureComputed(() => this.table().disableAddRemoveRows());
this.isSorted = ko.pureComputed(() => this.activeSortSpec().length > 0);
this.disableDragRows = ko.pureComputed(() => this.isSorted() || !this.table().supportsManualSort());
this.activeFilterBar = modelUtil.customValue(this.optionsObj.prop('filterBar'));
// Number of frozen columns
this.rawNumFrozen = modelUtil.customValue(this.optionsObj.prop('numFrozen'));
// Number for frozen columns to display
this.numFrozen = ko.pureComputed(() =>
Math.max(
0,
Math.min(
this.rawNumFrozen(),
this.viewFields().all().length - 1
)
)
);
} | the_stack |
import mockedEnv from "mocked-env";
import * as functionsTestInit from "firebase-functions-test";
import { messages } from "../src/logs/messages";
const defaultEnvironment = {
PROJECT_ID: "fake-project",
LOCATION: "us-central1",
// values from extension.yaml param defaults
LANGUAGES: "en,es,de,fr",
COLLECTION_PATH: "translations",
INPUT_FIELD_NAME: "input",
OUTPUT_FIELD_NAME: "translated",
};
const {
snapshot,
testTranslations,
mockDocumentSnapshotFactory,
mockTranslate,
mockTranslateClassMethod,
mockTranslateClass,
mockFirestoreUpdate,
mockFirestoreTransaction,
mockTranslateModule,
clearMocks,
} = global;
mockTranslateModule();
let functionsTest = functionsTestInit();
let restoreEnv;
describe("extension", () => {
beforeEach(() => {
restoreEnv = mockedEnv(defaultEnvironment);
clearMocks();
});
test("functions are exported", () => {
const exportedFunctions = jest.requireActual("../src");
expect(exportedFunctions.fstranslate).toBeInstanceOf(Function);
});
describe("functions.fstranslate", () => {
let logMock;
let errorLogMock;
let admin;
let wrappedMockTranslate;
let beforeSnapshot;
let afterSnapshot;
let documentChange;
beforeEach(() => {
// this is best thought of as default environment for each test which might be altered within
// each test subject to test's needs
jest.resetModules();
functionsTest = functionsTestInit();
admin = require("firebase-admin");
wrappedMockTranslate = mockTranslate();
logMock = jest.fn();
errorLogMock = jest.fn();
beforeSnapshot = snapshot({});
afterSnapshot = snapshot();
documentChange = functionsTest.makeChange(
beforeSnapshot,
mockDocumentSnapshotFactory(afterSnapshot)
);
admin.firestore().runTransaction = mockFirestoreTransaction();
require("firebase-functions").logger = {
log: logMock,
error: errorLogMock,
};
});
test("initializes Google Translation API with PROJECT_ID on function load", () => {
// need to reset modules
jest.resetModules();
// so we can require clean ../function/src that has not been called
require("../src");
expect(mockTranslateClass).toHaveBeenCalledTimes(1);
expect(mockTranslateClass).toHaveBeenCalledWith({
projectId: defaultEnvironment.PROJECT_ID,
});
});
test("function skips deleted document change events", async () => {
documentChange.after.exists = false;
const callResult = await wrappedMockTranslate(documentChange);
expect(callResult).toBeUndefined();
expect(logMock).toHaveBeenCalledWith(messages.documentDeleted());
expect(mockTranslateClassMethod).not.toHaveBeenCalled();
expect(mockFirestoreUpdate).not.toHaveBeenCalled();
});
test("function skips 'update' document change events if the input is unchanged", async () => {
beforeSnapshot = snapshot();
afterSnapshot = snapshot({
input: "hello",
changed: 123,
});
documentChange = functionsTest.makeChange(beforeSnapshot, afterSnapshot);
const callResult = await wrappedMockTranslate(documentChange);
expect(callResult).toBeUndefined();
expect(logMock).toHaveBeenCalledWith(
expect.stringContaining(messages.documentUpdatedUnchangedInput())
);
expect(mockTranslateClassMethod).not.toHaveBeenCalled();
expect(mockFirestoreUpdate).not.toHaveBeenCalled();
});
test("function skips document 'created' document change events without any input", async () => {
afterSnapshot = snapshot({
changed: 123,
});
documentChange = functionsTest.makeChange(beforeSnapshot, afterSnapshot);
const callResult = await wrappedMockTranslate(documentChange);
expect(callResult).toBeUndefined();
expect(logMock).toHaveBeenCalledWith(messages.documentCreatedNoInput());
expect(mockTranslateClassMethod).not.toHaveBeenCalled();
expect(mockFirestoreUpdate).not.toHaveBeenCalled();
});
test("function exits early if input & output fields are the same", async () => {
restoreEnv = mockedEnv({
...defaultEnvironment,
INPUT_FIELD_NAME: "input",
OUTPUT_FIELD_NAME: "input",
});
wrappedMockTranslate = mockTranslate();
const callResult = await wrappedMockTranslate(documentChange);
expect(callResult).toBeUndefined();
});
test("function exits early if input field is a translation output path", async () => {
restoreEnv = mockedEnv({
...defaultEnvironment,
INPUT_FIELD_NAME: "output.en",
OUTPUT_FIELD_NAME: "output",
});
wrappedMockTranslate = mockTranslate();
const callResult = await wrappedMockTranslate(documentChange);
expect(callResult).toBeUndefined();
});
test("function updates translation document with translations", async () => {
await wrappedMockTranslate(documentChange);
// confirm Google Translation API was called
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "en");
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "es");
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "fr");
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "de");
// confirm document update was called
expect(mockFirestoreUpdate).toHaveBeenCalledWith(
defaultEnvironment.OUTPUT_FIELD_NAME,
testTranslations
);
// confirm logs were printed
Object.keys(testTranslations).forEach((language) => {
// logs.translateInputString
expect(logMock).toHaveBeenCalledWith(
messages.translateInputString("hello", language)
);
// logs.translateStringComplete
expect(logMock).toHaveBeenCalledWith(
messages.translateStringComplete("hello", language)
);
});
// logs.translateInputStringToAllLanguages
expect(logMock).toHaveBeenCalledWith(
messages.translateInputStringToAllLanguages(
"hello",
defaultEnvironment.LANGUAGES.split(",")
)
);
// logs.translateInputToAllLanguagesComplete
expect(logMock).toHaveBeenCalledWith(
messages.translateInputToAllLanguagesComplete("hello")
);
});
test("function updates translation document with multiple translations", async () => {
beforeSnapshot = snapshot();
afterSnapshot = snapshot({
input: {
one: "hello",
two: "hello",
},
});
documentChange = functionsTest.makeChange(beforeSnapshot, afterSnapshot);
await wrappedMockTranslate(documentChange);
// confirm document update was called
expect(mockFirestoreUpdate).toHaveBeenCalledWith("translated", {
one: {
de: "hallo",
en: "hello",
es: "hola",
fr: "salut",
},
two: {
de: "hallo",
en: "hello",
es: "hola",
fr: "salut",
},
});
// confirm logs were printed
Object.entries((key, value) => {
expect(logMock).toHaveBeenCalledWith(
messages.translateInputString(value, key)
);
// logs.translateInputStringToAllLanguages
expect(logMock).toHaveBeenCalledWith(
messages.translateInputStringToAllLanguages(
key,
defaultEnvironment.LANGUAGES.split(",")
)
);
// logs.translateInputToAllLanguagesComplete
expect(logMock).toHaveBeenCalledWith(
messages.translateInputToAllLanguagesComplete(value)
);
});
});
test("function updates translation document when previous input changes", async () => {
beforeSnapshot = snapshot({
input: "goodbye",
});
documentChange.before = beforeSnapshot;
await wrappedMockTranslate(documentChange);
// logs.documentUpdatedChangedInput
expect(logMock).toHaveBeenCalledWith(
messages.documentUpdatedChangedInput()
);
// confirm Google Translation API was called
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "en");
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "es");
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "fr");
expect(mockTranslateClassMethod).toHaveBeenCalledWith("hello", "de");
// confirm document update was called
expect(mockFirestoreUpdate).toHaveBeenCalledWith(
defaultEnvironment.OUTPUT_FIELD_NAME,
testTranslations
);
});
test("function deletes translations if input field is removed", async () => {
beforeSnapshot = snapshot();
afterSnapshot = snapshot({});
documentChange = functionsTest.makeChange(
beforeSnapshot,
mockDocumentSnapshotFactory(afterSnapshot)
);
await wrappedMockTranslate(documentChange);
expect(mockFirestoreUpdate).toHaveBeenCalledWith(
defaultEnvironment.OUTPUT_FIELD_NAME,
admin.firestore.FieldValue.delete()
);
// logs.documentUpdatedDeletedInput
expect(logMock).toHaveBeenCalledWith(
messages.documentUpdatedDeletedInput()
);
});
test("function skips processing if no input string on before & after snapshots", async () => {
const snap = snapshot({
notTheInput: "hello",
});
documentChange = functionsTest.makeChange(
snap,
mockDocumentSnapshotFactory(snap)
);
await wrappedMockTranslate(documentChange);
expect(mockFirestoreUpdate).not.toHaveBeenCalled();
expect(mockTranslateClassMethod).not.toHaveBeenCalled();
// logs.documentUpdatedNoInput
expect(logMock).toHaveBeenCalledWith(messages.documentUpdatedNoInput());
});
test("function handles Google Translation API errors", async () => {
const error = new Error("Test Translation API Error");
mockTranslateClassMethod.mockImplementationOnce(() =>
Promise.reject(error)
);
await wrappedMockTranslate(documentChange);
// logs.translateStringError
expect(errorLogMock).toHaveBeenCalledWith(
...messages.translateStringError("hello", "en", error)
);
// logs.translateInputToAllLanguagesError
expect(errorLogMock).toHaveBeenCalledWith(
...messages.translateInputToAllLanguagesError("hello", error)
);
});
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/attestationProvidersMappers";
import * as Parameters from "../models/parameters";
import { AttestationManagementClientContext } from "../attestationManagementClientContext";
/** Class representing a AttestationProviders. */
export class AttestationProviders {
private readonly client: AttestationManagementClientContext;
/**
* Create a AttestationProviders.
* @param {AttestationManagementClientContext} client Reference to the service client.
*/
constructor(client: AttestationManagementClientContext) {
this.client = client;
}
/**
* Get the status of Attestation Provider.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersGetResponse>
*/
get(resourceGroupName: string, providerName: string, options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersGetResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance
* @param callback The callback
*/
get(resourceGroupName: string, providerName: string, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, providerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
get(resourceGroupName: string, providerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProvider>, callback?: msRest.ServiceCallback<Models.AttestationProvider>): Promise<Models.AttestationProvidersGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
providerName,
options
},
getOperationSpec,
callback) as Promise<Models.AttestationProvidersGetResponse>;
}
/**
* Creates a new Attestation Provider instance.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance.
* @param creationParams Client supplied parameters.
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersCreateResponse>
*/
create(resourceGroupName: string, providerName: string, creationParams: Models.AttestationServiceCreationParams, options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersCreateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance.
* @param creationParams Client supplied parameters.
* @param callback The callback
*/
create(resourceGroupName: string, providerName: string, creationParams: Models.AttestationServiceCreationParams, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance.
* @param creationParams Client supplied parameters.
* @param options The optional parameters
* @param callback The callback
*/
create(resourceGroupName: string, providerName: string, creationParams: Models.AttestationServiceCreationParams, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
create(resourceGroupName: string, providerName: string, creationParams: Models.AttestationServiceCreationParams, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProvider>, callback?: msRest.ServiceCallback<Models.AttestationProvider>): Promise<Models.AttestationProvidersCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
providerName,
creationParams,
options
},
createOperationSpec,
callback) as Promise<Models.AttestationProvidersCreateResponse>;
}
/**
* Updates the Attestation Provider.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance.
* @param updateParams Client supplied parameters.
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersUpdateResponse>
*/
update(resourceGroupName: string, providerName: string, updateParams: Models.AttestationServicePatchParams, options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance.
* @param updateParams Client supplied parameters.
* @param callback The callback
*/
update(resourceGroupName: string, providerName: string, updateParams: Models.AttestationServicePatchParams, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service instance.
* @param updateParams Client supplied parameters.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, providerName: string, updateParams: Models.AttestationServicePatchParams, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
update(resourceGroupName: string, providerName: string, updateParams: Models.AttestationServicePatchParams, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProvider>, callback?: msRest.ServiceCallback<Models.AttestationProvider>): Promise<Models.AttestationProvidersUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
providerName,
updateParams,
options
},
updateOperationSpec,
callback) as Promise<Models.AttestationProvidersUpdateResponse>;
}
/**
* Delete Attestation Service.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, providerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, providerName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param providerName Name of the attestation service
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, providerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, providerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
providerName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Returns a list of attestation providers in a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.AttestationProviderListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProviderListResult>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProviderListResult>, callback?: msRest.ServiceCallback<Models.AttestationProviderListResult>): Promise<Models.AttestationProvidersListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.AttestationProvidersListResponse>;
}
/**
* Returns attestation providers list in a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.AttestationProviderListResult>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProviderListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProviderListResult>, callback?: msRest.ServiceCallback<Models.AttestationProviderListResult>): Promise<Models.AttestationProvidersListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.AttestationProvidersListByResourceGroupResponse>;
}
/**
* Get the default provider
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersListDefaultResponse>
*/
listDefault(options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersListDefaultResponse>;
/**
* @param callback The callback
*/
listDefault(callback: msRest.ServiceCallback<Models.AttestationProviderListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listDefault(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProviderListResult>): void;
listDefault(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProviderListResult>, callback?: msRest.ServiceCallback<Models.AttestationProviderListResult>): Promise<Models.AttestationProvidersListDefaultResponse> {
return this.client.sendOperationRequest(
{
options
},
listDefaultOperationSpec,
callback) as Promise<Models.AttestationProvidersListDefaultResponse>;
}
/**
* Get the default provider by location.
* @param location The location of the default provider.
* @param [options] The optional parameters
* @returns Promise<Models.AttestationProvidersGetDefaultByLocationResponse>
*/
getDefaultByLocation(location: string, options?: msRest.RequestOptionsBase): Promise<Models.AttestationProvidersGetDefaultByLocationResponse>;
/**
* @param location The location of the default provider.
* @param callback The callback
*/
getDefaultByLocation(location: string, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
/**
* @param location The location of the default provider.
* @param options The optional parameters
* @param callback The callback
*/
getDefaultByLocation(location: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AttestationProvider>): void;
getDefaultByLocation(location: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AttestationProvider>, callback?: msRest.ServiceCallback<Models.AttestationProvider>): Promise<Models.AttestationProvidersGetDefaultByLocationResponse> {
return this.client.sendOperationRequest(
{
location,
options
},
getDefaultByLocationOperationSpec,
callback) as Promise<Models.AttestationProvidersGetDefaultByLocationResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Attestation/attestationProviders/{providerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.providerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AttestationProvider
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Attestation/attestationProviders/{providerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.providerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "creationParams",
mapper: {
...Mappers.AttestationServiceCreationParams,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.AttestationProvider
},
201: {
bodyMapper: Mappers.AttestationProvider
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Attestation/attestationProviders/{providerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.providerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "updateParams",
mapper: {
...Mappers.AttestationServicePatchParams,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.AttestationProvider
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Attestation/attestationProviders/{providerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.providerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Attestation/attestationProviders",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AttestationProviderListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Attestation/attestationProviders",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AttestationProviderListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listDefaultOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Attestation/defaultProviders",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AttestationProviderListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getDefaultByLocationOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Attestation/locations/{location}/defaultProvider",
urlParameters: [
Parameters.location,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AttestationProvider
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
"use strict";
import * as net from "net";
import * as fs from "fs";
import * as path from "path";
import {
workspace,
Disposable,
ExtensionContext,
window,
commands,
WorkspaceFolder,
ProgressLocation,
Progress,
DebugAdapterExecutable,
debug,
DebugConfiguration,
DebugConfigurationProvider,
CancellationToken,
ProviderResult,
extensions,
ConfigurationTarget,
env,
Uri,
} from "vscode";
import { LanguageClientOptions, State } from "vscode-languageclient";
import { LanguageClient, ServerOptions } from "vscode-languageclient/node";
import * as inspector from "./inspector";
import { copySelectedToClipboard, removeLocator } from "./locators";
import * as views from "./views";
import * as roboConfig from "./robocorpSettings";
import { logError, OUTPUT_CHANNEL } from "./channel";
import { getExtensionRelativeFile, verifyFileExists } from "./files";
import {
collectBaseEnv,
getRccLocation,
RCCDiagnostics,
runConfigDiagnostics,
STATUS_FAIL,
STATUS_FATAL,
STATUS_OK,
STATUS_WARNING,
submitIssue,
submitIssueUI,
} from "./rcc";
import { Timing } from "./time";
import { execFilePromise, ExecFileReturn } from "./subprocess";
import {
createRobot,
uploadRobot,
cloudLogin,
runRobotRCC,
cloudLogout,
setPythonInterpreterFromRobotYaml,
askAndRunRobotRCC,
rccConfigurationDiagnostics,
updateLaunchEnvironment,
resolveInterpreter,
} from "./activities";
import { sleep } from "./time";
import { handleProgressMessage, ProgressReport } from "./progress";
import { TREE_VIEW_ROBOCORP_ROBOTS_TREE, TREE_VIEW_ROBOCORP_ROBOT_CONTENT_TREE } from "./robocorpViews";
import { askAndCreateRccTerminal } from "./rccTerminal";
import {
deleteResourceInRobotContentTree,
newFileInRobotContentTree,
newFolderInRobotContentTree,
renameResourceInRobotContentTree,
} from "./viewsRobotContent";
import {
convertOutputWorkItemToInput,
deleteWorkItemInWorkItemsTree,
newWorkItemInWorkItemsTree,
openWorkItemHelp,
} from "./viewsWorkItems";
import { LocatorEntry, RobotEntry } from "./viewsCommon";
import {
ROBOCORP_CLOUD_LOGIN,
ROBOCORP_CLOUD_LOGOUT,
ROBOCORP_CLOUD_UPLOAD_ROBOT_TREE_SELECTION,
ROBOCORP_COMPUTE_ROBOT_LAUNCH_FROM_ROBOCORP_CODE_LAUNCH,
ROBOCORP_CONFIGURATION_DIAGNOSTICS,
ROBOCORP_CONVERT_OUTPUT_WORK_ITEM_TO_INPUT,
ROBOCORP_COPY_LOCATOR_TO_CLIPBOARD_INTERNAL,
ROBOCORP_CREATE_RCC_TERMINAL_TREE_SELECTION,
ROBOCORP_CREATE_ROBOT,
ROBOCORP_DEBUG_ROBOT_RCC,
ROBOCORP_DELETE_RESOURCE_IN_ROBOT_CONTENT_VIEW,
ROBOCORP_DELETE_WORK_ITEM_IN_WORK_ITEMS_VIEW,
ROBOCORP_EDIT_ROBOCORP_INSPECTOR_LOCATOR,
ROBOCORP_GET_LANGUAGE_SERVER_PYTHON,
ROBOCORP_GET_LANGUAGE_SERVER_PYTHON_INFO,
ROBOCORP_HELP_WORK_ITEMS,
ROBOCORP_NEW_FILE_IN_ROBOT_CONTENT_VIEW,
ROBOCORP_NEW_FOLDER_IN_ROBOT_CONTENT_VIEW,
ROBOCORP_NEW_ROBOCORP_INSPECTOR_BROWSER,
ROBOCORP_NEW_ROBOCORP_INSPECTOR_IMAGE,
ROBOCORP_NEW_WORK_ITEM_IN_WORK_ITEMS_VIEW,
ROBOCORP_OPEN_CLOUD_HOME,
ROBOCORP_OPEN_ROBOT_TREE_SELECTION,
ROBOCORP_RCC_TERMINAL_NEW,
ROBOCORP_REFRESH_CLOUD_VIEW,
ROBOCORP_REFRESH_ROBOTS_VIEW,
ROBOCORP_REFRESH_ROBOT_CONTENT_VIEW,
ROBOCORP_REMOVE_LOCATOR_FROM_JSON,
ROBOCORP_RENAME_RESOURCE_IN_ROBOT_CONTENT_VIEW,
ROBOCORP_ROBOTS_VIEW_TASK_DEBUG,
ROBOCORP_ROBOTS_VIEW_TASK_RUN,
ROBOCORP_RUN_ROBOT_RCC,
ROBOCORP_SET_PYTHON_INTERPRETER,
ROBOCORP_SUBMIT_ISSUE,
ROBOCORP_SUBMIT_ISSUE_INTERNAL,
ROBOCORP_UPDATE_LAUNCH_ENV,
ROBOCORP_UPLOAD_ROBOT_TO_CLOUD,
} from "./robocorpCommands";
const clientOptions: LanguageClientOptions = {
documentSelector: [
{ language: "json", pattern: "**/locators.json" },
{ language: "yaml", pattern: "**/conda.yaml" },
{ language: "yaml", pattern: "**/robot.yaml" },
],
synchronize: {
configurationSection: "robocorp",
},
outputChannel: OUTPUT_CHANNEL,
};
function startLangServerIO(command: string, args: string[], environ?: { [key: string]: string }): LanguageClient {
const serverOptions: ServerOptions = {
command,
args,
};
if (!environ) {
environ = process.env;
}
let src: string = path.resolve(__dirname, "../../src");
serverOptions.options = { env: { ...environ, PYTHONPATH: src }, cwd: path.dirname(command) };
// See: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide
return new LanguageClient(command, serverOptions, clientOptions);
}
function startLangServerTCP(addr: number): LanguageClient {
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,
});
});
});
};
return new LanguageClient(`tcp lang server (port ${addr})`, serverOptions, clientOptions);
}
interface InterpreterInfo {
pythonExe: string;
environ?: { [key: string]: string };
additionalPythonpathEntries: string[];
}
interface ActionResult {
success: boolean;
message: string;
result: any;
}
function notifyOfInitializationErrorShowOutputTab(msg?: string) {
OUTPUT_CHANNEL.show();
if (!msg) {
msg = "Unable to activate Robocorp Code extension. Please see: Output > Robocorp Code for more details.";
}
window.showErrorMessage(msg);
}
class CommandRegistry {
private context: ExtensionContext;
public registerErrorStubs: boolean = false;
public constructor(context: ExtensionContext) {
this.context = context;
}
public register(command: string, callback: (...args: any[]) => any, thisArg?: any): void {
if (this.registerErrorStubs) {
this.context.subscriptions.push(
commands.registerCommand(command, () => {
notifyOfInitializationErrorShowOutputTab();
})
);
} else {
this.context.subscriptions.push(commands.registerCommand(command, callback));
}
}
}
class RobocorpCodeDebugConfigurationProvider implements DebugConfigurationProvider {
provideDebugConfigurations?(folder: WorkspaceFolder | undefined, token?: CancellationToken): DebugConfiguration[] {
let configurations: DebugConfiguration[] = [];
configurations.push({
"type": "robocorp-code",
"name": "Robocorp Code: Launch task from robot.yaml",
"request": "launch",
"robot": '^"\\${file}"',
"task": "",
});
return configurations;
}
async resolveDebugConfigurationWithSubstitutedVariables(
folder: WorkspaceFolder | undefined,
debugConfiguration: DebugConfiguration,
token?: CancellationToken
): Promise<DebugConfiguration> {
if (!fs.existsSync(debugConfiguration.robot)) {
window.showWarningMessage('Error. Expected: specified "robot": ' + debugConfiguration.robot + " to exist.");
return;
}
let interpreter: InterpreterInfo | undefined = undefined;
let interpreterResult = await resolveInterpreter(debugConfiguration.robot);
if (!interpreterResult.success) {
window.showWarningMessage("Error resolving interpreter info: " + interpreterResult.message);
return;
}
interpreter = interpreterResult.result;
if (!interpreter) {
window.showWarningMessage("Unable to resolve interpreter for: " + debugConfiguration.robot);
return;
}
if (!interpreter.environ) {
window.showErrorMessage("Unable to resolve interpreter environment based on: " + debugConfiguration.robot);
return;
}
// Resolve environment
let env = interpreter.environ;
try {
let newEnv: { [key: string]: string } | "cancelled" = await commands.executeCommand(
ROBOCORP_UPDATE_LAUNCH_ENV,
{
"targetRobot": debugConfiguration.robot,
"env": env,
}
);
if (newEnv === "cancelled") {
OUTPUT_CHANNEL.appendLine("Launch cancelled");
return;
} else {
env = newEnv;
}
} catch (error) {
// The command may not be available.
}
if (debugConfiguration.noDebug) {
// Not running with debug: just use rcc to launch.
debugConfiguration.env = env;
return debugConfiguration;
}
// If it's a debug run, we need to get the input contents -- something as:
// "type": "robocorp-code",
// "name": "Robocorp Code: Launch task from current robot.yaml",
// "request": "launch",
// "robot": "c:/robot.yaml",
// "task": "entrypoint",
//
// and convert it to the contents expected by robotframework-lsp:
//
// "type": "robotframework-lsp",
// "name": "Robot: Current File",
// "request": "launch",
// "cwd": "${workspaceFolder}",
// "target": "c:/task.robot",
//
// (making sure that we can actually do this and it's a robot launch for the task)
let actionResult: ActionResult = await commands.executeCommand(
ROBOCORP_COMPUTE_ROBOT_LAUNCH_FROM_ROBOCORP_CODE_LAUNCH,
{
"name": debugConfiguration.name,
"request": debugConfiguration.request,
"robot": debugConfiguration.robot,
"task": debugConfiguration.task,
"additionalPythonpathEntries": interpreter.additionalPythonpathEntries,
"env": env,
"pythonExe": interpreter.pythonExe,
}
);
if (!actionResult.success) {
window.showErrorMessage(actionResult.message);
return;
}
let result = actionResult.result;
if (result && result.type && result.type == "python") {
let extension = extensions.getExtension("ms-python.python");
if (extension) {
if (!extension.isActive) {
// i.e.: Auto-activate python extension for the launch as the extension
// is only activated for debug on the resolution, whereas in this case
// the launch is already resolved.
await extension.activate();
}
}
}
return result;
}
}
function registerDebugger(pythonExecutable: string) {
async function createDebugAdapterExecutable(config: DebugConfiguration): Promise<DebugAdapterExecutable> {
let env = config.env;
if (!env) {
env = {};
}
let robotHome = roboConfig.getHome();
if (robotHome && robotHome.length > 0) {
if (env) {
env["ROBOCORP_HOME"] = robotHome;
} else {
env = { "ROBOCORP_HOME": robotHome };
}
}
let targetMain: string = path.resolve(__dirname, "../../src/robocorp_code_debug_adapter/__main__.py");
if (!fs.existsSync(targetMain)) {
window.showWarningMessage("Error. Expected: " + targetMain + " to exist.");
return;
}
if (!fs.existsSync(pythonExecutable)) {
window.showWarningMessage("Error. Expected: " + pythonExecutable + " to exist.");
return;
}
if (env) {
return new DebugAdapterExecutable(pythonExecutable, ["-u", targetMain], { "env": env });
} else {
return new DebugAdapterExecutable(pythonExecutable, ["-u", targetMain]);
}
}
debug.registerDebugAdapterDescriptorFactory("robocorp-code", {
createDebugAdapterDescriptor: (session) => {
const config: DebugConfiguration = session.configuration;
return createDebugAdapterExecutable(config);
},
});
debug.registerDebugConfigurationProvider("robocorp-code", new RobocorpCodeDebugConfigurationProvider());
}
async function verifyRobotFrameworkInstalled() {
if (!roboConfig.getVerifylsp()) {
return;
}
const ROBOT_EXTENSION_ID = "robocorp.robotframework-lsp";
let found = true;
try {
let extension = extensions.getExtension(ROBOT_EXTENSION_ID);
if (!extension) {
found = false;
}
} catch (error) {
found = false;
}
if (!found) {
// It seems it's not installed, install?
let install = "Install";
let dontAsk = "Don't ask again";
let chosen = await window.showInformationMessage(
"It seems that the Robot Framework Language Server extension is not installed to work with .robot Files.",
install,
dontAsk
);
if (chosen == install) {
commands.executeCommand("workbench.extensions.search", ROBOT_EXTENSION_ID);
} else if (chosen == dontAsk) {
roboConfig.setVerifylsp(false);
}
}
}
async function cloudLoginShowConfirmationAndRefresh() {
let loggedIn = await cloudLogin();
if (loggedIn) {
window.showInformationMessage("Successfully logged in Control Room.");
}
views.refreshCloudTreeView();
}
async function cloudLogoutAndRefresh() {
await cloudLogout();
views.refreshCloudTreeView();
}
interface RobocorpCodeCommandsOpts {
installErrorStubs: boolean;
}
function registerRobocorpCodeCommands(C: CommandRegistry, opts?: RobocorpCodeCommandsOpts) {
if (opts && opts.installErrorStubs) {
C.registerErrorStubs = true;
}
C.register(ROBOCORP_GET_LANGUAGE_SERVER_PYTHON, () => getLanguageServerPython());
C.register(ROBOCORP_GET_LANGUAGE_SERVER_PYTHON_INFO, () => getLanguageServerPythonInfo());
C.register(ROBOCORP_CREATE_ROBOT, () => createRobot());
C.register(ROBOCORP_UPLOAD_ROBOT_TO_CLOUD, () => uploadRobot());
C.register(ROBOCORP_CONFIGURATION_DIAGNOSTICS, () => rccConfigurationDiagnostics());
C.register(ROBOCORP_RUN_ROBOT_RCC, () => askAndRunRobotRCC(true));
C.register(ROBOCORP_DEBUG_ROBOT_RCC, () => askAndRunRobotRCC(false));
C.register(ROBOCORP_SET_PYTHON_INTERPRETER, () => setPythonInterpreterFromRobotYaml());
C.register(ROBOCORP_REFRESH_ROBOTS_VIEW, () => views.refreshTreeView(TREE_VIEW_ROBOCORP_ROBOTS_TREE));
C.register(ROBOCORP_REFRESH_CLOUD_VIEW, () => views.refreshCloudTreeView());
C.register(ROBOCORP_ROBOTS_VIEW_TASK_RUN, (entry: RobotEntry) => views.runSelectedRobot(true, entry));
C.register(ROBOCORP_ROBOTS_VIEW_TASK_DEBUG, (entry: RobotEntry) => views.runSelectedRobot(false, entry));
C.register(ROBOCORP_EDIT_ROBOCORP_INSPECTOR_LOCATOR, (locator?: LocatorEntry) =>
inspector.openRobocorpInspector(undefined, locator)
);
C.register(ROBOCORP_NEW_ROBOCORP_INSPECTOR_BROWSER, () => inspector.openRobocorpInspector("browser"));
C.register(ROBOCORP_NEW_ROBOCORP_INSPECTOR_IMAGE, () => inspector.openRobocorpInspector("image"));
C.register(ROBOCORP_COPY_LOCATOR_TO_CLIPBOARD_INTERNAL, (locator?: LocatorEntry) =>
copySelectedToClipboard(locator)
);
C.register(ROBOCORP_REMOVE_LOCATOR_FROM_JSON, (locator?: LocatorEntry) => removeLocator(locator));
C.register(ROBOCORP_OPEN_ROBOT_TREE_SELECTION, (robot: RobotEntry) => views.openRobotTreeSelection(robot));
C.register(ROBOCORP_CLOUD_UPLOAD_ROBOT_TREE_SELECTION, (robot: RobotEntry) =>
views.cloudUploadRobotTreeSelection(robot)
);
C.register(ROBOCORP_CREATE_RCC_TERMINAL_TREE_SELECTION, (robot: RobotEntry) =>
views.createRccTerminalTreeSelection(robot)
);
C.register(ROBOCORP_RCC_TERMINAL_NEW, () => askAndCreateRccTerminal());
C.register(ROBOCORP_REFRESH_ROBOT_CONTENT_VIEW, () => views.refreshTreeView(TREE_VIEW_ROBOCORP_ROBOT_CONTENT_TREE));
C.register(ROBOCORP_NEW_FILE_IN_ROBOT_CONTENT_VIEW, newFileInRobotContentTree);
C.register(ROBOCORP_NEW_FOLDER_IN_ROBOT_CONTENT_VIEW, newFolderInRobotContentTree);
C.register(ROBOCORP_DELETE_RESOURCE_IN_ROBOT_CONTENT_VIEW, deleteResourceInRobotContentTree);
C.register(ROBOCORP_RENAME_RESOURCE_IN_ROBOT_CONTENT_VIEW, renameResourceInRobotContentTree);
C.register(ROBOCORP_UPDATE_LAUNCH_ENV, updateLaunchEnvironment);
C.register(ROBOCORP_OPEN_CLOUD_HOME, () => {
commands.executeCommand("vscode.open", Uri.parse("https://cloud.robocorp.com/home"));
});
C.register(ROBOCORP_CONVERT_OUTPUT_WORK_ITEM_TO_INPUT, convertOutputWorkItemToInput);
C.register(ROBOCORP_CLOUD_LOGIN, () => cloudLoginShowConfirmationAndRefresh());
C.register(ROBOCORP_CLOUD_LOGOUT, () => cloudLogoutAndRefresh());
C.register(ROBOCORP_NEW_WORK_ITEM_IN_WORK_ITEMS_VIEW, newWorkItemInWorkItemsTree);
C.register(ROBOCORP_DELETE_WORK_ITEM_IN_WORK_ITEMS_VIEW, deleteWorkItemInWorkItemsTree);
C.register(ROBOCORP_HELP_WORK_ITEMS, openWorkItemHelp);
}
let langServer: LanguageClient;
export async function activate(context: ExtensionContext) {
let timing = new Timing();
// The first thing we need is the python executable.
OUTPUT_CHANNEL.appendLine("Activating Robocorp Code extension.");
let C = new CommandRegistry(context);
// Note: register the submit issue actions early on so that we can later actually
// report startup errors.
let logPath: string = context.logPath;
C.register(ROBOCORP_SUBMIT_ISSUE, () => {
submitIssueUI(logPath);
});
// i.e.: allow other extensions to also use our submit issue api.
C.register(
ROBOCORP_SUBMIT_ISSUE_INTERNAL,
(dialogMessage: string, email: string, errorName: string, errorCode: string, errorMessage: string) =>
submitIssue(
logPath, // gotten from plugin context
dialogMessage,
email,
errorName,
errorCode,
errorMessage
)
);
const extension = extensions.getExtension("robocorp.robotframework-lsp");
if (extension) {
// If the Robot Framework Language server is present, make sure it is compatible with this
// version.
try {
const version: string = extension.packageJSON.version;
const splitted = version.split(".");
const major = parseInt(splitted[0]);
const minor = parseInt(splitted[1]);
if (major == 0 && minor <= 20) {
const msg =
"Unable to initialize the Robocorp Code extension because the Robot Framework Language Server version (" +
version +
") is not compatible with this version of Robocorp Code. Robot Framework Language Server 0.21.0 or newer is required. Please update to proceed. ";
OUTPUT_CHANNEL.appendLine(msg);
registerRobocorpCodeCommands(C, { installErrorStubs: true });
notifyOfInitializationErrorShowOutputTab(msg);
return;
}
} catch (err) {
logError("Error verifying Robot Framework Language Server version.", err);
}
}
workspace.onDidChangeConfiguration((event) => {
for (let s of [
roboConfig.ROBOCORP_LANGUAGE_SERVER_ARGS,
roboConfig.ROBOCORP_LANGUAGE_SERVER_PYTHON,
roboConfig.ROBOCORP_LANGUAGE_SERVER_TCP_PORT,
]) {
if (event.affectsConfiguration(s)) {
window
.showWarningMessage(
'Please use the "Reload Window" action for changes in ' + s + " to take effect.",
...["Reload Window"]
)
.then((selection) => {
if (selection === "Reload Window") {
commands.executeCommand("workbench.action.reloadWindow");
}
});
return;
}
}
});
let executableAndEnv = await getLanguageServerPythonInfo();
if (!executableAndEnv) {
OUTPUT_CHANNEL.appendLine(
"Unable to activate Robocorp Code extension because python executable from RCC environment was not provided.\n" +
" -- Most common reason is that the environment couldn't be created due to network connectivity issues."
);
registerRobocorpCodeCommands(C, { installErrorStubs: true });
notifyOfInitializationErrorShowOutputTab();
return;
}
OUTPUT_CHANNEL.appendLine("Using python executable: " + executableAndEnv.pythonExe);
let startLsTiming = new Timing();
let port: number = roboConfig.getLanguageServerTcpPort();
if (port) {
// For TCP server needs to be started seperately
OUTPUT_CHANNEL.appendLine("Connecting to language server in port: " + port);
langServer = startLangServerTCP(port);
} else {
let targetFile: string = getExtensionRelativeFile("../../src/robocorp_code/__main__.py");
if (!targetFile) {
OUTPUT_CHANNEL.appendLine("Error resolving ../../src/robocorp_code/__main__.py");
registerRobocorpCodeCommands(C, { installErrorStubs: true });
notifyOfInitializationErrorShowOutputTab();
return;
}
let args: Array<string> = ["-u", targetFile];
let lsArgs = roboConfig.getLanguageServerArgs();
if (lsArgs) {
args = args.concat(lsArgs);
}
langServer = startLangServerIO(executableAndEnv.pythonExe, args, executableAndEnv.environ);
}
let stopListeningOnDidChangeState = langServer.onDidChangeState((event) => {
if (event.newState == State.Running) {
// i.e.: We need to register the customProgress as soon as it's running (we can't wait for onReady)
// because at that point if there are open documents, lots of things may've happened already, in
// which case the progress won't be shown on some cases where it should be shown.
context.subscriptions.push(
langServer.onNotification("$/customProgress", (args: ProgressReport) => {
// OUTPUT_CHANNEL.appendLine(args.id + ' - ' + args.kind + ' - ' + args.title + ' - ' + args.message + ' - ' + args.increment);
handleProgressMessage(args);
})
);
context.subscriptions.push(
langServer.onNotification("$/linkedAccountChanged", () => {
views.refreshCloudTreeView();
})
);
stopListeningOnDidChangeState.dispose();
}
});
let disposable: Disposable = langServer.start();
registerRobocorpCodeCommands(C);
views.registerViews(context);
registerDebugger(executableAndEnv.pythonExe);
context.subscriptions.push(disposable);
// i.e.: if we return before it's ready, the language server commands
// may not be available.
OUTPUT_CHANNEL.appendLine("Waiting for Robocorp Code (python) language server to finish activating...");
await langServer.onReady();
OUTPUT_CHANNEL.appendLine(
"Took: " + startLsTiming.getTotalElapsedAsStr() + " to initialize Robocorp Code Language Server."
);
OUTPUT_CHANNEL.appendLine("Robocorp Code extension ready. Took: " + timing.getTotalElapsedAsStr());
verifyRobotFrameworkInstalled();
}
export function deactivate(): Thenable<void> | undefined {
if (!langServer) {
return undefined;
}
return langServer.stop();
}
let _cachedPythonInfo: InterpreterInfo;
async function getLanguageServerPython(): Promise<string | undefined> {
let info = await getLanguageServerPythonInfo();
if (!info) {
return undefined;
}
return info.pythonExe;
}
export async function getLanguageServerPythonInfo(): Promise<InterpreterInfo | undefined> {
if (_cachedPythonInfo) {
return _cachedPythonInfo;
}
let cachedPythonInfo = await getLanguageServerPythonInfoUncached();
if (!cachedPythonInfo) {
return undefined; // Unable to get it.
}
// Ok, we got it (cache that info).
_cachedPythonInfo = cachedPythonInfo;
return _cachedPythonInfo;
}
async function enableWindowsLongPathSupport(rccLocation: string) {
try {
try {
// Expected failure if not admin.
await execFilePromise(rccLocation, ["configure", "longpaths", "--enable"], { env: { ...process.env } });
await sleep(100);
} catch (error) {
// Expected error (it means we need an elevated shell to run the command).
try {
// Now, at this point we resolve the links to have a canonical location, because
// we'll execute with a different user (i.e.: admin), we first resolve substs
// which may not be available for that user (i.e.: a subst can be applied to one
// account and not to the other) because path.resolve and fs.realPathSync don't
// seem to resolve substed drives, we do it manually here.
if (rccLocation.charAt(1) == ":") {
// Check that we're actually have a drive there.
try {
let resolved: string = fs.readlinkSync(rccLocation.charAt(0) + ":");
rccLocation = path.join(resolved, rccLocation.slice(2));
} catch (error) {
// ignore (it's not a link)
}
}
rccLocation = path.resolve(rccLocation);
rccLocation = fs.realpathSync(rccLocation);
} catch (error) {
OUTPUT_CHANNEL.appendLine("Error (handled) resolving rcc canonical location: " + error);
}
rccLocation = rccLocation.split("\\").join("/"); // escape for the shell execute
let result: ExecFileReturn = await execFilePromise(
"C:/Windows/System32/mshta.exe", // i.e.: Windows scripting
[
"javascript: var shell = new ActiveXObject('shell.application');" + // create a shell
"shell.ShellExecute('" +
rccLocation +
"', 'configure longpaths --enable', '', 'runas', 1);close();", // runas will run in elevated mode
],
{ env: { ...process.env } }
);
// Wait a second for the command to be executed as admin before proceeding.
await sleep(1000);
}
} catch (error) {
// Ignore here...
}
}
async function isLongPathSupportEnabledOnWindows(rccLocation: string): Promise<boolean> {
let enabled: boolean = true;
try {
let configureLongpathsOutput: ExecFileReturn = await execFilePromise(rccLocation, ["configure", "longpaths"], {
env: { ...process.env },
});
if (
configureLongpathsOutput.stdout.indexOf("OK.") != -1 ||
configureLongpathsOutput.stderr.indexOf("OK.") != -1
) {
enabled = true;
} else {
enabled = false;
}
} catch (error) {
enabled = false;
}
if (enabled) {
OUTPUT_CHANNEL.appendLine("Windows long paths support enabled");
} else {
OUTPUT_CHANNEL.appendLine("Windows long paths support NOT enabled.");
}
return enabled;
}
async function verifyLongPathSupportOnWindows(rccLocation: string): Promise<boolean> {
if (process.env.ROBOCORP_OVERRIDE_SYSTEM_REQUIREMENTS) {
// i.e.: When set we do not try to check (this flag makes "rcc configure longpaths"
// return an error).
return true;
}
if (process.platform == "win32") {
while (true) {
let enabled: boolean = await isLongPathSupportEnabledOnWindows(rccLocation);
if (!enabled) {
const YES = "Yes (requires elevated shell)";
const MANUALLY = "Open manual instructions";
let result = await window.showErrorMessage(
"Windows long paths support (required by Robocorp Code) is not enabled. Would you like to have Robocorp Code enable it now?",
{ "modal": true },
YES,
MANUALLY
// Auto-cancel in modal
);
if (result == YES) {
// Enable it.
await enableWindowsLongPathSupport(rccLocation);
let enabled = await isLongPathSupportEnabledOnWindows(rccLocation);
if (enabled) {
return true;
} else {
let result = await window.showErrorMessage(
"It was not possible to automatically enable windows long path support. " +
"Please follow the instructions from https://robocorp.com/docs/troubleshooting/windows-long-path (press Ok to open in browser).",
{ "modal": true },
"Ok"
// Auto-cancel in modal
);
if (result == "Ok") {
await env.openExternal(
Uri.parse("https://robocorp.com/docs/troubleshooting/windows-long-path")
);
}
}
} else if (result == MANUALLY) {
await env.openExternal(Uri.parse("https://robocorp.com/docs/troubleshooting/windows-long-path"));
} else {
// Cancel
OUTPUT_CHANNEL.appendLine(
"Extension will not be activated because Windows long paths support not enabled."
);
return false;
}
result = await window.showInformationMessage(
"Press Ok after Long Path support is manually enabled.",
{ "modal": true },
"Ok"
// Auto-cancel in modal
);
if (!result) {
OUTPUT_CHANNEL.appendLine(
"Extension will not be activated because Windows long paths support not enabled."
);
return false;
}
} else {
return true;
}
}
}
return true;
}
async function getLanguageServerPythonInfoUncached(): Promise<InterpreterInfo | undefined> {
let rccLocation = await getRccLocation();
if (!rccLocation) {
OUTPUT_CHANNEL.appendLine("Unable to get rcc executable location.");
return;
}
let robotYaml = getExtensionRelativeFile("../../bin/create_env/robot.yaml");
if (!robotYaml) {
OUTPUT_CHANNEL.appendLine("Unable to find: ../../bin/create_env/robot.yaml in extension.");
return;
}
let robotConda: string;
switch (process.platform) {
case "darwin":
robotConda = getExtensionRelativeFile("../../bin/create_env/conda_vscode_darwin_amd64.yaml");
break;
case "linux":
robotConda = getExtensionRelativeFile("../../bin/create_env/conda_vscode_linux_amd64.yaml");
break;
case "win32":
robotConda = getExtensionRelativeFile("../../bin/create_env/conda_vscode_windows_amd64.yaml");
break;
default:
robotConda = getExtensionRelativeFile("../../bin/create_env/conda.yaml");
break;
}
if (!robotConda) {
OUTPUT_CHANNEL.appendLine("Unable to find: ../../bin/create_env/conda.yaml in extension.");
return;
}
let getEnvInfoPy = getExtensionRelativeFile("../../bin/create_env/get_env_info.py");
if (!getEnvInfoPy) {
OUTPUT_CHANNEL.appendLine("Unable to find: ../../bin/create_env/get_env_info.py in extension.");
return;
}
/**
* @returns the result of running `get_env_info.py`.
*/
async function createDefaultEnv(
progress: Progress<{ message?: string; increment?: number }>
): Promise<ExecFileReturn> | undefined {
// Check that the user has long names enabled on windows.
if (!(await verifyLongPathSupportOnWindows(rccLocation))) {
return undefined;
}
// Check that ROBOCORP_HOME is valid (i.e.: doesn't have any spaces in it).
let robocorpHome: string = roboConfig.getHome();
if (!robocorpHome || robocorpHome.length == 0) {
robocorpHome = process.env["ROBOCORP_HOME"];
if (!robocorpHome) {
// Default from RCC (maybe it should provide an API to get it before creating an env?)
if (process.platform == "win32") {
robocorpHome = path.join(process.env.LOCALAPPDATA, "robocorp");
} else {
robocorpHome = path.join(process.env.HOME, ".robocorp");
}
}
}
OUTPUT_CHANNEL.appendLine("ROBOCORP_HOME: " + robocorpHome);
let rccDiagnostics: RCCDiagnostics | undefined = await runConfigDiagnostics(rccLocation, robocorpHome);
if (!rccDiagnostics) {
let msg = "There was an error getting RCC diagnostics. Robocorp Code will not be started!";
OUTPUT_CHANNEL.appendLine(msg);
window.showErrorMessage(msg);
return undefined;
}
while (!rccDiagnostics.isRobocorpHomeOk()) {
const SELECT_ROBOCORP_HOME = "Set new ROBOCORP_HOME";
const CANCEL = "Cancel";
let result = await window.showInformationMessage(
"The current ROBOCORP_HOME is invalid (paths with spaces/non ascii chars are not supported).",
SELECT_ROBOCORP_HOME,
CANCEL
);
if (!result || result == CANCEL) {
OUTPUT_CHANNEL.appendLine("Cancelled setting new ROBOCORP_HOME.");
return undefined;
}
let uriResult = await window.showOpenDialog({
"canSelectFolders": true,
"canSelectFiles": false,
"canSelectMany": false,
"openLabel": "Set as ROBOCORP_HOME",
});
if (!uriResult) {
OUTPUT_CHANNEL.appendLine("Cancelled getting ROBOCORP_HOME path.");
return undefined;
}
if (uriResult.length != 1) {
OUTPUT_CHANNEL.appendLine("Expected 1 path to set as ROBOCORP_HOME. Found: " + uriResult.length);
return undefined;
}
robocorpHome = uriResult[0].fsPath;
rccDiagnostics = await runConfigDiagnostics(rccLocation, robocorpHome);
if (!rccDiagnostics) {
let msg = "There was an error getting RCC diagnostics. Robocorp Code will not be started!";
OUTPUT_CHANNEL.appendLine(msg);
window.showErrorMessage(msg);
return undefined;
}
if (rccDiagnostics.isRobocorpHomeOk()) {
OUTPUT_CHANNEL.appendLine("Selected ROBOCORP_HOME: " + robocorpHome);
let config = workspace.getConfiguration("robocorp");
await config.update("home", robocorpHome, ConfigurationTarget.Global);
}
}
function createOpenUrl(failedCheck) {
return (value) => {
if (value == "Open troubleshoot URL") {
env.openExternal(Uri.parse(failedCheck.url));
}
};
}
let canProceed: boolean = true;
for (const failedCheck of rccDiagnostics.failedChecks) {
if (failedCheck.status == STATUS_FATAL) {
canProceed = false;
}
let func = window.showErrorMessage;
if (failedCheck.status == STATUS_WARNING) {
func = window.showWarningMessage;
}
if (failedCheck.url) {
func(failedCheck.message, "Open troubleshoot URL").then(createOpenUrl(failedCheck));
} else {
func(failedCheck.message);
}
}
if (!canProceed) {
return undefined;
}
progress.report({ message: "Update env (may take a few minutes)." });
// Get information on a base package with our basic dependencies (this can take a while...).
let rccEnvPromise = collectBaseEnv(robotConda, robocorpHome);
let timing = new Timing();
let finishedCondaRun = false;
let onFinish = function () {
finishedCondaRun = true;
};
rccEnvPromise.then(onFinish, onFinish);
// Busy async loop so that we can show the elapsed time.
while (true) {
await sleep(93); // Strange sleep so it's not always a .0 when showing ;)
if (finishedCondaRun) {
break;
}
if (timing.elapsedFromLastMeasurement(5000)) {
progress.report({
message: "Update env (may take a few minutes). " + timing.getTotalElapsedAsStr() + " elapsed.",
});
}
}
let envResult = await rccEnvPromise;
OUTPUT_CHANNEL.appendLine("Took: " + timing.getTotalElapsedAsStr() + " to update conda env.");
if (!envResult) {
OUTPUT_CHANNEL.appendLine("Error creating conda env.");
return undefined;
}
// Ok, we now have the holotree space created and just collected the environment variables. Let's now do
// a raw python run with that information to collect information from python.
let pythonExe = envResult.env["PYTHON_EXE"];
if (!pythonExe) {
OUTPUT_CHANNEL.appendLine("Error: PYTHON_EXE not available in the holotree environment.");
return undefined;
}
let pythonTiming = new Timing();
let resultPromise: Promise<ExecFileReturn> = execFilePromise(pythonExe, [getEnvInfoPy], { env: envResult.env });
let finishedPythonRun = false;
let onFinishPython = function () {
finishedPythonRun = true;
};
resultPromise.then(onFinishPython, onFinishPython);
// Busy async loop so that we can show the elapsed time.
while (true) {
await sleep(93); // Strange sleep so it's not always a .0 when showing ;)
if (finishedPythonRun) {
break;
}
if (timing.elapsedFromLastMeasurement(5000)) {
progress.report({ message: "Collecting env info. " + timing.getTotalElapsedAsStr() + " elapsed." });
}
}
let ret = await resultPromise;
OUTPUT_CHANNEL.appendLine("Took: " + pythonTiming.getTotalElapsedAsStr() + " to collect python info.");
return ret;
}
let result: ExecFileReturn | undefined = await window.withProgress(
{
location: ProgressLocation.Notification,
title: "Robocorp",
cancellable: false,
},
createDefaultEnv
);
function disabled(msg: string): undefined {
msg = "Robocorp Code extension disabled. Reason: " + msg;
OUTPUT_CHANNEL.appendLine(msg);
window.showErrorMessage(msg);
return undefined;
}
if (!result) {
return disabled("Unable to get python to launch language server.");
}
try {
let jsonContents = result.stderr;
let start: number = jsonContents.indexOf("JSON START>>");
let end: number = jsonContents.indexOf("<<JSON END");
if (start == -1 || end == -1) {
throw Error("Unable to find JSON START>> or <<JSON END");
}
start += "JSON START>>".length;
jsonContents = jsonContents.substr(start, end - start);
let contents: object = JSON.parse(jsonContents);
let pythonExe = contents["python_executable"];
OUTPUT_CHANNEL.appendLine("Python executable: " + pythonExe);
OUTPUT_CHANNEL.appendLine("Python version: " + contents["python_version"]);
OUTPUT_CHANNEL.appendLine("Robot Version: " + contents["robot_version"]);
let env = contents["environment"];
if (!env) {
OUTPUT_CHANNEL.appendLine("Environment: NOT received");
} else {
// Print some env vars we may care about:
OUTPUT_CHANNEL.appendLine("Environment:");
OUTPUT_CHANNEL.appendLine(" PYTHONPATH: " + env["PYTHONPATH"]);
OUTPUT_CHANNEL.appendLine(" APPDATA: " + env["APPDATA"]);
OUTPUT_CHANNEL.appendLine(" HOMEDRIVE: " + env["HOMEDRIVE"]);
OUTPUT_CHANNEL.appendLine(" HOMEPATH: " + env["HOMEPATH"]);
OUTPUT_CHANNEL.appendLine(" HOME: " + env["HOME"]);
OUTPUT_CHANNEL.appendLine(" ROBOT_ROOT: " + env["ROBOT_ROOT"]);
OUTPUT_CHANNEL.appendLine(" ROBOT_ARTIFACTS: " + env["ROBOT_ARTIFACTS"]);
OUTPUT_CHANNEL.appendLine(" RCC_INSTALLATION_ID: " + env["RCC_INSTALLATION_ID"]);
OUTPUT_CHANNEL.appendLine(" ROBOCORP_HOME: " + env["ROBOCORP_HOME"]);
OUTPUT_CHANNEL.appendLine(" PROCESSOR_ARCHITECTURE: " + env["PROCESSOR_ARCHITECTURE"]);
OUTPUT_CHANNEL.appendLine(" OS: " + env["OS"]);
OUTPUT_CHANNEL.appendLine(" PATH: " + env["PATH"]);
}
if (verifyFileExists(pythonExe)) {
return {
pythonExe: pythonExe,
environ: contents["environment"],
additionalPythonpathEntries: [],
};
}
return disabled("Python executable: " + pythonExe + " does not exist.");
} catch (error) {
return disabled(
"Unable to get python to launch language server.\nStderr: " +
result.stderr +
"\nStdout (json contents): " +
result.stdout
);
}
} | the_stack |
import { EmbeddedActionsParser, ILexingError, IOrAlt, IRecognitionException, IToken, Lexer, TokenType } from 'chevrotain';
import { AbstractElement, Action, Assignment, isAssignment, isCrossReference } from '../grammar/generated/ast';
import { Linker } from '../references/linker';
import { LangiumServices } from '../services';
import { AstNode, CompositeCstNode, CstNode, LeafCstNode } from '../syntax-tree';
import { getContainerOfType, linkContentToContainer } from '../utils/ast-util';
import { tokenToRange } from '../utils/cst-util';
import { CompositeCstNodeImpl, CstNodeBuilder, LeafCstNodeImpl, RootCstNodeImpl } from './cst-node-builder';
import { IParserConfig } from './parser-config';
import { ValueConverter } from './value-converter';
export type ParseResult<T = AstNode> = {
value: T,
parserErrors: IRecognitionException[],
lexerErrors: ILexingError[]
}
export const DatatypeSymbol = Symbol('Datatype');
type RuleResult = () => any;
type Args = Record<string, boolean>;
type RuleImpl = (args: Args) => any;
type Alternatives = Array<IOrAlt<any>>;
interface AssignmentElement {
assignment?: Assignment
crossRef: boolean
}
export class LangiumParser {
private readonly linker: Linker;
private readonly converter: ValueConverter;
private readonly lexer: Lexer;
private readonly nodeBuilder = new CstNodeBuilder();
private readonly wrapper: ChevrotainWrapper;
private stack: any[] = [];
private mainRule!: RuleResult;
private assignmentMap = new Map<AbstractElement, AssignmentElement | undefined>();
private get current(): any {
return this.stack[this.stack.length - 1];
}
constructor(services: LangiumServices, tokens: TokenType[]) {
this.wrapper = new ChevrotainWrapper(tokens, services.parser.ParserConfig);
this.linker = services.references.Linker;
this.converter = services.parser.ValueConverter;
this.lexer = new Lexer(tokens);
}
MAIN_RULE(
name: string,
type: string | symbol | undefined,
implementation: RuleImpl
): RuleResult {
return this.mainRule = this.DEFINE_RULE(name, type, implementation);
}
DEFINE_RULE(
name: string,
type: string | symbol | undefined,
implementation: RuleImpl
): RuleResult {
return this.wrapper.DEFINE_RULE(name, this.startImplementation(type, implementation).bind(this));
}
parse<T extends AstNode = AstNode>(input: string): ParseResult<T> {
this.nodeBuilder.buildRootNode(input);
const lexerResult = this.lexer.tokenize(input);
this.wrapper.input = lexerResult.tokens;
const result = this.mainRule.call(this.wrapper);
this.addHiddenTokens(result.$cstNode, lexerResult.groups.hidden);
return {
value: result,
lexerErrors: lexerResult.errors,
parserErrors: this.wrapper.errors
};
}
private addHiddenTokens(node: RootCstNodeImpl, tokens?: IToken[]): void {
if (tokens) {
for (const token of tokens) {
const hiddenNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, true);
hiddenNode.root = node;
this.addHiddenToken(node, hiddenNode);
}
}
}
private addHiddenToken(node: CompositeCstNode, token: LeafCstNode): void {
const { offset, end } = node;
const { offset: tokenStart, end: tokenEnd } = token;
if (offset >= tokenEnd) {
node.children.unshift(token);
} else if (end <= tokenStart) {
node.children.push(token);
} else {
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
const childEnd = child.end;
if (child instanceof CompositeCstNodeImpl && tokenEnd < childEnd) {
this.addHiddenToken(child, token);
return;
} else if (tokenEnd <= child.offset) {
node.children.splice(i, 0, token);
return;
}
}
}
}
private startImplementation($type: string | symbol | undefined, implementation: RuleImpl): RuleImpl {
return (args) => {
if (!this.wrapper.IS_RECORDING) {
this.stack.push({ $type });
}
let result: unknown;
try {
result = implementation(args);
} catch (err) {
console.log('Parser exception thrown!', err);
result = undefined;
}
if (!this.wrapper.IS_RECORDING && result === undefined) {
result = this.construct();
}
return result;
};
}
alternatives(idx: number, choices: Alternatives): void {
this.wrapper.wrapOr(idx, choices);
}
optional(idx: number, callback: () => void): void {
this.wrapper.wrapOption(idx, callback);
}
many(idx: number, callback: () => void): void {
this.wrapper.wrapMany(idx, callback);
}
atLeastOne(idx: number, callback: () => void): void {
this.wrapper.wrapAtLeastOne(idx, callback);
}
consume(idx: number, tokenType: TokenType, feature: AbstractElement): void {
const token = this.wrapper.wrapConsume(idx, tokenType);
if (!this.wrapper.IS_RECORDING) {
const leafNode = this.nodeBuilder.buildLeafNode(token, feature);
const { assignment, crossRef } = this.getAssignment(feature);
if (assignment) {
let crossRefId: string | undefined;
if (crossRef) {
crossRefId = `${this.current.$type}:${assignment.feature}`;
}
this.assign(assignment, token.image, leafNode, crossRefId);
}
}
}
unassignedSubrule(idx: number, rule: RuleResult, feature: AbstractElement, args: Args): void {
const result = this.subrule(idx, rule, feature, args);
if (!this.wrapper.IS_RECORDING) {
const resultKind = result.$type;
const object = this.assignWithoutOverride(result, this.current);
if (resultKind) {
object.$type = resultKind;
}
const newItem = object;
this.stack.pop();
this.stack.push(newItem);
}
}
subrule(idx: number, rule: RuleResult, feature: AbstractElement, args: Args): any {
let cstNode: CompositeCstNode | undefined;
if (!this.wrapper.IS_RECORDING) {
cstNode = this.nodeBuilder.buildCompositeNode(feature);
}
const subruleResult = this.wrapper.wrapSubrule(idx, rule, args);
if (!this.wrapper.IS_RECORDING) {
const { assignment, crossRef } = this.getAssignment(feature);
if (assignment && cstNode) {
let crossRefId: string | undefined;
if (crossRef) {
crossRefId = `${this.current.$type}:${assignment.feature}`;
}
this.assign(assignment, subruleResult, cstNode, crossRefId);
}
}
return subruleResult;
}
action($type: string, action: Action): void {
if (!this.wrapper.IS_RECORDING) {
let last = this.current;
// This branch is used for left recursive grammar rules.
// Those don't call `construct` before another action.
// Therefore, we need to call it here.
if (!last.$cstNode && action.feature && action.operator) {
last = this.construct(false);
const feature = last.$cstNode.feature;
this.nodeBuilder.buildCompositeNode(feature);
}
const newItem = { $type };
this.stack.pop();
this.stack.push(newItem);
if (action.feature && action.operator) {
this.assign(action, last, last.$cstNode);
}
}
}
/**
* Initializes array fields of the current object. Array fields are not allowed to be undefined.
* Therefore, all array fields are initialized with an empty array.
* @param initialArrayProperties The grammar access element that belongs to the current rule
*/
initializeElement(initialArrayProperties: string[]): void {
if (!this.wrapper.IS_RECORDING) {
const item = this.current;
for (const element of initialArrayProperties) {
item[element] = [];
}
}
}
construct(pop = true): unknown {
if (this.wrapper.IS_RECORDING) {
return undefined;
}
const obj = this.current;
linkContentToContainer(obj);
this.nodeBuilder.construct(obj);
if (pop) {
this.stack.pop();
}
if (obj.$type === DatatypeSymbol) {
const node = obj.$cstNode;
return node.text;
}
return obj;
}
private getAssignment(feature: AbstractElement): AssignmentElement {
if (!this.assignmentMap.has(feature)) {
const assignment = getContainerOfType(feature, isAssignment);
this.assignmentMap.set(feature, {
assignment: assignment,
crossRef: assignment ? isCrossReference(assignment.terminal) : false
});
}
return this.assignmentMap.get(feature)!;
}
private assign(assignment: { operator: string, feature: string }, value: unknown, cstNode: CstNode, crossRefId?: string): void {
const obj = this.current;
const feature = assignment.feature.replace(/\^/g, '');
let item: unknown;
if (crossRefId && typeof value === 'string') {
const refText = cstNode ? this.converter.convert(value, cstNode).toString() : value;
item = this.linker.buildReference(obj, cstNode, crossRefId, refText);
} else if (cstNode && typeof value === 'string') {
item = this.converter.convert(value, cstNode);
} else {
item = value;
}
switch (assignment.operator) {
case '=': {
obj[feature] = item;
break;
}
case '?=': {
obj[feature] = true;
break;
}
case '+=': {
if (!Array.isArray(obj[feature])) {
obj[feature] = [];
}
obj[feature].push(item);
}
}
}
private assignWithoutOverride(target: any, source: any): any {
for (const [name, value] of Object.entries(source)) {
if (target[name] === undefined) {
target[name] = value;
}
}
return target;
}
finalize(): void {
this.wrapper.wrapSelfAnalysis();
}
}
const defaultConfig: IParserConfig = {
recoveryEnabled: true,
nodeLocationTracking: 'full',
skipValidations: true
};
/**
* This class wraps the embedded actions parser of chevrotain and exposes protected methods.
* This way, we can build the `LangiumParser` as a composition.
*/
class ChevrotainWrapper extends EmbeddedActionsParser {
constructor(tokens: TokenType[], config?: IParserConfig) {
super(tokens, {
...defaultConfig,
...config
});
}
get IS_RECORDING(): boolean {
return this.RECORDING_PHASE;
}
DEFINE_RULE(name: string, impl: RuleImpl): RuleResult {
return this.RULE(name, impl);
}
wrapSelfAnalysis(): void {
this.performSelfAnalysis();
}
wrapConsume(idx: number, tokenType: TokenType): IToken {
return this.consume(idx, tokenType);
}
wrapSubrule(idx: number, rule: RuleResult, args: Args): unknown {
return this.subrule(idx, rule, {
ARGS: [args]
});
}
wrapOr(idx: number, choices: Alternatives): void {
this.or(idx, choices);
}
wrapOption(idx: number, callback: () => void): void {
this.option(idx, callback);
}
wrapMany(idx: number, callback: () => void): void {
this.many(idx, callback);
}
wrapAtLeastOne(idx: number, callback: () => void): void {
this.atLeastOne(idx, callback);
}
} | the_stack |
import { UpdateableNetwork } from "../core/interfaces/contract";
import { IERC20, Split as SplitContract } from "contracts";
import { ContractWrapper } from "../core/classes/contract-wrapper";
import { ContractInterceptor } from "../core/classes/contract-interceptor";
import { IStorage } from "../core/interfaces/IStorage";
import { NetworkOrSignerOrProvider, TransactionResult } from "../core/types";
import { ContractMetadata } from "../core/classes/contract-metadata";
import { ContractEncoder } from "../core/classes/contract-encoder";
import { SDKOptions } from "../schema/sdk-options";
import { CurrencyValue } from "../types/currency";
import { fetchCurrencyValue } from "../common/currency";
import { BigNumber, Contract } from "ethers";
import { SplitRecipient } from "../types/SplitRecipient";
import { SplitsContractSchema } from "../schema/contracts/splits";
import { GasCostEstimator } from "../core/classes/gas-cost-estimator";
import { ContractEvents } from "../core/classes/contract-events";
import ERC20Abi from "../../abis/IERC20.json";
import { ContractAnalytics } from "../core/classes/contract-analytics";
/**
* Create custom royalty splits to distribute funds.
*
* @example
*
* ```javascript
* import { ThirdwebSDK } from "@thirdweb-dev/sdk";
*
* const sdk = new ThirdwebSDK("rinkeby");
* const contract = sdk.getSplit("{{contract_address}}");
* ```
*
* @public
*/
export class Split implements UpdateableNetwork {
static contractType = "split" as const;
static contractAbi = require("../../abis/Split.json");
/**
* @internal
*/
static schema = SplitsContractSchema;
private contractWrapper: ContractWrapper<SplitContract>;
private storage: IStorage;
public metadata: ContractMetadata<SplitContract, typeof Split.schema>;
public encoder: ContractEncoder<SplitContract>;
public estimator: GasCostEstimator<SplitContract>;
public events: ContractEvents<SplitContract>;
/**
* @internal
*/
public interceptor: ContractInterceptor<SplitContract>;
/**
* @internal
*/
public analytics: ContractAnalytics<SplitContract>;
constructor(
network: NetworkOrSignerOrProvider,
address: string,
storage: IStorage,
options: SDKOptions = {},
contractWrapper = new ContractWrapper<SplitContract>(
network,
address,
Split.contractAbi,
options,
),
) {
this.contractWrapper = contractWrapper;
this.storage = storage;
this.metadata = new ContractMetadata(
this.contractWrapper,
Split.schema,
this.storage,
);
this.analytics = new ContractAnalytics(this.contractWrapper);
this.encoder = new ContractEncoder(this.contractWrapper);
this.estimator = new GasCostEstimator(this.contractWrapper);
this.events = new ContractEvents(this.contractWrapper);
this.interceptor = new ContractInterceptor(this.contractWrapper);
}
onNetworkUpdated(network: NetworkOrSignerOrProvider) {
this.contractWrapper.updateSignerOrProvider(network);
}
getAddress(): string {
return this.contractWrapper.readContract.address;
}
/** ******************************
* READ FUNCTIONS
*******************************/
/**
* Get Recipients of this splits contract
*
* @remarks Get the data about the shares of every split recipient on the contract
*
* @example
* ```javascript
* const recipients = await contract.getAllRecipients();
* console.log(recipients);
* ```
*/
public async getAllRecipients(): Promise<SplitRecipient[]> {
const recipients: SplitRecipient[] = [];
let index = BigNumber.from(0);
const totalRecipients =
await this.contractWrapper.readContract.payeeCount();
while (index.lt(totalRecipients)) {
try {
const recipientAddress = await this.contractWrapper.readContract.payee(
index,
);
recipients.push(
await this.getRecipientSplitPercentage(recipientAddress),
);
index = index.add(1);
} catch (err: any) {
// The only way we know how to detect that we've found all recipients
// is if we get an error when trying to get the next recipient.
if (
"method" in err &&
(err["method"] as string).toLowerCase().includes("payee(uint256)")
) {
break;
} else {
throw err;
}
}
}
return recipients;
}
/**
* Returns all the recipients and their balances in the native currency.
*
* @returns A map of recipient addresses to their balances in the native currency.
*/
public async balanceOfAllRecipients() {
const recipients = await this.getAllRecipients();
const balances: { [key: string]: BigNumber } = {};
for (const recipient of recipients) {
balances[recipient.address] = await this.balanceOf(recipient.address);
}
return balances;
}
/**
* Returns all the recipients and their balances in a non-native currency.
*
* @param tokenAddress - The address of the currency to check the balances in.
* @returns A map of recipient addresses to their balances in the specified currency.
*/
public async balanceOfTokenAllRecipients(tokenAddress: string) {
const recipients = await this.getAllRecipients();
const balances: { [key: string]: CurrencyValue } = {};
for (const recipient of recipients) {
balances[recipient.address] = await this.balanceOfToken(
recipient.address,
tokenAddress,
);
}
return balances;
}
/**
* Get Funds owed to a particular wallet
*
* @remarks Get the amount of funds in the native currency held by the contract that is owed to a specific recipient.
*
* @example
* ```javascript
* // The address to check the funds of
* const address = "{{wallet_address}}";
* const funds = await contract.balanceOf(address);
* console.log(funds);
* ```
*/
public async balanceOf(address: string): Promise<BigNumber> {
const walletBalance =
await this.contractWrapper.readContract.provider.getBalance(
this.getAddress(),
);
const totalReleased = await this.contractWrapper.readContract[
"totalReleased()"
]();
const totalReceived = walletBalance.add(totalReleased);
return this._pendingPayment(
address,
totalReceived,
await this.contractWrapper.readContract["released(address)"](address),
);
}
/**
* Get non-native Token Funds owed to a particular wallet
*
* @remarks Get the amount of funds in the non-native tokens held by the contract that is owed to a specific recipient.
*
* @example
* ```javascript
* // The address to check the funds of
* const address = "{{wallet_address}}";
* // The address of the currency to check the contracts funds of
* const tokenAddress = "0x..."
* const funds = await contract.balanceOfToken(address, tokenAddress);
* console.log(funds);
* ```
*/
public async balanceOfToken(
walletAddress: string,
tokenAddress: string,
): Promise<CurrencyValue> {
const erc20 = new Contract(
tokenAddress,
ERC20Abi,
this.contractWrapper.getProvider(),
) as IERC20;
const walletBalance = await erc20.balanceOf(this.getAddress());
const totalReleased = await this.contractWrapper.readContract[
"totalReleased(address)"
](tokenAddress);
const totalReceived = walletBalance.add(totalReleased);
const value = await this._pendingPayment(
walletAddress,
totalReceived,
await this.contractWrapper.readContract["released(address,address)"](
tokenAddress,
walletAddress,
),
);
return await fetchCurrencyValue(
this.contractWrapper.getProvider(),
tokenAddress,
value,
);
}
/**
* Get the % of funds owed to a given address
* @param address - the address to check percentage of
*/
public async getRecipientSplitPercentage(
address: string,
): Promise<SplitRecipient> {
const [totalShares, walletsShares] = await Promise.all([
this.contractWrapper.readContract.totalShares(),
this.contractWrapper.readContract.shares(address),
]);
// We convert to basis points to avoid floating point loss of precision
return {
address,
splitPercentage:
walletsShares.mul(BigNumber.from(1e7)).div(totalShares).toNumber() /
1e5,
};
}
/** ******************************
* WRITE FUNCTIONS
*******************************/
/**
* Withdraw Funds
* @remarks Triggers a transfer to account of the amount of native currency they are owed.
*
* @example
* ```javascript
* // the wallet address that wants to withdraw their funds
* const walletAddress = "{{wallet_address}}"
* await contract.withdraw(walletAddress);
* ```
*
* @param walletAddress - The address to distributes the amount to
*/
public async withdraw(walletAddress: string): Promise<TransactionResult> {
return {
receipt: await this.contractWrapper.sendTransaction("release(address)", [
walletAddress,
]),
};
}
/**
* Triggers a transfer to account of the amount of a given currency they are owed.
*
* @param walletAddress - The address to distributes the amount to
* @param tokenAddress - The address of the currency contract to distribute funds
*/
public async withdrawToken(
walletAddress: string,
tokenAddress: string,
): Promise<TransactionResult> {
return {
receipt: await this.contractWrapper.sendTransaction(
"release(address,address)",
[tokenAddress, walletAddress],
),
};
}
/**
* Distribute Funds
*
* @remarks Distribute funds held by the contract in the native currency to all recipients.
*
* @example
* ```javascript
* await contract.distribute();
* ```
*/
public async distribute(): Promise<TransactionResult> {
return {
receipt: await this.contractWrapper.sendTransaction("distribute()", []),
};
}
/**
* Distribute Funds
*
* @remarks Distribute funds held by the contract in the native currency to all recipients.
*
* @example
* ```javascript
* // The address of the currency to distribute funds
* const tokenAddress = "0x..."
* await contract.distributeToken(tokenAddress);
* ```
*
* @param tokenAddress - The address of the currency contract to distribute funds
*/
public async distributeToken(
tokenAddress: string,
): Promise<TransactionResult> {
return {
receipt: await this.contractWrapper.sendTransaction(
"distribute(address)",
[tokenAddress],
),
};
}
/** ******************************
* PRIVATE FUNCTIONS
*******************************/
private async _pendingPayment(
address: string,
totalReceived: BigNumber,
alreadyReleased: BigNumber,
): Promise<BigNumber> {
const addressReceived = totalReceived.mul(
await this.contractWrapper.readContract.shares(address),
);
const totalRoyaltyAvailable = addressReceived.div(
await this.contractWrapper.readContract.totalShares(),
);
return totalRoyaltyAvailable.sub(alreadyReleased);
}
} | the_stack |
import { Localized } from "@fluent/react/compat";
import cn from "classnames";
import key from "keymaster";
import { noop } from "lodash";
import React, {
FunctionComponent,
useCallback,
useEffect,
useMemo,
useRef,
} from "react";
import { MediaContainer } from "coral-admin/components/MediaContainer";
import { HOTKEYS } from "coral-admin/constants";
import { GQLWordlistMatch } from "coral-framework/schema";
import { PropTypesOf } from "coral-framework/types";
import {
Button,
ButtonIcon,
Card,
Flex,
HorizontalGutter,
Icon,
TextLink,
Timestamp,
} from "coral-ui/components/v2";
import { StarRating } from "coral-ui/components/v3";
import { CommentContent, InReplyTo, UsernameButton } from "../Comment";
import ApproveButton from "./ApproveButton";
import CommentAuthorContainer from "./CommentAuthorContainer";
import FeatureButton from "./FeatureButton";
import MarkersContainer from "./MarkersContainer";
import RejectButton from "./RejectButton";
import styles from "./ModerateCard.css";
interface Props {
id: string;
username: string;
createdAt: string;
body: string;
highlight?: boolean;
inReplyTo?: {
id: string;
username: string | null;
} | null;
comment: PropTypesOf<typeof MarkersContainer>["comment"] &
PropTypesOf<typeof CommentAuthorContainer>["comment"] &
PropTypesOf<typeof MediaContainer>["comment"];
settings: PropTypesOf<typeof MarkersContainer>["settings"];
status: "approved" | "rejected" | "undecided";
featured: boolean;
moderatedBy: React.ReactNode | null;
viewContextHref: string;
showStory: boolean;
storyTitle?: React.ReactNode;
storyHref?: string;
siteName: string | null;
onModerateStory?: React.EventHandler<React.MouseEvent>;
onApprove: () => void;
onReject: () => void;
onFeature: () => void;
onUsernameClick: (id?: string) => void;
onConversationClick: (() => void) | null;
onFocusOrClick: () => void;
mini?: boolean;
hideUsername?: boolean;
selected?: boolean;
/**
* If set to true, it means this comment is about to be removed
* from the queue. This will trigger some styling changes to
* reflect that
*/
dangling?: boolean;
deleted?: boolean;
/**
* If set to true, it means that this comment cannot be moderated by the
* current user.
*/
readOnly?: boolean;
edited: boolean;
selectPrev?: () => void;
selectNext?: () => void;
onBan: () => void;
isQA?: boolean;
rating?: number | null;
bannedWords?: Readonly<Readonly<GQLWordlistMatch>[]>;
suspectWords?: Readonly<Readonly<GQLWordlistMatch>[]>;
isArchived?: boolean;
isArchiving?: boolean;
}
const ModerateCard: FunctionComponent<Props> = ({
id,
username,
createdAt,
body,
highlight = false,
inReplyTo,
comment,
settings,
rating,
viewContextHref,
status,
featured,
onApprove,
onReject,
onFeature,
onUsernameClick,
dangling,
showStory,
storyTitle,
storyHref,
onModerateStory,
siteName,
moderatedBy,
selected,
onFocusOrClick,
onConversationClick,
mini = false,
hideUsername = false,
deleted = false,
readOnly = false,
edited,
selectNext,
selectPrev,
onBan,
isQA,
bannedWords,
suspectWords,
isArchived,
isArchiving,
}) => {
const div = useRef<HTMLDivElement>(null);
useEffect(() => {
if (selected) {
if (selectNext) {
key(HOTKEYS.NEXT, id, selectNext);
}
if (selectPrev) {
key(HOTKEYS.PREV, id, selectPrev);
}
if (onBan) {
key(HOTKEYS.BAN, id, onBan);
}
key(HOTKEYS.APPROVE, id, onApprove);
key(HOTKEYS.REJECT, id, onReject);
// The the scope such that only events attached to the ${id} scope will
// be honored.
key.setScope(id);
return () => {
// Remove all events that are set in the ${id} scope.
key.deleteScope(id);
};
} else {
// Remove all events that were set in the ${id} scope.
key.deleteScope(id);
}
return noop;
}, [selected, id, selectNext, selectPrev, onBan, onApprove, onReject]);
useEffect(() => {
if (selected && div && div.current) {
div.current.focus();
}
}, [selected, div]);
const commentBody = useMemo(
() =>
deleted ? (
<Localized id="moderate-comment-deleted-body">
<div className={styles.deleted}>
This comment is no longer available. The commenter has deleted their
account.
</div>
</Localized>
) : (
body
),
[deleted, body]
);
const commentAuthorClick = useCallback(() => {
onUsernameClick();
}, [onUsernameClick]);
const commentParentAuthorClick = useCallback(() => {
if (inReplyTo) {
onUsernameClick(inReplyTo.id);
}
}, [onUsernameClick, inReplyTo]);
return (
<Card
className={cn(
styles.root,
{ [styles.borderless]: mini },
{ [styles.dangling]: dangling },
{ [styles.deleted]: deleted },
{ [styles.selected]: selected }
)}
ref={div}
tabIndex={0}
data-testid={`moderate-comment-${id}`}
id={`moderate-comment-${id}`}
onClick={onFocusOrClick}
>
<Flex>
<div className={styles.mainContainer}>
<div
className={cn(styles.topBar, {
[styles.topBarMini]: mini && !inReplyTo,
})}
>
<Flex alignItems="center">
{!hideUsername && username && (
<>
<UsernameButton
username={username}
onClick={commentAuthorClick}
/>
<CommentAuthorContainer comment={comment} />
</>
)}
<Timestamp>{createdAt}</Timestamp>
{edited && (
<Localized id="moderate-comment-edited">
<span className={styles.edited}>(edited)</span>
</Localized>
)}
<FeatureButton
featured={featured}
onClick={onFeature}
enabled={!deleted && !isQA && !readOnly}
/>
</Flex>
{inReplyTo && inReplyTo.username && (
<div className={styles.inReplyTo}>
<InReplyTo onUsernameClick={commentParentAuthorClick}>
{inReplyTo.username}
</InReplyTo>
</div>
)}
</div>
{rating && (
<div className={styles.ratingsArea}>
<StarRating rating={rating} />
</div>
)}
<div className={styles.contentArea}>
<div className={styles.content}>
<CommentContent
highlight={highlight}
bannedWords={bannedWords}
suspectWords={suspectWords}
>
{commentBody}
</CommentContent>
<MediaContainer comment={comment} />
</div>
{onConversationClick && (
<div className={styles.viewContext}>
<Button iconLeft variant="text" onClick={onConversationClick}>
<ButtonIcon>question_answer</ButtonIcon>
<Localized id="moderate-comment-viewConversation">
<span>View conversation</span>
</Localized>
</Button>
</div>
)}
<div
className={cn(styles.separator, {
[styles.ruledSeparator]: !mini,
})}
/>
</div>
<div className={styles.footer}>
<HorizontalGutter spacing={3}>
{showStory && (
<div>
<div className={styles.storyLabel}>
<Localized id="moderate-comment-storyLabel">
<span>Comment on</span>
</Localized>
<span>:</span>
</div>
<div className={styles.commentOn}>
{siteName && (
<span className={styles.siteName}>
{siteName}
<Icon>keyboard_arrow_right</Icon>
</span>
)}
<span className={styles.storyTitle}>{storyTitle}</span>
</div>
<div>
<Localized id="moderate-comment-moderateStory">
<TextLink
href={storyHref}
onClick={onModerateStory}
className={styles.link}
>
Moderate Story
</TextLink>
</Localized>
</div>
</div>
)}
<MarkersContainer
onUsernameClick={onUsernameClick}
comment={comment}
settings={settings}
/>
</HorizontalGutter>
</div>
</div>
<Flex
className={cn(styles.aside, {
[styles.asideWithoutReplyTo]: !inReplyTo,
[styles.asideMini]: mini && !inReplyTo,
[styles.asideMiniWithReplyTo]:
mini && inReplyTo && inReplyTo.username,
})}
alignItems="center"
direction="column"
itemGutter
>
{!mini && (
<Localized id="moderate-comment-decision">
<div className={styles.decision}>DECISION</div>
</Localized>
)}
<Flex itemGutter>
<RejectButton
onClick={onReject}
invert={status === "rejected"}
disabled={
status === "rejected" ||
dangling ||
deleted ||
readOnly ||
isArchived ||
isArchiving
}
readOnly={readOnly}
className={cn({
[styles.miniButton]: mini,
})}
/>
<ApproveButton
onClick={onApprove}
invert={status === "approved"}
disabled={
status === "approved" ||
dangling ||
deleted ||
readOnly ||
isArchived ||
isArchiving
}
readOnly={readOnly}
className={cn({
[styles.miniButton]: mini,
})}
/>
</Flex>
{moderatedBy}
</Flex>
</Flex>
</Card>
);
};
export default ModerateCard; | the_stack |
import { Applicative, Applicative1 } from 'fp-ts/lib/Applicative'
import * as RA from 'fp-ts/lib/ReadonlyArray'
import * as RNEA from 'fp-ts/lib/ReadonlyNonEmptyArray'
import * as RR from 'fp-ts/lib/ReadonlyRecord'
import { constant, flow, identity, Predicate } from 'fp-ts/lib/function'
import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from 'fp-ts/lib/HKT'
import * as O from 'fp-ts/lib/Option'
import * as E from 'fp-ts/lib/Either'
import { pipe } from 'fp-ts/lib/pipeable'
import { Traversable, Traversable1, Traversable2, Traversable3 } from 'fp-ts/lib/Traversable'
import { Iso } from './Iso'
import { Index } from './Ix'
import { Lens } from './Lens'
import { Optional } from './Optional'
import { Prism } from './Prism'
import { Traversal } from './Traversal'
import { At } from './At'
import { NonEmptyArray } from 'fp-ts/lib/NonEmptyArray'
import { URI as IURI } from 'fp-ts/lib/Identity'
// -------------------------------------------------------------------------------------
// Iso
// -------------------------------------------------------------------------------------
/** @internal */
export const iso = <S, A>(get: Iso<S, A>['get'], reverseGet: Iso<S, A>['reverseGet']): Iso<S, A> => ({
get,
reverseGet
})
/** @internal */
export const isoAsLens = <S, A>(sa: Iso<S, A>): Lens<S, A> => lens(sa.get, flow(sa.reverseGet, constant))
/** @internal */
export const isoAsPrism = <S, A>(sa: Iso<S, A>): Prism<S, A> => prism(flow(sa.get, O.some), sa.reverseGet)
/** @internal */
export const isoAsOptional = <S, A>(sa: Iso<S, A>): Optional<S, A> =>
optional(flow(sa.get, O.some), flow(sa.reverseGet, constant))
/** @internal */
export const isoAsTraversal = <S, A>(sa: Iso<S, A>): Traversal<S, A> =>
traversal(<F>(F: Applicative<F>) => (f: (a: A) => HKT<F, A>) => (s: S) =>
F.map(f(sa.get(s)), (a) => sa.reverseGet(a))
)
// -------------------------------------------------------------------------------------
// Lens
// -------------------------------------------------------------------------------------
/** @internal */
export const lens = <S, A>(get: Lens<S, A>['get'], set: Lens<S, A>['set']): Lens<S, A> => ({ get, set })
/** @internal */
export const lensAsOptional = <S, A>(sa: Lens<S, A>): Optional<S, A> => optional(flow(sa.get, O.some), sa.set)
/** @internal */
export const lensAsTraversal = <S, A>(sa: Lens<S, A>): Traversal<S, A> =>
traversal(<F>(F: Applicative<F>) => (f: (a: A) => HKT<F, A>) => (s: S) => F.map(f(sa.get(s)), (a) => sa.set(a)(s)))
/** @internal */
export const lensComposeLens = <A, B>(ab: Lens<A, B>) => <S>(sa: Lens<S, A>): Lens<S, B> =>
lens(
(s) => ab.get(sa.get(s)),
(b) => (s) => sa.set(ab.set(b)(sa.get(s)))(s)
)
/** @internal */
export const prismComposePrism = <A, B>(ab: Prism<A, B>) => <S>(sa: Prism<S, A>): Prism<S, B> =>
prism(flow(sa.getOption, O.chain(ab.getOption)), flow(ab.reverseGet, sa.reverseGet))
/** @internal */
export const lensComposePrism = <A, B>(ab: Prism<A, B>) => <S>(sa: Lens<S, A>): Optional<S, B> =>
optionalComposeOptional(prismAsOptional(ab))(lensAsOptional(sa))
/** @internal */
export const lensId = <S>(): Lens<S, S> => lens(identity, constant)
/** @internal */
export const lensProp = <A, P extends keyof A>(prop: P) => <S>(sa: Lens<S, A>): Lens<S, A[P]> =>
lens(
(s) => sa.get(s)[prop],
(ap) => (s) => {
const oa = sa.get(s)
if (ap === oa[prop]) {
return s
}
return sa.set(Object.assign({}, oa, { [prop]: ap }))(s)
}
)
/** @internal */
export const lensProps = <A, P extends keyof A>(...props: readonly [P, P, ...ReadonlyArray<P>]) => <S>(
sa: Lens<S, A>
): Lens<S, { [K in P]: A[K] }> =>
lens(
(s) => {
const a = sa.get(s)
const r: { [K in P]?: A[K] } = {}
for (const k of props) {
r[k] = a[k]
}
return r as any
},
(a) => (s) => {
const oa = sa.get(s)
for (const k of props) {
if (a[k] !== oa[k]) {
return sa.set(Object.assign({}, oa, a))(s)
}
}
return s
}
)
/** @internal */
export const lensComponent = <A extends ReadonlyArray<unknown>, P extends keyof A>(prop: P) => <S>(
sa: Lens<S, A>
): Lens<S, A[P]> =>
lens(
(s) => sa.get(s)[prop],
(ap) => (s) => {
const oa = sa.get(s)
if (ap === oa[prop]) {
return s
}
const copy: A = oa.slice() as any
copy[prop] = ap
return sa.set(copy)(s)
}
)
/** @internal */
export const lensAtKey = (key: string) => <S, A>(sa: Lens<S, RR.ReadonlyRecord<string, A>>): Lens<S, O.Option<A>> =>
pipe(sa, lensComposeLens(atReadonlyRecord<A>().at(key)))
// -------------------------------------------------------------------------------------
// Prism
// -------------------------------------------------------------------------------------
/** @internal */
export const prism = <S, A>(
getOption: Prism<S, A>['getOption'],
reverseGet: Prism<S, A>['reverseGet']
): Prism<S, A> => ({ getOption, reverseGet })
/** @internal */
export const prismAsOptional = <S, A>(sa: Prism<S, A>): Optional<S, A> => optional(sa.getOption, (a) => prismSet(a)(sa))
/** @internal */
export const prismAsTraversal = <S, A>(sa: Prism<S, A>): Traversal<S, A> =>
traversal(<F>(F: Applicative<F>) => (f: (a: A) => HKT<F, A>) => (s: S) =>
pipe(
sa.getOption(s),
O.fold(
() => F.of(s),
(a) => F.map(f(a), (a) => prismSet(a)(sa)(s))
)
)
)
/** @internal */
export const prismModifyOption = <A>(f: (a: A) => A) => <S>(sa: Prism<S, A>) => (s: S): O.Option<S> =>
pipe(
sa.getOption(s),
O.map((o) => {
const n = f(o)
return n === o ? s : sa.reverseGet(n)
})
)
/** @internal */
export const prismModify = <A>(f: (a: A) => A) => <S>(sa: Prism<S, A>): ((s: S) => S) => {
const g = prismModifyOption(f)(sa)
return (s) =>
pipe(
g(s),
O.getOrElse(() => s)
)
}
/** @internal */
export const prismSet = <A>(a: A): (<S>(sa: Prism<S, A>) => (s: S) => S) => prismModify(() => a)
/** @internal */
export const prismComposeLens = <A, B>(ab: Lens<A, B>) => <S>(sa: Prism<S, A>): Optional<S, B> =>
optionalComposeOptional(lensAsOptional(ab))(prismAsOptional(sa))
/** @internal */
export const prismFromNullable = <A>(): Prism<A, NonNullable<A>> => prism(O.fromNullable, identity)
/** @internal */
export const prismFromPredicate = <A>(predicate: Predicate<A>): Prism<A, A> =>
prism(O.fromPredicate(predicate), identity)
/** @internal */
export const prismSome = <A>(): Prism<O.Option<A>, A> => prism(identity, O.some)
/** @internal */
export const prismRight = <E, A>(): Prism<E.Either<E, A>, A> => prism(O.fromEither, E.right)
/** @internal */
export const prismLeft = <E, A>(): Prism<E.Either<E, A>, E> =>
prism(
(s) => (E.isLeft(s) ? O.some(s.left) : O.none), // TODO: replace with E.getLeft in v3
E.left
)
// -------------------------------------------------------------------------------------
// Optional
// -------------------------------------------------------------------------------------
/** @internal */
export const optional = <S, A>(getOption: Optional<S, A>['getOption'], set: Optional<S, A>['set']): Optional<S, A> => ({
getOption,
set
})
/** @internal */
export const optionalAsTraversal = <S, A>(sa: Optional<S, A>): Traversal<S, A> =>
traversal(<F>(F: Applicative<F>) => (f: (a: A) => HKT<F, A>) => (s: S) =>
pipe(
sa.getOption(s),
O.fold(
() => F.of(s),
(a) => F.map(f(a), (a: A) => sa.set(a)(s))
)
)
)
/** @internal */
export const optionalModifyOption = <A>(f: (a: A) => A) => <S>(optional: Optional<S, A>) => (s: S): O.Option<S> =>
pipe(
optional.getOption(s),
O.map((a) => {
const n = f(a)
return n === a ? s : optional.set(n)(s)
})
)
/** @internal */
export const optionalModify = <A>(f: (a: A) => A) => <S>(optional: Optional<S, A>): ((s: S) => S) => {
const g = optionalModifyOption(f)(optional)
return (s) =>
pipe(
g(s),
O.getOrElse(() => s)
)
}
/** @internal */
export const optionalComposeOptional = <A, B>(ab: Optional<A, B>) => <S>(sa: Optional<S, A>): Optional<S, B> =>
optional(flow(sa.getOption, O.chain(ab.getOption)), (b) => optionalModify(ab.set(b))(sa))
/** @internal */
export const optionalIndex = (i: number) => <S, A>(sa: Optional<S, ReadonlyArray<A>>): Optional<S, A> =>
pipe(sa, optionalComposeOptional(indexReadonlyArray<A>().index(i)))
/** @internal */
export const optionalIndexNonEmpty = (i: number) => <S, A>(
sa: Optional<S, RNEA.ReadonlyNonEmptyArray<A>>
): Optional<S, A> => pipe(sa, optionalComposeOptional(indexReadonlyNonEmptyArray<A>().index(i)))
/** @internal */
export const optionalKey = (key: string) => <S, A>(sa: Optional<S, RR.ReadonlyRecord<string, A>>): Optional<S, A> =>
pipe(sa, optionalComposeOptional(indexReadonlyRecord<A>().index(key)))
/** @internal */
export const optionalFindFirst = <A>(predicate: Predicate<A>): Optional<ReadonlyArray<A>, A> =>
optional(RA.findFirst(predicate), (a) => (s) =>
pipe(
RA.findIndex(predicate)(s),
O.fold(
() => s,
(i) => RA.unsafeUpdateAt(i, a, s)
)
)
)
const unsafeUpdateAt = <A>(i: number, a: A, as: RNEA.ReadonlyNonEmptyArray<A>): RNEA.ReadonlyNonEmptyArray<A> => {
if (as[i] === a) {
return as
} else {
const xs: NonEmptyArray<A> = [as[0], ...as.slice(1)]
xs[i] = a
return xs
}
}
/** @internal */
export const optionalFindFirstNonEmpty = <A>(predicate: Predicate<A>): Optional<RNEA.ReadonlyNonEmptyArray<A>, A> =>
optional<RNEA.ReadonlyNonEmptyArray<A>, A>(RA.findFirst(predicate), (a) => (as) =>
pipe(
RA.findIndex(predicate)(as),
O.fold(
() => as,
(i) => unsafeUpdateAt(i, a, as)
)
)
)
// -------------------------------------------------------------------------------------
// Traversal
// -------------------------------------------------------------------------------------
/** @internal */
export const traversal = <S, A>(modifyF: Traversal<S, A>['modifyF']): Traversal<S, A> => ({
modifyF
})
/** @internal */
export function traversalComposeTraversal<A, B>(ab: Traversal<A, B>): <S>(sa: Traversal<S, A>) => Traversal<S, B> {
return (sa) => traversal(<F>(F: Applicative<F>) => (f: (a: B) => HKT<F, B>) => sa.modifyF(F)(ab.modifyF(F)(f)))
}
/** @internal */
export const ApplicativeIdentity: Applicative1<IURI> = {
URI: 'Identity',
map: (fa, f) => f(fa),
of: identity,
ap:
/* istanbul ignore next */
(fab, fa) => fab(fa)
}
const isIdentity = (F: Applicative<any>): boolean => F.URI === 'Identity'
/** @internal */
export function fromTraversable<T extends URIS3>(T: Traversable3<T>): <R, E, A>() => Traversal<Kind3<T, R, E, A>, A>
/** @internal */
export function fromTraversable<T extends URIS2>(T: Traversable2<T>): <E, A>() => Traversal<Kind2<T, E, A>, A>
/** @internal */
export function fromTraversable<T extends URIS>(T: Traversable1<T>): <A>() => Traversal<Kind<T, A>, A>
/** @internal */
export function fromTraversable<T>(T: Traversable<T>): <A>() => Traversal<HKT<T, A>, A>
export function fromTraversable<T>(T: Traversable<T>): <A>() => Traversal<HKT<T, A>, A> {
return <A>() =>
traversal(<F>(F: Applicative<F>) => {
// if `F` is `Identity` then `traverseF = map`
const traverseF: <A, B>(ta: HKT<T, A>, f: (a: A) => HKT<F, B>) => HKT<F, HKT<T, B>> = isIdentity(F)
? (T.map as any)
: T.traverse(F)
return (f: (a: A) => HKT<F, A>) => (s: HKT<T, A>) => traverseF(s, f)
})
}
/** @internal */
export function traversalTraverse<T extends URIS>(
T: Traversable1<T>
): <S, A>(sta: Traversal<S, Kind<T, A>>) => Traversal<S, A> {
return traversalComposeTraversal(fromTraversable(T)())
}
// -------------------------------------------------------------------------------------
// Ix
// -------------------------------------------------------------------------------------
/** @internal */
export const index = <S, I, A>(index: Index<S, I, A>['index']): Index<S, I, A> => ({ index })
/** @internal */
export const indexReadonlyArray = <A = never>(): Index<ReadonlyArray<A>, number, A> =>
index((i) =>
optional(
(as) => RA.lookup(i, as),
(a) => (as) =>
pipe(
RA.lookup(i, as),
O.fold(
() => as,
() => RA.unsafeUpdateAt(i, a, as)
)
)
)
)
/** @internal */
export const indexReadonlyNonEmptyArray = <A = never>(): Index<RNEA.ReadonlyNonEmptyArray<A>, number, A> =>
index((i) =>
optional(
(as) => RA.lookup(i, as),
(a) => (as) =>
pipe(
RA.lookup(i, as),
O.fold(
() => as,
() => unsafeUpdateAt(i, a, as)
)
)
)
)
/** @internal */
export const indexReadonlyRecord = <A = never>(): Index<RR.ReadonlyRecord<string, A>, string, A> =>
index((k) =>
optional(
(r) => RR.lookup(k, r),
(a) => (r) => {
if (r[k] === a || O.isNone(RR.lookup(k, r))) {
return r
}
return RR.insertAt(k, a)(r)
}
)
)
// -------------------------------------------------------------------------------------
// At
// -------------------------------------------------------------------------------------
/** @internal */
export const at = <S, I, A>(at: At<S, I, A>['at']): At<S, I, A> => ({ at })
/** @internal */
export function atReadonlyRecord<A = never>(): At<RR.ReadonlyRecord<string, A>, string, O.Option<A>> {
return at((key) =>
lens(
(r) => RR.lookup(key, r),
O.fold(
() => RR.deleteAt(key),
(a) => RR.insertAt(key, a)
)
)
)
} | the_stack |
import { Injectable, Type } from '@angular/core';
import { CoreDelegate, CoreDelegateHandler } from '@classes/delegate';
import { AddonModAssignDefaultFeedbackHandler } from './handlers/default-feedback';
import { AddonModAssignAssign, AddonModAssignSubmission, AddonModAssignPlugin, AddonModAssignSavePluginData } from './assign';
import { makeSingleton } from '@singletons';
import { CoreWSFile } from '@services/ws';
import { AddonModAssignSubmissionFormatted } from './assign-helper';
import { CoreFormFields } from '@singletons/form';
/**
* Interface that all feedback handlers must implement.
*/
export interface AddonModAssignFeedbackHandler extends CoreDelegateHandler {
/**
* Name of the type of feedback the handler supports. E.g. 'file'.
*/
type: string;
/**
* Discard the draft data of the feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
discardDraft?(assignId: number, userId: number, siteId?: string): void | Promise<void>;
/**
* Return the Component to use to display the plugin data.
* It's recommended to return the class of the component, but you can also return an instance of the component.
*
* @param plugin The plugin object.
* @return The component (or promise resolved with component) to use, undefined if not found.
*/
getComponent?(plugin: AddonModAssignPlugin): Type<unknown> | undefined | Promise<Type<unknown> | undefined>;
/**
* Return the draft saved data of the feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param siteId Site ID. If not defined, current site.
* @return Data (or promise resolved with the data).
*/
getDraft?(
assignId: number,
userId: number,
siteId?: string,
): CoreFormFields | Promise<CoreFormFields | undefined> | undefined;
/**
* Get files used by this plugin.
* The files returned by this function will be prefetched when the user prefetches the assign.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return The files (or promise resolved with the files).
*/
getPluginFiles?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): CoreWSFile[] | Promise<CoreWSFile[]>;
/**
* Get a readable name to use for the plugin.
*
* @param plugin The plugin object.
* @return The plugin name.
*/
getPluginName?(plugin: AddonModAssignPlugin): string;
/**
* Check if the feedback data has changed for this plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the feedback.
* @param userId User ID of the submission.
* @return Boolean (or promise resolved with boolean): whether the data has changed.
*/
hasDataChanged?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
userId: number,
): boolean | Promise<boolean>;
/**
* Check whether the plugin has draft data stored.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param siteId Site ID. If not defined, current site.
* @return Boolean or promise resolved with boolean: whether the plugin has draft data.
*/
hasDraftData?(assignId: number, userId: number, siteId?: string): boolean | Promise<boolean>;
/**
* Prefetch any required data for the plugin.
* This should NOT prefetch files. Files to be prefetched should be returned by the getPluginFiles function.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
prefetch?(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<void>;
/**
* Prepare and add to pluginData the data to send to the server based on the draft data saved.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param pluginData Object where to store the data to send.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
prepareFeedbackData?(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
pluginData: AddonModAssignSavePluginData,
siteId?: string,
): void | Promise<void>;
/**
* Save draft data of the feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param data The data to save.
* @param siteId Site ID. If not defined, current site.
* @return If the function is async, it should return a Promise resolved when done.
*/
saveDraft?(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
data: CoreFormFields,
siteId?: string,
): void | Promise<void>;
}
/**
* Delegate to register plugins for assign feedback.
*/
@Injectable({ providedIn: 'root' })
export class AddonModAssignFeedbackDelegateService extends CoreDelegate<AddonModAssignFeedbackHandler> {
protected handlerNameProperty = 'type';
constructor(
protected defaultHandler: AddonModAssignDefaultFeedbackHandler,
) {
super('AddonModAssignFeedbackDelegate', true);
}
/**
* Discard the draft data of the feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async discardPluginFeedbackData(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<void> {
return await this.executeFunctionOnEnabled(plugin.type, 'discardDraft', [assignId, userId, siteId]);
}
/**
* Get the component to use for a certain feedback plugin.
*
* @param plugin The plugin object.
* @return Promise resolved with the component to use, undefined if not found.
*/
async getComponentForPlugin(plugin: AddonModAssignPlugin): Promise<Type<unknown> | undefined> {
return await this.executeFunctionOnEnabled(plugin.type, 'getComponent', [plugin]);
}
/**
* Return the draft saved data of the feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the draft data.
*/
async getPluginDraftData<T>(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<T | undefined> {
return await this.executeFunctionOnEnabled(plugin.type, 'getDraft', [assignId, userId, siteId]);
}
/**
* Get files used by this plugin.
* The files returned by this function will be prefetched when the user prefetches the assign.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the files.
*/
async getPluginFiles(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<CoreWSFile[]> {
const files: CoreWSFile[] | undefined =
await this.executeFunctionOnEnabled(plugin.type, 'getPluginFiles', [assign, submission, plugin, siteId]);
return files || [];
}
/**
* Get a readable name to use for a certain feedback plugin.
*
* @param plugin Plugin to get the name for.
* @return Human readable name.
*/
getPluginName(plugin: AddonModAssignPlugin): string | undefined {
return this.executeFunctionOnEnabled(plugin.type, 'getPluginName', [plugin]);
}
/**
* Check if the feedback data has changed for a certain plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param inputData Data entered by the user for the feedback.
* @param userId User ID of the submission.
* @return Promise resolved with true if data has changed, resolved with false otherwise.
*/
async hasPluginDataChanged(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission | AddonModAssignSubmissionFormatted,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
userId: number,
): Promise<boolean | undefined> {
return await this.executeFunctionOnEnabled(
plugin.type,
'hasDataChanged',
[assign, submission, plugin, inputData, userId],
);
}
/**
* Check whether the plugin has draft data stored.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with true if it has draft data.
*/
async hasPluginDraftData(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<boolean | undefined> {
return await this.executeFunctionOnEnabled(plugin.type, 'hasDraftData', [assignId, userId, siteId]);
}
/**
* Check if a feedback plugin is supported.
*
* @param pluginType Type of the plugin.
* @return Whether it's supported.
*/
isPluginSupported(pluginType: string): boolean {
return this.hasHandler(pluginType, true);
}
/**
* Prefetch any required data for a feedback plugin.
*
* @param assign The assignment.
* @param submission The submission.
* @param plugin The plugin object.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async prefetch(
assign: AddonModAssignAssign,
submission: AddonModAssignSubmission,
plugin: AddonModAssignPlugin,
siteId?: string,
): Promise<void> {
return await this.executeFunctionOnEnabled(plugin.type, 'prefetch', [assign, submission, plugin, siteId]);
}
/**
* Prepare and add to pluginData the data to submit for a certain feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param pluginData Object where to store the data to send.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when data has been gathered.
*/
async preparePluginFeedbackData(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
pluginData: AddonModAssignSavePluginData,
siteId?: string,
): Promise<void> {
return await this.executeFunctionOnEnabled(
plugin.type,
'prepareFeedbackData',
[assignId, userId, plugin, pluginData, siteId],
);
}
/**
* Save draft data of the feedback plugin.
*
* @param assignId The assignment ID.
* @param userId User ID.
* @param plugin The plugin object.
* @param inputData Data to save.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when data has been saved.
*/
async saveFeedbackDraft(
assignId: number,
userId: number,
plugin: AddonModAssignPlugin,
inputData: CoreFormFields,
siteId?: string,
): Promise<void> {
return await this.executeFunctionOnEnabled(
plugin.type,
'saveDraft',
[assignId, userId, plugin, inputData, siteId],
);
}
}
export const AddonModAssignFeedbackDelegate = makeSingleton(AddonModAssignFeedbackDelegateService); | the_stack |
import fs, { NoParamCallback, PathLike } from 'fs'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import getPort from 'get-port'
import open from 'open'
import { logManager } from '../logger'
import { LoginAuthenticator } from '../login-authenticator'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const recording = require('log4js/lib/appenders/recording')
jest.mock('fs', () => {
const originalLib = jest.requireActual('fs')
return {
...originalLib,
mkdirSync: jest.fn(),
readFileSync: jest.fn(),
writeFileSync: jest.fn(),
chmod: jest.fn(),
}
})
const mockApp = {
get: jest.fn(),
listen: jest.fn(),
}
jest.mock('express', () => {
return () => mockApp
})
jest.mock('get-port')
jest.mock('open')
jest.mock('axios')
async function delay(milliseconds: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
describe('LoginAuthenticator', () => {
const credentialsFilename = '/full/path/to/file/credentials.json'
const profileName = 'myProfile'
const clientIdProvider = {
baseURL: 'https://example.com/unused-here',
authURL: 'https://example.com/unused-here',
keyApiURL: 'https://example.com/unused-here',
baseOAuthInURL: 'https://example.com/oauth-in-url',
oauthAuthTokenRefreshURL: 'https://example.com/refresh-url',
clientId: 'client-id',
}
const config = {
appenders: {
main: { type: 'recording' },
stdout: { type: 'stdout' },
},
categories: {
default: { appenders: ['main'], level: 'ERROR' },
'login-authenticator': { appenders: ['main'], level: 'TRACE' },
},
}
const accessToken = 'db3d92f1-0000-0000-0000-000000000000'
const refreshToken = '3f3fb859-0000-0000-0000-000000000000'
const credentialsFileData = {
[profileName]: {
'accessToken': accessToken,
'refreshToken': refreshToken,
'expires': '2020-10-15T13:26:39.966Z',
'scope': 'controller:stCli',
'installedAppId': 'installed app id',
'deviceId': 'device id',
},
}
const otherCredentialsFileData = {
other: {
'accessToken': 'other access token',
'refreshToken': 'other refresh token',
'expires': '2021-07-15T22:33:44.123Z',
'scope': 'controller:stCli',
'installedAppId': 'installed app id',
'deviceId': 'device id',
},
}
const refreshableCredentialsFileData = {
[profileName]: {
...credentialsFileData[profileName],
'expires': new Date().toISOString(),
},
}
const codeVerifierRegex = /\bcode_verifier=[\w|-]+\b/
interface AuthTokenResponse {
access_token: string
refresh_token: string
expires_in: number
scope: string
installed_app_id: string
device_id: string
}
const tokenResponse: AxiosResponse<AuthTokenResponse> = {
data: {
access_token: 'access token',
refresh_token: 'refresh token',
expires_in: 24 * 3600,
scope: 'scope list',
installed_app_id: 'installed app id',
device_id: 'device id',
},
status: 200,
statusText: 'OK',
headers: '',
config: {},
}
const mockServer = {
close: jest.fn(),
}
mockApp.listen.mockReturnValue(mockServer)
const mockStartResponse = {
redirect: jest.fn(),
}
const mockFinishRequest = {
query: { code: 'auth-code' },
}
const mockFinishResponse = {
send: jest.fn(),
}
logManager.init(config)
const mkdirMock = fs.mkdirSync as jest.Mock<typeof fs.mkdirSync>
const readFileMock = (fs.readFileSync as unknown as jest.Mock<Buffer, [fs.PathLike]>)
.mockImplementation(() => { throw { code: 'ENOENT' } })
const writeFileMock = fs.writeFileSync as jest.Mock<typeof fs.writeFileSync>
const chmodMock = fs.chmod as unknown as jest.Mock<void, [PathLike, string | number, NoParamCallback]>
const getPortMock = (getPort as unknown as jest.Mock<Promise<number>, [getPort.Options | undefined]>)
.mockResolvedValue(7777)
const postMock = (axios.post as unknown as jest.Mock<Promise<AxiosResponse<unknown>>, [string, unknown, AxiosRequestConfig | undefined]>)
.mockResolvedValue(tokenResponse)
function setupAuthenticator(): LoginAuthenticator {
LoginAuthenticator.init(credentialsFilename)
return new LoginAuthenticator(profileName, clientIdProvider)
}
type ExpressRouteHandler = (request: Request, response: Response) => void
const finishHappy = (finishHandler: ExpressRouteHandler): void =>
finishHandler(mockFinishRequest as unknown as Request, mockFinishResponse as unknown as Response)
// Call handlers like would happen if the user were following the flow in the browser.
async function imitateBrowser(finishHandlerCaller = finishHappy): Promise<void> {
while (mockApp.get.mock.calls.length < 2) {
await delay(25)
}
const startHandler: ExpressRouteHandler = mockApp.get.mock.calls[0][1]
const finishHandler: ExpressRouteHandler = mockApp.get.mock.calls[1][1]
startHandler({} as Request, mockStartResponse as unknown as Response)
finishHandlerCaller(finishHandler)
while (mockServer.close.mock.calls.length < 1) {
await delay(25)
}
const closeHandler: (error?: Error) => void = mockServer.close.mock.calls[0][0]
closeHandler()
}
afterEach(() => {
jest.clearAllMocks()
delete (globalThis as { _credentialsFile?: string })._credentialsFile
recording.reset()
})
describe('init', () => {
it('makes sure directories exist', () => {
LoginAuthenticator.init(credentialsFilename)
expect(mkdirMock).toHaveBeenCalledTimes(1)
expect(mkdirMock).toHaveBeenCalledWith('/full/path/to/file', { recursive: true })
})
it('sets _credentialsFile properly', function () {
LoginAuthenticator.init(credentialsFilename)
expect((global as { _credentialsFile?: string })._credentialsFile).toBe(credentialsFilename)
})
})
describe('constructor', () => {
it('throws exception when init not called', function () {
expect(() => new LoginAuthenticator(profileName, clientIdProvider))
.toThrow('LoginAuthenticator credentials file not set.')
})
it('constructs without errors', function () {
LoginAuthenticator.init(credentialsFilename)
const loginAuthenticator = new LoginAuthenticator(profileName, clientIdProvider)
expect(loginAuthenticator).toBeDefined()
})
it('reads auth from credentials file', () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(credentialsFileData)))
LoginAuthenticator.init(credentialsFilename)
const loginAuthenticator = new LoginAuthenticator(profileName, clientIdProvider)
expect(loginAuthenticator).toBeDefined()
const logs = recording.replay()
expect(logs.length).toBe(2)
expect(logs[0].data[0]).toBe('constructing a LoginAuthenticator')
expect(readFileMock).toBeCalledWith(credentialsFilename)
expect(logs[1].data[0]).toEqual(expect.stringContaining('authentication info from file'))
})
it('partially redacts token values in logs', async () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(credentialsFileData)))
LoginAuthenticator.init(credentialsFilename)
new LoginAuthenticator(profileName, clientIdProvider)
const logs = recording.replay()
const authInfoLog = logs[1].data[0]
expect(authInfoLog).not.toIncludeMultiple([accessToken, refreshToken])
expect(authInfoLog).toIncludeMultiple(['db3d92f1', '3f3fb859'])
})
})
describe('login', () => {
it('works on the happy path', async () => {
const loginAuthenticator = setupAuthenticator()
const loginPromise = loginAuthenticator.login()
await imitateBrowser()
await loginPromise
expect(getPortMock).toHaveBeenCalledTimes(1)
expect(getPortMock).toHaveBeenCalledWith({ port: [61973, 61974, 61975] })
expect(mockApp.get).toHaveBeenCalledTimes(2)
expect(mockApp.get).toHaveBeenCalledWith('/start', expect.any(Function))
expect(mockApp.get).toHaveBeenCalledWith('/finish', expect.any(Function))
expect(mockApp.listen).toHaveBeenCalledTimes(1)
expect(mockApp.listen).toHaveBeenCalledWith(7777, expect.any(Function))
const listenHandler: () => Promise<void> = mockApp.listen.mock.calls[0][1]
await listenHandler()
expect(open).toHaveBeenCalledTimes(1)
expect(open).toHaveBeenCalledWith('http://localhost:7777/start')
expect(mockStartResponse.redirect).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledWith('https://example.com/oauth-in-url/token', expect.anything(), expect.anything())
const postData = postMock.mock.calls[0][1]
expect(postData).toMatch(/\bgrant_type=authorization_code\b/)
expect(postData).toMatch(/\bclient_id=client-id\b/)
expect(postData).toMatch(codeVerifierRegex)
expect(postData).toMatch(/\bcode=auth-code\b/)
expect(postData).toMatch(/\bredirect_uri=http%3A%2F%2Flocalhost%3A7777%2Ffinish\b/)
const postConfig = postMock.mock.calls[0][2]
expect(postConfig?.headers['Content-Type']).toBe('application/x-www-form-urlencoded')
expect(mockFinishResponse.send).toHaveBeenCalledTimes(1)
expect(mockFinishResponse.send).toHaveBeenCalledWith(expect.stringContaining('You can close the window.'))
expect(readFileMock).toHaveBeenCalledTimes(2)
expect(readFileMock).toHaveBeenCalledWith(credentialsFilename)
expect(writeFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledWith(credentialsFilename, expect.stringMatching(/"myProfile":/))
expect(chmodMock).toHaveBeenCalledTimes(1)
expect(chmodMock).toHaveBeenCalledWith(credentialsFilename, 0o600, expect.any(Function))
})
it('logs error if setting permissions of credentials file fails', async () => {
chmodMock.mockImplementationOnce((path: PathLike, mode: string | number, callback: NoParamCallback) => {
callback(Error('failed to chmod'))
})
const loginAuthenticator = setupAuthenticator()
const loginPromise = loginAuthenticator.login()
await imitateBrowser()
await loginPromise
expect(chmodMock).toHaveBeenCalledTimes(1)
expect(chmodMock).toHaveBeenCalledWith(credentialsFilename, 0o600, expect.any(Function))
const logs = recording.replay()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const pertinentLog = logs.filter((log: { data: any[] }) => log.data[0] === 'failed to set permissions on credentials file')
expect(pertinentLog.length).toBe(1)
})
it('reports error when authentication fails', async () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(credentialsFileData)))
const loginAuthenticator = setupAuthenticator()
const loginPromise = loginAuthenticator.login()
const mockFinishRequest = {
query: {
error: 'could not get code',
error_description: 'because of reasons',
},
}
const finishWithError = (finishHandler: ExpressRouteHandler): void =>
finishHandler(mockFinishRequest as unknown as Request, mockFinishResponse as unknown as Response)
await imitateBrowser(finishWithError)
await expect(loginPromise).rejects.toBe('unable to get authentication info')
expect(mockApp.get).toHaveBeenCalledTimes(2)
expect(mockApp.get).toHaveBeenCalledWith('/start', expect.any(Function))
expect(mockApp.get).toHaveBeenCalledWith('/finish', expect.any(Function))
expect(mockApp.listen).toHaveBeenCalledTimes(1)
expect(mockApp.listen).toHaveBeenCalledWith(7777, expect.any(Function))
const listenHandler: () => Promise<void> = mockApp.listen.mock.calls[0][1]
await listenHandler()
expect(open).toHaveBeenCalledTimes(1)
expect(open).toHaveBeenCalledWith('http://localhost:7777/start')
expect(mockStartResponse.redirect).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledTimes(0)
expect(mockFinishResponse.send).toHaveBeenCalledTimes(1)
expect(mockFinishResponse.send).toHaveBeenCalledWith(expect.stringContaining('Failure trying to authenticate.'))
expect(readFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledTimes(0)
expect(chmodMock).toHaveBeenCalledTimes(0)
})
it('reports error when token request fails', async () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(credentialsFileData)))
postMock.mockRejectedValueOnce({ name: 'forced error', message: 'forced failure' })
const loginAuthenticator = setupAuthenticator()
const loginPromise = loginAuthenticator.login()
await imitateBrowser()
await expect(loginPromise).rejects.toBe('unable to get authentication info')
expect(mockApp.get).toHaveBeenCalledTimes(2)
expect(mockApp.get).toHaveBeenCalledWith('/start', expect.any(Function))
expect(mockApp.get).toHaveBeenCalledWith('/finish', expect.any(Function))
expect(mockApp.listen).toHaveBeenCalledTimes(1)
expect(mockApp.listen).toHaveBeenCalledWith(7777, expect.any(Function))
const listenHandler: () => Promise<void> = mockApp.listen.mock.calls[0][1]
await listenHandler()
expect(open).toHaveBeenCalledTimes(1)
expect(open).toHaveBeenCalledWith('http://localhost:7777/start')
expect(mockStartResponse.redirect).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledWith('https://example.com/oauth-in-url/token', expect.anything(), expect.anything())
const postData = postMock.mock.calls[0][1]
expect(postData).toMatch(/\bgrant_type=authorization_code\b/)
expect(postData).toMatch(/\bclient_id=client-id\b/)
expect(postData).toMatch(codeVerifierRegex)
expect(postData).toMatch(/\bcode=auth-code\b/)
expect(postData).toMatch(/\bredirect_uri=http%3A%2F%2Flocalhost%3A7777%2Ffinish\b/)
const postConfig = postMock.mock.calls[0][2]
expect(postConfig?.headers['Content-Type']).toBe('application/x-www-form-urlencoded')
expect(mockFinishResponse.send).toHaveBeenCalledTimes(1)
expect(mockFinishResponse.send).toHaveBeenCalledWith(expect.stringContaining('Failure trying retrieve token.'))
expect(readFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledTimes(0)
expect(chmodMock).toHaveBeenCalledTimes(0)
})
})
describe('logout', () => {
it('works on the happy path', async () => {
readFileMock.mockReturnValue(Buffer.from(JSON.stringify(credentialsFileData)))
const loginAuthenticator = setupAuthenticator()
await expect(loginAuthenticator.logout()).resolves.toBe(undefined)
expect(readFileMock).toHaveBeenCalledTimes(2)
expect(writeFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledWith(credentialsFilename, '{}')
})
it('is fine when there is no profile to delete', async () => {
readFileMock.mockReturnValue(Buffer.from(JSON.stringify(otherCredentialsFileData)))
const loginAuthenticator = setupAuthenticator()
await expect(loginAuthenticator.logout()).resolves.toBe(undefined)
expect(readFileMock).toHaveBeenCalledTimes(2)
expect(writeFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledWith(credentialsFilename, JSON.stringify(otherCredentialsFileData, null, 4))
})
})
describe('authenticate', () => {
it('calls generic authenticate', async () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(credentialsFileData)))
const genericSpy = jest.spyOn(LoginAuthenticator.prototype, 'authenticateGeneric')
const loginAuthenticator = setupAuthenticator()
const requestConfig = {}
const response = await loginAuthenticator.authenticate(requestConfig)
expect(response.headers.Authorization).toEqual('Bearer access token')
expect(genericSpy).toBeCalledTimes(1)
})
})
describe('authenticateGeneric', () => {
it('refreshes token when necessary', async () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(refreshableCredentialsFileData)))
const loginAuthenticator = setupAuthenticator()
const requestConfig = {}
const response = await loginAuthenticator.authenticate(requestConfig)
expect(response.headers.Authorization).toEqual('Bearer access token')
expect(postMock).toHaveBeenCalledTimes(1)
const postData = postMock.mock.calls[0][1]
expect(postData).toMatch(/\bgrant_type=refresh_token\b/)
expect(postData).toMatch(/\bclient_id=client-id\b/)
expect(postData).toEqual(expect.stringContaining(`refresh_token=${refreshToken}`))
const postConfig = postMock.mock.calls[0][2]
expect(postConfig?.headers['Content-Type']).toBe('application/x-www-form-urlencoded')
expect(readFileMock).toHaveBeenCalledTimes(2)
expect(readFileMock).toHaveBeenCalledWith(credentialsFilename)
expect(writeFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledWith(credentialsFilename, expect.stringMatching(/"myProfile":/))
})
it('logs in when refresh fails', async () => {
readFileMock.mockReturnValueOnce(Buffer.from(JSON.stringify(refreshableCredentialsFileData)))
postMock.mockRejectedValueOnce(Error('forced failure'))
postMock.mockResolvedValueOnce(tokenResponse)
const loginAuthenticator = setupAuthenticator()
const requestConfig = {}
const promise = loginAuthenticator.authenticate(requestConfig)
await imitateBrowser()
const response = await promise
expect(response.headers.Authorization).toEqual('Bearer access token')
expect(postMock).toHaveBeenCalledTimes(2)
const postData = postMock.mock.calls[0][1]
expect(postData).toMatch(/\bgrant_type=refresh_token\b/)
expect(postData).toMatch(/\bclient_id=client-id\b/)
expect(postData).toEqual(expect.stringContaining(`refresh_token=${refreshToken}`))
const postConfig = postMock.mock.calls[0][2]
expect(postConfig?.headers['Content-Type']).toBe('application/x-www-form-urlencoded')
expect(postMock).toHaveBeenCalledWith('https://example.com/oauth-in-url/token', expect.anything(), expect.anything())
const postData2 = postMock.mock.calls[1][1]
expect(postData2).toMatch(/\bgrant_type=authorization_code\b/)
expect(postData2).toMatch(/\bclient_id=client-id\b/)
expect(postData2).toMatch(codeVerifierRegex)
expect(postData2).toMatch(/\bcode=auth-code\b/)
expect(postData2).toMatch(/\bredirect_uri=http%3A%2F%2Flocalhost%3A7777%2Ffinish\b/)
const postConfig2 = postMock.mock.calls[1][2]
expect(postConfig2?.headers['Content-Type']).toBe('application/x-www-form-urlencoded')
expect(mockFinishResponse.send).toHaveBeenCalledTimes(1)
expect(mockFinishResponse.send).toHaveBeenCalledWith(expect.stringContaining('You can close the window.'))
expect(readFileMock).toHaveBeenCalledTimes(2)
expect(readFileMock).toHaveBeenCalledWith(credentialsFilename)
expect(writeFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledWith(credentialsFilename, expect.stringMatching(/"myProfile":/))
})
it('logs in not logged in', async () => {
const loginAuthenticator = setupAuthenticator()
const requestConfig = {}
const promise = loginAuthenticator.authenticate(requestConfig)
await imitateBrowser()
const response = await promise
expect(response.headers.Authorization).toEqual('Bearer access token')
expect(getPortMock).toHaveBeenCalledTimes(1)
expect(getPortMock).toHaveBeenCalledWith({ port: [61973, 61974, 61975] })
expect(mockApp.get).toHaveBeenCalledTimes(2)
expect(mockApp.get).toHaveBeenCalledWith('/start', expect.any(Function))
expect(mockApp.get).toHaveBeenCalledWith('/finish', expect.any(Function))
expect(mockApp.listen).toHaveBeenCalledTimes(1)
expect(mockApp.listen).toHaveBeenCalledWith(7777, expect.any(Function))
const listenHandler: () => Promise<void> = mockApp.listen.mock.calls[0][1]
await listenHandler()
expect(open).toHaveBeenCalledTimes(1)
expect(open).toHaveBeenCalledWith('http://localhost:7777/start')
expect(mockStartResponse.redirect).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledTimes(1)
expect(postMock).toHaveBeenCalledWith('https://example.com/oauth-in-url/token', expect.anything(), expect.anything())
const postData = postMock.mock.calls[0][1]
expect(postData).toMatch(/\bgrant_type=authorization_code\b/)
expect(postData).toMatch(/\bclient_id=client-id\b/)
expect(postData).toMatch(codeVerifierRegex)
expect(postData).toMatch(/\bcode=auth-code\b/)
expect(postData).toMatch(/\bredirect_uri=http%3A%2F%2Flocalhost%3A7777%2Ffinish\b/)
const postConfig = postMock.mock.calls[0][2]
expect(postConfig?.headers['Content-Type']).toBe('application/x-www-form-urlencoded')
expect(mockFinishResponse.send).toHaveBeenCalledTimes(1)
expect(mockFinishResponse.send).toHaveBeenCalledWith(expect.stringContaining('You can close the window.'))
expect(readFileMock).toHaveBeenCalledTimes(2)
expect(readFileMock).toHaveBeenCalledWith(credentialsFilename)
expect(writeFileMock).toHaveBeenCalledTimes(1)
expect(writeFileMock).toHaveBeenCalledWith(credentialsFilename, expect.stringMatching(/"myProfile":/))
})
})
}) | the_stack |
import * as csx from './csx';
import { vendorPrefixed } from './csx';
import * as typestyle from 'typestyle';
import * as React from "react";
/** Creates a copy of an object without the mentioned keys */
function _objectWithoutProperties(obj: any, keys: string[]) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
declare global {
interface Function {
displayName?: string;
}
}
/********
*
* Primitives
*
********/
/**
* For that time you just need a visual vertical seperation
*/
export const SmallVerticalSpace = (props: { space?: number }) => {
return <div style={{ height: props.space || 24 }}></div>;
}
SmallVerticalSpace.displayName = "SmallVerticalSpace";
/**
* For that time you just need a visual horizontal seperation
*/
export const SmallHorizontalSpace = (props: { space?: number }) => {
return <div style={{ width: props.space || 24, display: 'inline-block' }}></div>;
}
SmallVerticalSpace.displayName = "SmallHorizontalSpace";
interface PrimitiveProps extends React.HTMLProps<HTMLDivElement> { };
namespace ClassNames {
export const content = typestyle.style(vendorPrefixed.content);
export const flex = typestyle.style(vendorPrefixed.pass, vendorPrefixed.flex);
export const flexScrollY = typestyle.style(vendorPrefixed.pass, vendorPrefixed.flex, vendorPrefixed.vertical, { overflowY: 'auto' });
export const pass = typestyle.style(vendorPrefixed.pass);
export const contentVertical = typestyle.style(vendorPrefixed.content, vendorPrefixed.vertical);
export const contentVerticalCentered = typestyle.style(vendorPrefixed.content, vendorPrefixed.vertical, vendorPrefixed.center);
export const contentHorizontal = typestyle.style(vendorPrefixed.content, vendorPrefixed.horizontal);
export const contentHorizontalCentered = typestyle.style(vendorPrefixed.content, vendorPrefixed.horizontal, vendorPrefixed.center);
export const flexVertical = typestyle.style(vendorPrefixed.flex, vendorPrefixed.vertical, { maxWidth: '100%' /*normalizing browser bugs*/ });
export const flexHorizontal = typestyle.style(vendorPrefixed.flex, vendorPrefixed.horizontal);
}
/**
* Generally prefer an inline block (as that will wrap).
* Use this for critical `content` driven *vertical* height
*
* Takes as much space as it needs, no more, no less
*/
export const Content = (props: PrimitiveProps) => {
const className = ClassNames.content + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="Content" {...props} className={className}>
{props.children}
</div>
);
};
Content.displayName = "Content";
/**
* Takes as much space as it needs, no more, no less
*/
export const InlineBlock = (props: PrimitiveProps) => {
const style = csx.extend({ display: 'inline-block' }, props.style || {});
return (
<div data-comment="InlineBlock" {...props} style={style}>
{props.children}
</div>
);
};
InlineBlock.displayName = "InlineBlock";
/**
* Takes up all the parent space, no more, no less
*/
export const Flex = (props: PrimitiveProps) => {
const className = ClassNames.flex + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="Flex" {...props} className={className}>
{props.children}
</div>
);
};
Flex.displayName = "Flex";
/**
* Takes up all the parent space, no more, no less and scrolls the children in Y if needed
*/
export const FlexScrollY = (props: PrimitiveProps) => {
const className = ClassNames.flexScrollY + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="FlexScrollY" {...props} className={className}>
{props.children}
</div>
);
};
FlexScrollY.displayName = "FlexScrollY";
/**
* When you need a general purpose container. Use this instead of a `div`
*/
export const Pass = (props: PrimitiveProps) => {
const className = ClassNames.pass + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="Pass" {...props} className={className}>
{props.children}
</div>
);
};
Pass.displayName = "Pass";
/**
* Provides a Vertical Container. For the parent it behaves like content.
*/
export const ContentVertical = (props: PrimitiveProps) => {
const className = ClassNames.contentVertical + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="ContentVertical" {...props} className={className}>
{props.children}
</div>
);
};
ContentVertical.displayName = "ContentVertical";
/**
* Quite commonly need horizontally centered text
*/
export const ContentVerticalCentered = (props: PrimitiveProps) => {
const className = ClassNames.contentVerticalCentered + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="ContentVerticalCentered" {...props} className={className}>
{props.children}
</div>
);
}
ContentVerticalCentered.displayName = "ContentVerticalCentered";
/**
* Provides a Horizontal Container. For the parent it behaves like content.
*/
export const ContentHorizontal = (props: PrimitiveProps) => {
const className = ClassNames.contentHorizontal + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="ContentHorizontal" {...props} className={className}>
{props.children}
</div>
);
};
ContentHorizontal.displayName = "ContentHorizontal";
/**
* Provides a Horizontal Container and centers its children in the cross dimension
*/
export const ContentHorizontalCentered = (props: PrimitiveProps) => {
const className = ClassNames.contentHorizontalCentered + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="ContentHorizontalCentered" {...props} className={className}>
{props.children}
</div>
);
};
ContentHorizontalCentered.displayName = "ContentHorizontalCentered";
/**
* Provides a Vertical Container. For the parent it behaves like flex.
*/
export const FlexVertical = (props: PrimitiveProps) => {
const className = ClassNames.flexVertical + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="FlexVertical" {...props} className={className}>
{props.children}
</div>
);
};
FlexVertical.displayName = "FlexVertical";
/**
* Provides a Horizontal Container. For the parent it behaves like flex.
*/
export const FlexHorizontal = (props: PrimitiveProps) => {
const className = ClassNames.flexHorizontal + (props.className ? ` ${props.className}` : '');
return (
<div data-comment="FlexHorizontal" {...props} className={className}>
{props.children}
</div>
);
};
FlexHorizontal.displayName = "FlexHorizontal";
/********
*
* Grid System
*
********/
interface PaddedProps extends PrimitiveProps {
padding: number | string;
}
/**
* Lays out the children horizontally with
* - ThisComponent: gets the overall Height (by max) of the children
* - Children: get the Width : equally distributed from the parent Width
* - Children: get the Height : sized by content
* - ThisComponent: Puts a horizontal padding between each item
*/
export const ContentHorizontalFlexPadded = (props: PaddedProps) => {
const {padding} = props;
const otherProps = _objectWithoutProperties(props, ['padding', 'children']);
const children = React.Children.toArray(props.children).filter(c => !!c);
const last = children.length - 1;
const itemPadding = (index: number) => {
if (index == last) {
return csx.Box.padding(0);
}
else {
return csx.Box.padding(0, padding, 0, 0);
}
}
return (
<ContentHorizontal {...otherProps}>
{
children.map((child, i) => <Flex key={(child as any).key || i} style={itemPadding(i)}>{child}</Flex>)
}
</ContentHorizontal>
);
}
ContentHorizontalFlexPadded.displayName = "ContentHorizontalFlexPadded";
/**
* Lays out the children horizontally with
* - Parent: gets to chose the Width
* - ThisComponent: gets the overall Height (by max) of the children
* - Children: get the Width : equally distributed from the parent Width
* - Children: get the Height : sized by content
* - ThisComponent: Puts a horizontal padding between each item
*/
export const FlexHorizontalFlexPadded = (props: PaddedProps) => {
const {padding} = props;
const otherProps = _objectWithoutProperties(props, ['padding', 'children']);
const children = React.Children.toArray(props.children).filter(c => !!c);
const last = children.length - 1;
const itemPadding = (index: number) => {
if (index == last) {
return csx.Box.padding(0);
}
else {
return csx.Box.padding(0, padding, 0, 0);
}
}
return (
<FlexHorizontal {...otherProps}>
{
children.map((child, i) => <Flex key={(child as any).key || i} style={itemPadding(i)}>{child}</Flex>)
}
</FlexHorizontal>
);
}
FlexHorizontalFlexPadded.displayName = "FlexHorizontalFlexPadded";
/**
* Lays out the children horizontally with
* - Parent: gets to chose the Width
* - ThisComponent: gets the overall Height (by max) of the children
* - Children: get the Width : equally distributed from the parent Width
* - Children: get the Height : sized by content
* - ThisComponent: Puts a horizontal padding between each item
*/
export const ContentHorizontalContentPadded = (props: PaddedProps) => {
const {padding} = props;
const otherProps = _objectWithoutProperties(props, ['padding', 'children']);
const children = React.Children.toArray(props.children).filter(c => !!c);
const last = children.length - 1;
const itemPadding = (index: number) => {
if (index == last) {
return csx.Box.padding(0);
}
else {
return csx.Box.padding(0, padding, 0, 0);
}
}
return (
<ContentHorizontal {...otherProps}>
{
children.map((child, i) => <Content key={(child as any).key || i} style={itemPadding(i)}>{child}</Content>)
}
</ContentHorizontal>
);
}
ContentHorizontalContentPadded.displayName = "ContentHorizontalContentPadded";
/**
* Lays out the children vertically with
* - Parent: gets to chose the Width
* - ThisComponent: gets the Height : (by sum) of the children
* - Children: get the Width : parent
* - Children: get the Height : sized by content
* - ThisComponent: Puts a vertical padding between each item
*/
export const ContentVerticalContentPadded = (props: PaddedProps) => {
const {padding} = props;
const otherProps = _objectWithoutProperties(props, ['padding', 'children']);
const children = React.Children.toArray(props.children).filter(c => !!c);
const last = children.length - 1;
const itemPadding = (index: number) => {
if (index == last) {
return csx.Box.padding(0);
}
else {
return csx.Box.padding(0, 0, padding, 0);
}
}
return (
<ContentVertical {...otherProps}>
{
children.map((child, i) => <Content key={(child as any).key || i} style={itemPadding(i)}>{child}</Content>)
}
</ContentVertical>
);
}
ContentVerticalContentPadded.displayName = "ContentVerticalContentPadded";
interface GridMarginedProps extends PrimitiveProps {
margin: number | string;
}
/**
* Lays out the children vertically with
* - Parent: gets to chose the overall Width
* - ThisComponent: gets the Height : (by sum) of the children
* - Children: get the Width : sized by content
* - Children: get the Height : sized by content
* - ThisComponent: Puts a margin between each item.
* - ThisComponent: Puts a negative margin on itself to offset the margins of the children (prevents them from leaking out)
*/
export const GridMargined = (props: GridMarginedProps) => {
const {margin} = props;
const otherProps = _objectWithoutProperties(props, ['margin', 'children']);
const marginPx = `${margin}px`;
const style = csx.extend(csx.wrap, { marginTop: '-' + marginPx, marginLeft: '-' + marginPx }, props.style || {});
const children = React.Children.toArray(props.children).filter(c => !!c);
return (
<ContentHorizontal {...otherProps} style={style}>
{
children.map((child, i) => <Content key={(child as any).key || i} style={{ marginLeft: marginPx, marginTop: marginPx }}>{child}</Content>)
}
</ContentHorizontal>
);
}
GridMargined.displayName = "GridMargined"; | the_stack |
import Cache, {CacheUpdate} from '../types/Cache';
import Query from '../types/Query';
import ServerPreparation from '../types/ServerPreparation';
import NetworkLayerInterface from '../types/NetworkLayerInterface';
import createError from '../utils/create-error';
import mergeQueries from '../utils/merge-queries';
import runQueryAgainstCache, {
QueryCacheResult,
} from '../utils/run-query-against-cache';
import notEqual from '../utils/not-equal';
import mergeCache from '../utils/merge-cache';
import NetworkLayer from '../network-layer';
import RequestBatcher from './request-batcher';
import Mutation from './mutation';
import ErrorResult from '../types/ErrorResult';
import {OptimisticUpdateHandler, BaseCache} from './optimistic';
import OptimisticValueStore from './OptimisticValueStore';
import {createNodeID} from '../types/NodeID';
import {BaseRootQuery, Mutation as TypedMutation} from '../typed-helpers/query';
import ServerResponse from '../types/ServerResponse';
import Request from '../types/Request';
declare const BICYCLE_SERVER_PREPARATION: ServerPreparation | void;
export {
NetworkLayer,
NetworkLayerInterface as INetworkLayer,
QueryCacheResult,
createNodeID,
Request,
ServerResponse,
};
export type ClientOptions = {
networkLayer?: NetworkLayerInterface;
serverPreparation?: ServerPreparation;
cacheTimeout?: number;
};
export interface Subscription {
unsubscribe: () => void;
}
class Client<
OptimisticUpdatersType = {
[typeName: string]: {[mutationName: string]: OptimisticUpdateHandler};
}
> {
private readonly _options: ClientOptions;
private _cache: Cache;
private _optimisticCache: Cache;
private readonly _optimisticValueStore: OptimisticValueStore = new OptimisticValueStore();
private readonly _queries: Query[] = [];
private readonly _queriesCount: number[] = [];
private readonly _updateHandlers: (() => any)[] = [];
private readonly _networkErrorHandlers: ((err: Error) => any)[] = [];
private readonly _mutationErrorHandlers: ((err: Error) => any)[] = [];
private readonly _queueRequestHandlers: (() => any)[] = [];
private readonly _successfulResponseHandlers: ((
pendingMutations: number,
) => any)[] = [];
private readonly _optimisticUpdaters: {
[typeName: string]: void | {
[mutationName: string]: void | OptimisticUpdateHandler;
};
} = {};
private readonly _request: RequestBatcher;
constructor(options: ClientOptions = {}) {
this._options = options;
const serverPreparation =
options.serverPreparation !== undefined
? options.serverPreparation
: typeof BICYCLE_SERVER_PREPARATION !== 'undefined'
? BICYCLE_SERVER_PREPARATION
: undefined;
this._cache =
(serverPreparation && serverPreparation.c) ||
({Root: {root: {}}} as Cache);
this._optimisticCache = this._cache;
this._request = new RequestBatcher(
options.networkLayer === undefined
? new NetworkLayer()
: options.networkLayer,
serverPreparation,
this,
);
}
private _onUpdate(fn: () => any) {
this._updateHandlers.push(fn);
}
private _offUpdate(fn: () => any) {
this._updateHandlers.splice(this._updateHandlers.indexOf(fn), 1);
}
// called by RequestBatcher, these errors are always retried and are usually temporary
_handleNetworkError(err: Error) {
(err as any).code = 'NETWORK_ERROR';
setTimeout(() => {
throw err;
}, 0);
this._networkErrorHandlers.forEach(handler => {
handler(err);
});
}
// called by RequestBatcher, these errors are not retried
_handleMutationError(err: Error) {
setTimeout(() => {
throw err;
}, 0);
this._mutationErrorHandlers.forEach(handler => {
handler(err);
});
}
_handleQueueRequest() {
this._queueRequestHandlers.forEach(handler => {
handler();
});
}
_handleSuccessfulResponse(pendingMutations: number) {
this._successfulResponseHandlers.forEach(handler => {
handler(pendingMutations);
});
}
_handleNewSession(data: Cache) {
this._cache = data;
this._updateOptimistCache();
}
// called by RequestBatcher when there is new data for the cache or the list of pending mutations changes
_handleUpdate(data: void | CacheUpdate) {
if (data) {
this._cache = mergeCache(this._cache, data);
}
this._updateOptimistCache();
}
private _updateOptimistCache() {
const pendingMutations = this._request.getPendingMutations();
if (pendingMutations.length) {
const result = {};
const cache = new BaseCache(
createNodeID('Root', 'root'),
this._cache,
result,
);
pendingMutations.forEach(mutation => mutation.applyOptimistic(cache));
this._optimisticCache = mergeCache(this._cache, result);
} else {
this._optimisticCache = this._cache;
}
this._updateHandlers.forEach(handler => {
handler();
});
}
private _getQuery(): Query {
if (this._queries.length === 0) return {};
return mergeQueries(...this._queries);
}
private _updateQuery() {
this._request.updateQuery(this._getQuery());
}
private _addQuery(query: Query) {
const i = this._queries.indexOf(query);
if (i !== -1) {
this._queriesCount[i]++;
return;
}
this._queries.push(query);
this._queriesCount.push(1);
this._updateQuery();
}
private _removeQuery(query: Query) {
const i = this._queries.indexOf(query);
if (i === -1) {
console.warn('You attempted to remove a query that does not exist.');
return;
}
this._queriesCount[i]--;
if (this._queriesCount[i] !== 0) return;
this._queries.splice(i, 1);
this._queriesCount.splice(i, 1);
this._updateQuery();
}
queryCache<TResult>(query: BaseRootQuery<TResult>): QueryCacheResult<TResult>;
queryCache(query: Query): QueryCacheResult<any>;
queryCache(query: Query | BaseRootQuery<any>): QueryCacheResult<any> {
return runQueryAgainstCache(
this._optimisticCache,
query instanceof BaseRootQuery ? query._query : query,
);
}
query<TResult>(query: BaseRootQuery<TResult>): Promise<TResult>;
query(query: Query): Promise<any>;
query(query: Query | BaseRootQuery<any>): Promise<any> {
const q = query instanceof BaseRootQuery ? query._query : query;
return new Promise((resolve, reject) => {
let subscription: null | Subscription = null;
let done = false;
subscription = this.subscribe(q, (result, loaded, errors) => {
if (errors.length) {
const err = createError(
'Error fetching data for query:\n' + errors.join('\n'),
{
code: 'BICYCLE_QUERY_ERROR',
query: q,
errors,
result,
},
);
reject(err);
done = true;
if (subscription) subscription.unsubscribe();
} else if (loaded) {
resolve(result);
done = true;
if (subscription) subscription.unsubscribe();
}
});
if (done) subscription.unsubscribe();
});
}
defineOptimisticUpdaters(updates: OptimisticUpdatersType) {
const u = updates as any;
Object.keys(u).forEach(t => {
if (!this._optimisticUpdaters[t]) this._optimisticUpdaters[t] = {};
Object.keys(u[t]).forEach(k => {
this._optimisticUpdaters[t][k] = u[t][k];
});
});
}
update<TResult>(mutation: TypedMutation<TResult>): Promise<TResult>;
update(
method: string,
args: any,
optimisticUpdate?: OptimisticUpdateHandler,
): Promise<any>;
update(
method: string | TypedMutation<any>,
args?: any,
optimisticUpdate?: OptimisticUpdateHandler,
): Promise<any> {
// TODO: share a single "Mutation" class
const m = method instanceof TypedMutation ? method._name : method;
const a = method instanceof TypedMutation ? method._args : args;
let o =
method instanceof TypedMutation
? method._optimisticUpdate
: optimisticUpdate;
if (!o) {
const split = m.split('.');
o =
this._optimisticUpdaters[split[0]] &&
this._optimisticUpdaters[split[0]][split[1]];
}
return this._request.runMutation(
new Mutation(m, a, o, this._optimisticValueStore),
);
}
subscribe<TResult>(
query: BaseRootQuery<TResult>,
fn: (
result: TResult,
loaded: boolean,
errors: ReadonlyArray<string>,
errorDetails: ReadonlyArray<ErrorResult>,
) => any,
): Subscription;
subscribe(
query: Query,
fn: (
result: any,
loaded: boolean,
errors: ReadonlyArray<string>,
errorDetails: ReadonlyArray<ErrorResult>,
) => any,
): Subscription;
subscribe(
query: Query | BaseRootQuery<any>,
fn: (
result: any,
loaded: boolean,
errors: ReadonlyArray<string>,
errorDetails: ReadonlyArray<ErrorResult>,
) => any,
): Subscription {
const q = query instanceof BaseRootQuery ? query._query : query;
let lastValue: any = null;
const onUpdate = () => {
const nextValue = this.queryCache(q);
if (lastValue === null || notEqual(lastValue, nextValue)) {
lastValue = nextValue;
fn(
nextValue.result,
nextValue.loaded,
nextValue.errors,
nextValue.errorDetails,
);
}
};
this._onUpdate(onUpdate);
onUpdate();
this._addQuery(q);
return {
unsubscribe: () => {
this._offUpdate(onUpdate);
if (this._options.cacheTimeout) {
setTimeout(() => this._removeQuery(q), this._options.cacheTimeout);
} else {
this._removeQuery(q);
}
},
};
}
subscribeToNetworkErrors(fn: (err: Error) => any): Subscription {
this._networkErrorHandlers.push(fn);
return {
unsubscribe: () => {
this._networkErrorHandlers.splice(
this._networkErrorHandlers.indexOf(fn),
1,
);
},
};
}
subscribeToMutationErrors(fn: (err: Error) => any): Subscription {
this._mutationErrorHandlers.push(fn);
return {
unsubscribe: () => {
this._mutationErrorHandlers.splice(
this._mutationErrorHandlers.indexOf(fn),
1,
);
},
};
}
subscribeToQueueRequest(fn: () => any): Subscription {
this._queueRequestHandlers.push(fn);
return {
unsubscribe: () => {
this._queueRequestHandlers.splice(
this._queueRequestHandlers.indexOf(fn),
1,
);
},
};
}
subscribeToSuccessfulResponse(
fn: (pendingMutations: number) => any,
): Subscription {
this._successfulResponseHandlers.push(fn);
return {
unsubscribe: () => {
this._successfulResponseHandlers.splice(
this._successfulResponseHandlers.indexOf(fn),
1,
);
},
};
}
}
export default Client; | the_stack |
import 'jest';
import * as React from 'react';
import * as PropTypes from 'prop-types';
import {configure, mount, ReactWrapper} from 'enzyme';
import ReactSixteenAdapter = require('enzyme-adapter-react-16');
import {ConnectableComponent, ConnectableComponentProps, viewBinding, connect, getEspReactRenderModel} from '../src';
import {Router} from 'esp-js';
import {observeEvent} from 'esp-js/src/decorators/observeEvent';
import {ConnectableComponentChildProps, PublishEvent, PublishModelEventContext, PublishModelEventDelegate} from '../src/connectableComponent';
configure({adapter: new ReactSixteenAdapter()});
class TestModelView1 extends React.Component {
constructor(props) {
super(props);
}
render() {
return <span>View1</span>;
}
}
class TestModelView2 extends React.Component {
constructor(props) {
super(props);
}
render() {
return <span>View2</span>;
}
}
class TestModelView3 extends React.Component {
constructor(props) {
super(props);
}
render() {
return <span>View3</span>;
}
}
@viewBinding(TestModelView1)
@viewBinding(TestModelView3, 'alternative-view-context')
class TestModel {
public value: string;
constructor() {
this.value = 'initial-value';
}
@observeEvent('test-event')
_onTestEvent(ev) {
this.value = ev;
}
}
class TestModel2 extends TestModel {
@getEspReactRenderModel()
_getOtherState() {
return {
value: this.value,
value2: this.value,
value3: 'value-3'
} as MappedModel;
}
}
class TestModel3 extends TestModel {
getEspReactRenderModel() {
return {
value: this.value,
value2: this.value,
value3: 'value-3.1'
} as MappedModel;
}
}
interface MappedModel {
value: string;
value2: string;
value3: string;
}
interface TestOptions {
useConnectFunction?: boolean;
useMapModelToProps?: boolean;
useCreatePublishEventProps?: boolean;
useAlternativeViewContext?: boolean;
passOtherProps?: boolean;
useRenderModelSelectorDecorator?: boolean;
useRenderModelSelectorFunction?: boolean;
}
describe('ConnectableComponent', () => {
let router,
testModel: TestModel,
testModel2: TestModel,
connectableComponentWrapper: ReactWrapper<ConnectableComponentProps<TestModel>, {}, ConnectableComponent<TestModel>>,
connectableComponentProps: ConnectableComponentProps<TestModel>,
mapModelToProps,
createPublishEventProps,
publishEventProps,
userAlternativeViewContext,
otherProps = { other1: 'other-value' };
function createModel(options: TestOptions) {
if (options.useRenderModelSelectorDecorator) {
return new TestModel2();
}
if (options.useRenderModelSelectorFunction) {
return new TestModel3();
}
return new TestModel();
}
function setup(options: TestOptions) {
router = new Router();
testModel = createModel(options);
router.addModel('model-id', testModel);
router.observeEventsOn('model-id', testModel);
testModel2 = new TestModel();
router.addModel('model-id2', testModel2);
router.observeEventsOn('model-id2', testModel2);
connectableComponentProps = {
modelId: 'model-id'
};
if (options.useMapModelToProps) {
mapModelToProps = (model: TestModel | MappedModel, publishEventProps: any) => {
return {
foo: model.value,
publishEventProps,
...model
};
};
}
if (options.useCreatePublishEventProps) {
publishEventProps = {
publishEvent1: () => {
}
};
createPublishEventProps = (publishEvent: PublishEvent) => publishEventProps;
}
if (options.useAlternativeViewContext) {
userAlternativeViewContext = 'alternative-view-context';
}
if (options.useConnectFunction) {
const HotView2 = connect(
mapModelToProps,
createPublishEventProps
)(TestModelView2);
connectableComponentWrapper = mount(
<HotView2 {...otherProps}/>,
{context: {router}, childContextTypes: {router: PropTypes.instanceOf(Router)}}
);
connectableComponentWrapper.setProps(connectableComponentProps);
} else {
connectableComponentWrapper = mount(
<ConnectableComponent
{...connectableComponentProps}
mapModelToProps={mapModelToProps}
viewContext={userAlternativeViewContext}
{...otherProps}
/>,
{context: {router}, childContextTypes: {router: PropTypes.instanceOf(Router)}}
);
}
}
function publishAnEventToModel1() {
router.publishEvent('model-id', 'test-event', 'the-event-value');
expect(testModel.value).toEqual('the-event-value');
connectableComponentWrapper.update();
}
function publishAnEventToModel2() {
router.publishEvent('model-id2', 'test-event','the-event-value2');
expect(testModel2.value).toEqual('the-event-value2');
connectableComponentWrapper.update();
}
afterEach(() => {
// console.log(connectableComponentWrapper.debug());
});
describe('ConnectableComponent via connect()', () => {
beforeEach(() => {
setup({useConnectFunction: true, useMapModelToProps: true, useCreatePublishEventProps: true});
});
const getChidViewProps = () => {
return connectableComponentWrapper.childAt(0).childAt(0).props() as ConnectableComponentChildProps<TestModel>;
};
describe('Child view props', () => {
it('passes mapped props', () => {
let props = getChidViewProps();
expect(props.foo).toEqual('initial-value');
});
it('passes publishEventProps to props mapper', () => {
let props = getChidViewProps();
expect(props.publishEventProps).toBe(publishEventProps);
});
it('passes model', () => {
let props = getChidViewProps();
expect(props.model).toBe(testModel);
});
it('passes publishEventProps', () => {
let props = getChidViewProps();
expect(props.publishEvent1).toBeDefined();
});
it('passes other props', () => {
let props = getChidViewProps();
expect(props.other1).toEqual('other-value');
});
});
describe('View rendering', () => {
it('Renders the view provided to connect', () => {
expect(connectableComponentWrapper.containsMatchingElement(<TestModelView2/>)).toBeTruthy();
});
});
});
describe('ConnectableComponent directly', () => {
const getChidViewProps = () => {
return connectableComponentWrapper.childAt(0).props() as ConnectableComponentChildProps<TestModel>;
};
describe('Child view props', () => {
beforeEach(() => {
setup({useConnectFunction: false});
});
it('passes modelId', () => {
let props = getChidViewProps();
expect(props.modelId).toEqual('model-id');
});
it('passes router', () => {
let props = getChidViewProps();
expect(props.router).toBe(router);
});
it('passes model', () => {
let props = getChidViewProps();
expect(props.model).toBe(testModel);
});
it('passes other props', () => {
let props = getChidViewProps();
expect(props.other1).toEqual('other-value');
});
});
describe('Re-renders', () => {
beforeEach(() => {
setup({useConnectFunction: false});
});
it('Re-renders when model updates', () => {
publishAnEventToModel1();
let props = getChidViewProps();
expect(props.model.value).toBe('the-event-value');
});
});
describe('Model Subscription', () => {
beforeEach(() => {
setup({useConnectFunction: false});
});
it('Re-subscribes to new model when modelId changes', () => {
const newProps = {
...connectableComponentWrapper.props(),
modelId: 'model-id2',
};
connectableComponentWrapper.setProps(newProps);
connectableComponentWrapper.update();
publishAnEventToModel2();
let props = getChidViewProps();
expect(props.foo).toBe('the-event-value2');
});
});
describe('Publish Event Context', () => {
beforeEach(() => {
setup({useConnectFunction: false});
});
// Cant test hooks yet, will test using state below
// https://github.com/enzymejs/enzyme/issues/2011
xit('Can publish event via context', () => {
const childViewContext = connectableComponentWrapper.context();
let publishEvent: PublishModelEventDelegate = React.useContext(PublishModelEventContext);
publishEvent('test-event', 'the-event-value');
connectableComponentWrapper.update();
let props = getChidViewProps();
expect(props.foo).toBe('the-event-value');
});
// Note this is a a best effort to test the context hook created via state
it('publishEvent set', () => {
const state = connectableComponentWrapper.state();
state.publishEvent('test-event', 'the-event-value');
connectableComponentWrapper.update();
let props = getChidViewProps();
expect(props.model.value).toBe('the-event-value');
});
it('publishEvent recreated on modle change', () => {
const newProps = {
...connectableComponentWrapper.props(),
modelId: 'model-id2',
};
connectableComponentWrapper.setProps(newProps);
connectableComponentWrapper.update();
const state = connectableComponentWrapper.state();
state.publishEvent('test-event', 'the-event-value');
connectableComponentWrapper.update();
let props = getChidViewProps();
expect(props.model.value).toBe('the-event-value');
expect(testModel2.value).toBe('the-event-value');
});
});
describe('View rendering', () => {
it('Renders the view found via @viewBinding', () => {
setup({useConnectFunction: false});
expect(connectableComponentWrapper.containsMatchingElement(<TestModelView1/>)).toBeTruthy();
});
it('Renders alternative view found via @viewBinding', () => {
setup({useConnectFunction: false, useAlternativeViewContext: true});
expect(connectableComponentWrapper.containsMatchingElement(<TestModelView3/>)).toBeTruthy();
});
});
describe('Overriding model/state selector', () => {
function testModelHasBeenReplacedWithMappedModel(expectedValue3) {
let props = getChidViewProps();
let mappedModel = props.model as any as MappedModel;
expect(mappedModel.value2).toBe('initial-value');
expect(mappedModel.value3).toBe(expectedValue3);
publishAnEventToModel1();
props = getChidViewProps();
mappedModel = props.model as any as MappedModel;
expect(mappedModel.value2).toBe('the-event-value');
}
function testSwappedModelPassedToMapModelToPropsFunction(expectedValue3) {
let props = getChidViewProps();
expect(props.value2).toBe('initial-value');
expect(props.value3).toBe(expectedValue3);
publishAnEventToModel1();
props = getChidViewProps();
expect(props.value2).toBe('the-event-value');
}
describe('using @stateToRenderSelector', () => {
it('Swaps the model for that returned by the function decorated with a @stateToRenderSelector decorator', () => {
setup({useConnectFunction: false, useRenderModelSelectorDecorator: true});
testModelHasBeenReplacedWithMappedModel('value-3');
});
it('passes the swapped model to mapModelToProps function', () => {
setup({useConnectFunction: false, useRenderModelSelectorDecorator: true, useMapModelToProps: true});
testSwappedModelPassedToMapModelToPropsFunction('value-3');
});
});
describe('using state to render function', () => {
it('Swaps the model for that returned by the function decorated with a @stateToRenderSelector decorator', () => {
setup({useConnectFunction: false, useRenderModelSelectorFunction: true});
testModelHasBeenReplacedWithMappedModel('value-3.1');
});
it('passes the swapped model to mapModelToProps function', () => {
setup({useConnectFunction: false, useRenderModelSelectorFunction: true, useMapModelToProps: true});
testSwappedModelPassedToMapModelToPropsFunction('value-3.1');
});
});
});
});
}); | the_stack |
import { runInAction } from "mobx";
import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3";
import Iso8601 from "terriajs-cesium/Source/Core/Iso8601";
import JulianDate from "terriajs-cesium/Source/Core/JulianDate";
import HeightReference from "terriajs-cesium/Source/Scene/HeightReference";
import loadJson from "../../../../lib/Core/loadJson";
import loadText from "../../../../lib/Core/loadText";
import TerriaError from "../../../../lib/Core/TerriaError";
import CommonStrata from "../../../../lib/Models/Definition/CommonStrata";
import GeoJsonCatalogItem from "../../../../lib/Models/Catalog/CatalogItems/GeoJsonCatalogItem";
import Terria from "../../../../lib/Models/Terria";
import updateModelFromJson from "../../../../lib/Models/Definition/updateModelFromJson";
import { JsonObject } from "../../../../lib/Core/Json";
import GeoJsonDataSource from "terriajs-cesium/Source/DataSources/GeoJsonDataSource";
describe("GeoJsonCatalogItem - with cesium primitives", function() {
let terria: Terria;
let geojson: GeoJsonCatalogItem;
beforeEach(function() {
terria = new Terria({
baseUrl: "./"
});
geojson = new GeoJsonCatalogItem("test-geojson", terria);
geojson.setTrait(CommonStrata.user, "forceCesiumPrimitives", true);
});
describe("GeoJsonCatalogItem", function() {
it("reloads when the URL is changed", async function() {
geojson.setTrait(
CommonStrata.user,
"url",
"data:application/json;base64,eyJ0eXBlIjoiRmVhdHVyZUNvbGxlY3Rpb24iLCJmZWF0dXJlcyI6W3sidHlwZSI6IkZlYXR1cmUiLCJwcm9wZXJ0aWVzIjp7fSwiZ2VvbWV0cnkiOnsidHlwZSI6IlBvaW50IiwiY29vcmRpbmF0ZXMiOlsxNDgsLTMxLjNdfX1dfQ=="
);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
?.getValue(JulianDate.now())
.equalsEpsilon(Cartesian3.fromDegrees(148.0, -31.3), 0.0001)
).toBeTruthy("Doesn't match first location");
geojson.setTrait(
CommonStrata.user,
"url",
"data:application/json;base64,eyJ0eXBlIjoiRmVhdHVyZUNvbGxlY3Rpb24iLCJmZWF0dXJlcyI6W3sidHlwZSI6IkZlYXR1cmUiLCJwcm9wZXJ0aWVzIjp7fSwiZ2VvbWV0cnkiOnsidHlwZSI6IlBvaW50IiwiY29vcmRpbmF0ZXMiOlsxNTEsLTMzLjhdfX1dfQ=="
);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
?.getValue(JulianDate.now())
.equalsEpsilon(Cartesian3.fromDegrees(151.0, -33.8), 0.0001)
).toBeTruthy("Doesn't match updated location");
});
});
describe("loading in EPSG:28356", function() {
it("works by URL", async function() {
geojson.setTrait(
CommonStrata.user,
"url",
"test/GeoJSON/bike_racks.geojson"
);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works by string", async function() {
const geojsonString = await loadText("test/GeoJSON/bike_racks.geojson");
geojson.setTrait(CommonStrata.user, "geoJsonString", geojsonString);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works by data object", async function() {
const geojsonObject = await loadJson("test/GeoJSON/bike_racks.geojson");
geojson.setTrait(CommonStrata.user, "geoJsonData", geojsonObject);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works with zip", async function() {
geojson.setTrait(CommonStrata.user, "url", "test/GeoJSON/bike_racks.zip");
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
/* it("have default dataUrl and dataUrlType", function() {
geojson.updateFromJson({
url: "test/GeoJSON/bike_racks.geojson"
});
expect(geojson.dataUrl).toBe("test/GeoJSON/bike_racks.geojson");
expect(geojson.dataUrlType).toBe("direct");
})
it("use provided dataUrl", function(done) {
geojson.url = "test/GeoJSON/bike_racks.geojson";
geojson.dataUrl = "test/test.html";
geojson.dataUrlType = "fake type";
geojson.load().then(function() {
expect(geojson.dataSource.entities.values.length).toBeGreaterThan(0);
expect(geojson.dataUrl).toBe("test/test.html");
expect(geojson.dataUrlType).toBe("fake type");
done();
});
})
it("works by blob", function(done) {
loadBlob("test/GeoJSON/bike_racks.geojson").then(function(blob) {
geojson.data = blob;
geojson.dataSourceUrl = "anything.geojson";
geojson.load().then(function() {
expect(geojson.dataSource.entities.values.length).toBeGreaterThan(0);
done();
});
});
}); */
});
describe("loading in CRS:84", function() {
it("works by URL", async function() {
geojson.setTrait(
CommonStrata.user,
"url",
"test/GeoJSON/cemeteries.geojson"
);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works by string", async function() {
const geojsonString = await loadText("test/GeoJSON/cemeteries.geojson");
geojson.setTrait(CommonStrata.user, "geoJsonString", geojsonString);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works by blob", async function() {
const blob = await loadJson("test/GeoJSON/cemeteries.geojson");
geojson.setTrait(CommonStrata.user, "geoJsonData", <JsonObject>blob);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works with zip", async function() {
geojson.setTrait(CommonStrata.user, "url", "test/GeoJSON/cemeteries.zip");
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
});
describe("loading without specified CRS (assumes EPSG:4326)", function() {
it("works by URL", async function() {
geojson.setTrait(CommonStrata.user, "url", "test/GeoJSON/gme.geojson");
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works by string", async function() {
const geojsonString = await loadText("test/GeoJSON/gme.geojson");
geojson.setTrait(CommonStrata.user, "geoJsonString", geojsonString);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works by blob", async function() {
const blob = await loadJson("test/GeoJSON/gme.geojson");
geojson.setTrait(CommonStrata.user, "geoJsonData", <JsonObject>blob);
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
it("works with zip", async function() {
geojson.setTrait(CommonStrata.user, "url", "test/GeoJSON/cemeteries.zip");
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values.length
).toBeGreaterThan(0);
expect(
(geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position
).toBeDefined();
});
});
// describe('loading Esri-style GeoJSON with an "envelope"', function() {
// it("works by URL", async function() {
// geojson.setTrait(
// CommonStrata.user,
// "url",
// "test/GeoJSON/EsriEnvelope.geojson"
// );
// await geojson.loadMapItems();
// expect(geojson.mapItems.length).toEqual(1);
// expect((geojson.mapItems[0] as GeoJsonDataSource).entities.values.length).toBeGreaterThan(0);
// expect((geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position).toBeDefined();
// });
//
// it("works by string", async function() {
// const geojsonString = await loadText("test/GeoJSON/EsriEnvelope.geojson");
// geojson.setTrait(CommonStrata.user, "geoJsonString", geojsonString);
// await geojson.loadMapItems();
// expect(geojson.mapItems.length).toEqual(1);
// expect((geojson.mapItems[0] as GeoJsonDataSource).entities.values.length).toBeGreaterThan(0);
// expect((geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position).toBeDefined();
// });
//
// it("works by blob", async function() {
// const blob = await loadJson("test/GeoJSON/EsriEnvelope.geojson");
// geojson.setTrait(CommonStrata.user, "geoJsonData", <JsonObject>blob);
// await geojson.loadMapItems();
// expect(geojson.mapItems.length).toEqual(1);
// expect((geojson.mapItems[0] as GeoJsonDataSource).entities.values.length).toBeGreaterThan(0);
// expect((geojson.mapItems[0] as GeoJsonDataSource).entities.values[0].position).toBeDefined();
// });
// });
describe("error handling", function() {
it("fails gracefully when the data at a URL is not JSON", async () => {
geojson.setTrait(CommonStrata.user, "url", "test/KML/vic_police.kml");
const error = (await geojson.loadMapItems()).error;
expect(error).toBeDefined("Load should not succeed");
});
it("fails gracefully when the provided string is not JSON", async () => {
const s = await loadText("test/KML/vic_police.kml");
geojson.setTrait(CommonStrata.user, "geoJsonString", s);
const error = (await geojson.loadMapItems()).error;
expect(error).toBeDefined("Load should not succeed");
});
it("fails gracefully when the data at a URL is JSON but not GeoJSON", async () => {
geojson.setTrait(CommonStrata.user, "url", "test/CZML/verysimple.czml");
const error = (await geojson.loadMapItems()).error;
expect(error).toBeDefined("Load should not succeed");
});
it("fails gracefully when the provided string is JSON but not GeoJSON", async () => {
const s = await loadText("test/CZML/verysimple.czml");
geojson.setTrait(CommonStrata.user, "geoJsonString", s);
const error = (await geojson.loadMapItems()).error;
expect(error).toBeDefined("Load should not succeed");
});
/*
it("fails gracefully when the provided blob is JSON but not GeoJSON", function(done) {
loadBlob("test/CZML/verysimple.czml").then(function(blob) {
geojson.data = blob;
geojson.dataSourceUrl = "anything.czml";
geojson
.load()
.then(function() {
done.fail("Load should not succeed.");
})
.otherwise(function(e) {
expect(e instanceof TerriaError).toBe(true);
done();
});
});
}); */
});
// describe("Adding and removing attribution", function() {
// var currentViewer;
// beforeEach(function() {
// currentViewer = geojson.terria.currentViewer;
// geojson.url = "test/GeoJSON/polygon.topojson";
// terria.disclaimerListener = function(member, callback) {
// callback();
// };
// geojson.isEnabled = true;
// });
// it("can add attribution", function(done) {
// spyOn(currentViewer, "addAttribution");
// geojson.load();
// geojson._loadForEnablePromise.then(function() {
// expect(currentViewer.addAttribution).toHaveBeenCalled();
// done();
// });
// });
// it("can remove attribution", function(done) {
// spyOn(currentViewer, "removeAttribution");
// geojson.load();
// geojson._loadForEnablePromise.then(function() {
// geojson.isEnabled = false;
// expect(currentViewer.removeAttribution).toHaveBeenCalled();
// done();
// });
// });
// });
describe("Support for time-varying geojson", () => {
it("Associates features with discrete times", async () => {
geojson.setTrait(
CommonStrata.user,
"url",
"test/GeoJSON/time-based.geojson"
);
geojson.setTrait(CommonStrata.user, "timeProperty", "year");
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
const entities = (geojson.mapItems[0] as GeoJsonDataSource).entities
.values;
expect(entities.length).toEqual(2);
const entity1 = entities[0];
expect(
entity1.availability?.start.equals(
JulianDate.fromDate(new Date("2021"))
)
).toBeTruthy();
expect(
entity1.availability?.stop.equals(Iso8601.MAXIMUM_VALUE)
).toBeTruthy();
const entity2 = entities[1];
expect(
entity2.availability?.start.equals(
JulianDate.fromDate(new Date("2019"))
)
).toBeTruthy();
expect(
entity2.availability?.stop.equals(JulianDate.fromDate(new Date("2021")))
).toBeTruthy();
});
});
describe("Support for geojson with extruded heights", () => {
it("Sets polygon height properties correctly", async () => {
geojson.setTrait(CommonStrata.user, "url", "test/GeoJSON/height.geojson");
geojson.setTrait(CommonStrata.user, "heightProperty", "someProperty");
await geojson.loadMapItems();
expect(geojson.mapItems.length).toEqual(1);
const entities = (geojson.mapItems[0] as GeoJsonDataSource).entities
.values;
expect(entities.length).toEqual(2);
const entity1 = entities[0];
expect(
entity1.polygon?.extrudedHeight?.getValue(
terria.timelineClock.currentTime
)
).toBe(10);
expect(
entity1.polygon?.heightReference?.getValue(
terria.timelineClock.currentTime
)
).toBe(HeightReference.CLAMP_TO_GROUND);
const entity2 = entities[1];
expect(
entity2.polygon?.extrudedHeight?.getValue(
terria.timelineClock.currentTime
)
).toBe(20);
expect(
entity2.polygon?.heightReference?.getValue(
terria.timelineClock.currentTime
)
).toBe(HeightReference.CLAMP_TO_GROUND);
expect(
entity2.polygon?.extrudedHeightReference?.getValue(
terria.timelineClock.currentTime
)
).toBe(HeightReference.RELATIVE_TO_GROUND);
});
});
describe("Per features styling", function() {
it("Applies styles to features according to their properties, respecting string case", async function() {
const name = "PETER FAGANS GRAVE";
const fill = "#0000ff";
runInAction(() => {
updateModelFromJson(geojson, CommonStrata.override, {
name: "test",
type: "geojson",
url: "test/GeoJSON/cemeteries.geojson",
perPropertyStyles: [
{
properties: { NAME: name },
style: {
fill: fill
},
caseSensitive: true
}
]
});
});
await geojson.loadMapItems();
const entity = (geojson
.mapItems[0] as GeoJsonDataSource).entities.values.find(
e => e.properties?.getValue(JulianDate.now()).NAME === name
);
expect(entity).toBeDefined();
expect(entity?.properties?.getValue(JulianDate.now())?.fill).toEqual(
fill
);
});
});
});
describe("GeoJsonCatalogItem - with CZML template", function() {
let terria: Terria;
let geojson: GeoJsonCatalogItem;
beforeEach(function() {
terria = new Terria({
baseUrl: "./"
});
geojson = new GeoJsonCatalogItem("test-geojson", terria);
});
describe("Support for czml templating", () => {
it("Sets polygon height properties correctly", async () => {
geojson.setTrait(CommonStrata.user, "url", "test/GeoJSON/points.geojson");
geojson.setTrait(CommonStrata.user, "czmlTemplate", {
cylinder: {
length: {
reference: "#properties.height"
},
topRadius: {
reference: "#properties.radius"
},
bottomRadius: {
reference: "#properties.radius"
},
material: {
solidColor: {
color: {
rgba: [0, 200, 0, 20]
}
}
}
}
});
await geojson.loadMapItems();
const entities = (geojson.mapItems[0] as GeoJsonDataSource).entities
.values;
console.log(entities);
expect(entities.length).toEqual(5);
const entity1 = entities[0];
expect(
entity1.cylinder?.length?.getValue(terria.timelineClock.currentTime)
).toBe(10);
expect(
entity1.cylinder?.bottomRadius?.getValue(
terria.timelineClock.currentTime
)
).toBe(10);
expect(entity1.properties?.someOtherProp?.getValue()).toBe("what");
const entity2 = entities[1];
expect(
entity2.cylinder?.length?.getValue(terria.timelineClock.currentTime)
).toBe(20);
expect(
entity2.cylinder?.bottomRadius?.getValue(
terria.timelineClock.currentTime
)
).toBe(5);
expect(entity2.properties?.someOtherProp?.getValue()).toBe("ok");
});
});
}); | the_stack |
import {
TemplateDataFetchers,
PageTemplateData,
TemplateDoc,
NoteTemplateData,
TemplateAnalysis,
} from './types'
import fromPairs from 'lodash/fromPairs'
interface GeneratorInput {
templateAnalysis: TemplateAnalysis
dataFetchers: TemplateDataFetchers
normalizedPageUrls: string[]
annotationUrls: string[]
}
/** Simply exists to attempt to clean up typedefs for some intermediate variables. */
interface UrlMappedData<T> {
[url: string]: T
}
export const joinTags = (tags?: string[]): string | undefined =>
tags == null
? undefined
: tags.reduce(
(acc, tag, i) =>
`${acc}#${tag}${i === tags.length - 1 ? '' : ' '}`,
'',
)
const groupNotesByPages = (
notes: UrlMappedData<NoteTemplateData>,
): UrlMappedData<NoteTemplateData[]> => {
const grouped: UrlMappedData<NoteTemplateData[]> = {}
for (const { pageUrl, ...noteData } of Object.values(notes)) {
grouped[pageUrl] = [
...(grouped[pageUrl] ?? []),
{ pageUrl, ...noteData },
]
}
return grouped
}
const omitEmptyFields = (docs: TemplateDoc[]): TemplateDoc[] =>
docs.map((doc) => {
if (doc.Notes) {
doc.Notes = doc.Notes.map(omitEmpty)
}
if (doc.Pages) {
doc.Pages = doc.Pages.map(({ Notes, ...pageTemplateDoc }) => {
if (!Notes?.length) {
return omitEmpty(pageTemplateDoc)
}
return {
...omitEmpty(pageTemplateDoc),
Notes: Notes.map(omitEmpty),
}
})
}
return omitEmpty(doc)
})
const omitEmpty = <T extends any>(obj: T): T => {
const clone = { ...obj }
for (const key in clone) {
if (clone[key] == null || clone[key]?.length === 0) {
delete clone[key]
}
}
return clone
}
// This function covers all single page cases + multi-page cases when no notes are referenced
const generateForPages = async ({
templateAnalysis,
dataFetchers,
...params
}: GeneratorInput): Promise<TemplateDoc[]> => {
const pageData = await dataFetchers.getPages(params.normalizedPageUrls)
let noteLinks: UrlMappedData<string> = {}
let pageTags: UrlMappedData<string[]> = {}
let noteTags: UrlMappedData<string[]> = {}
let notes: UrlMappedData<NoteTemplateData> = {}
let noteUrlsForPages: UrlMappedData<string[]> = {}
if (templateAnalysis.requirements.pageTags) {
pageTags = await dataFetchers.getTagsForPages(params.normalizedPageUrls)
}
if (
templateAnalysis.requirements.note ||
templateAnalysis.requirements.noteTags ||
templateAnalysis.requirements.noteLink
) {
noteUrlsForPages = await dataFetchers.getNoteIdsForPages(
params.normalizedPageUrls,
)
}
// At this point, all needed data is fetched and we decide how to shape the template doc
const templateDocs: TemplateDoc[] = []
for (const [normalizedPageUrl, { fullTitle, fullUrl }] of Object.entries(
pageData,
)) {
const tags = pageTags[normalizedPageUrl] ?? []
const noteUrls = noteUrlsForPages[normalizedPageUrl] ?? []
if (templateAnalysis.requirements.note) {
notes = await dataFetchers.getNotes(noteUrls)
}
if (templateAnalysis.requirements.noteTags) {
noteTags = await dataFetchers.getTagsForNotes(noteUrls)
}
if (templateAnalysis.requirements.noteLink) {
noteLinks = await dataFetchers.getNoteLinks(noteUrls)
}
const pageLink =
templateAnalysis.requirements.pageLink &&
(
await dataFetchers.getPageLinks({
[normalizedPageUrl]: { annotationUrls: noteUrls },
})
)[normalizedPageUrl]
templateDocs.push({
PageTitle: fullTitle,
PageTags: joinTags(tags),
PageTagList: tags,
PageUrl: fullUrl,
PageLink: pageLink,
Notes: noteUrls.map((url) => ({
NoteText: notes[url].comment,
NoteHighlight: notes[url].body,
NoteTagList: noteTags[url],
NoteTags: joinTags(noteTags[url]),
NoteLink: noteLinks[url],
})),
title: fullTitle,
tags,
url: fullUrl,
})
}
return templateAnalysis.expectedContext === 'page-list'
? [{ Pages: templateDocs }]
: templateDocs
}
// This function covers all single + multi-note cases + multi-page cases when notes are referenced
const generateForNotes = async ({
templateAnalysis,
dataFetchers,
...params
}: GeneratorInput): Promise<TemplateDoc[]> => {
const notes = await dataFetchers.getNotes(params.annotationUrls)
const notesByPageUrl = groupNotesByPages(notes)
let noteTags: UrlMappedData<string[]> = {}
let noteLinks: UrlMappedData<string> = {}
let pages: UrlMappedData<PageTemplateData> = {}
let pageTags: UrlMappedData<string[]> = {}
let pageLinks: UrlMappedData<string> = {}
if (templateAnalysis.requirements.page) {
pages = await dataFetchers.getPages(params.normalizedPageUrls)
}
if (templateAnalysis.requirements.pageTags) {
pageTags = await dataFetchers.getTagsForPages(params.normalizedPageUrls)
}
if (templateAnalysis.requirements.noteTags) {
noteTags = await dataFetchers.getTagsForNotes(params.annotationUrls)
}
if (templateAnalysis.requirements.pageLink) {
pageLinks = await dataFetchers.getPageLinks(
fromPairs(
params.normalizedPageUrls.map((normalizedPageUrl) => [
normalizedPageUrl,
{
annotationUrls: Object.values(notes)
.filter((note) => note.pageUrl)
.map((note) => note.url),
},
]),
),
)
}
if (templateAnalysis.requirements.noteLink) {
noteLinks = await dataFetchers.getNoteLinks(params.annotationUrls)
}
// At this point, all needed data is fetched and we decide how to shape the template doc
// User clicked to copy all notes on page but they only want to render page info, so set only page data
if (
!templateAnalysis.requirements.note &&
!templateAnalysis.requirements.noteLink &&
!templateAnalysis.requirements.noteTags
) {
const templateDocs: TemplateDoc[] = []
for (const [pageUrl, { fullTitle, fullUrl }] of Object.entries(pages)) {
templateDocs.push({
PageTitle: fullTitle,
PageTags: joinTags(pageTags[pageUrl]),
PageTagList: pageTags[pageUrl],
PageUrl: fullUrl,
PageLink: pageLinks[pageUrl],
title: fullTitle,
tags: pageTags[pageUrl],
url: fullUrl,
})
}
return templateDocs
}
if (templateAnalysis.expectedContext === 'note') {
// but they are using the top-level data (NoteText, etc.) so return
const templateDocs: TemplateDoc[] = []
for (const [noteUrl, { body, comment, pageUrl }] of Object.entries(
notes,
)) {
const pageData = pages[pageUrl] ?? ({} as PageTemplateData)
templateDocs.push({
NoteText: comment,
NoteHighlight: body,
NoteTagList: noteTags[noteUrl],
NoteTags: joinTags(noteTags[noteUrl]),
NoteLink: noteLinks[noteUrl],
PageTitle: pageData.fullTitle,
PageUrl: pageData.fullUrl,
PageTags: joinTags(pageTags[pageUrl]),
PageTagList: pageTags[pageUrl],
PageLink: pageLinks[pageUrl],
title: pageData.fullTitle,
url: pageData.fullUrl,
tags: pageTags[pageUrl],
})
}
return templateDocs
}
// Everything after here is in the context of 'page' or 'page-list'
// If page is not required, we simply need to set the array of Notes
if (!templateAnalysis.requirements.page) {
const templateDocs: TemplateDoc[] = []
for (const [noteUrl, { body, comment }] of Object.entries(notes)) {
templateDocs.push({
NoteText: comment,
NoteHighlight: body,
NoteTagList: noteTags[noteUrl],
NoteTags: joinTags(noteTags[noteUrl]),
NoteLink: noteLinks[noteUrl],
})
}
return [{ Notes: templateDocs }]
}
const docs: TemplateDoc[] = []
// This covers all other cases where notes are needed
for (const [pageUrl, { fullUrl, fullTitle }] of Object.entries(pages)) {
docs.push({
PageTitle: fullTitle,
PageUrl: fullUrl,
PageTags: joinTags(pageTags[pageUrl]),
PageTagList: pageTags[pageUrl],
PageLink: pageLinks[pageUrl],
title: fullTitle,
url: fullUrl,
tags: pageTags[pageUrl],
Notes: notesByPageUrl[pageUrl].map(
({ url: noteUrl, body, comment }) => ({
NoteText: comment,
NoteHighlight: body,
NoteTagList: noteTags[noteUrl],
NoteTags: joinTags(noteTags[noteUrl]),
NoteLink: noteLinks[noteUrl],
PageTitle: fullTitle,
PageUrl: fullUrl,
PageTags: joinTags(pageTags[pageUrl]),
PageTagList: pageTags[pageUrl],
PageLink: pageLinks[pageUrl],
title: fullTitle,
url: fullUrl,
tags: pageTags[pageUrl],
}),
),
})
}
return templateAnalysis.expectedContext === 'page-list'
? [{ Pages: docs }]
: docs
}
export default async function generateTemplateDocs(
params: GeneratorInput,
): Promise<TemplateDoc[]> {
let docs: TemplateDoc[] = []
// This condition is needed as under some contexts, notes aren't specified upfront (page copy-paster), but users can still reference a page's notes in their templates
// so we need to get the note URLs by looking them up using the page URLs
// TODO: Can we just have one function but fetch the note URLs in this parent scope (if needed) and pass them down?
if (!params.annotationUrls.length) {
docs = await generateForPages(params)
} else if (params.annotationUrls.length >= 1) {
docs = await generateForNotes(params)
}
return omitEmptyFields(docs)
} | the_stack |
import { PoetBlockAnchor } from '@po.et/poet-js'
import { DateTime } from 'luxon'
import { Collection, Db } from 'mongodb'
import * as Pino from 'pino'
import { identity, map, filter, tap, complement } from 'ramda'
import { TransactionReceipt } from 'web3-core'
import { EthereumRegistryContract } from 'Helpers/EthereumRegistryContract'
import { IPFS } from 'Helpers/IPFS'
import { childWithFileName } from 'Helpers/Logging'
import { asyncPipe } from 'Helpers/asyncPipe'
import { ClaimIPFSHashPair } from 'Interfaces'
export interface Dependencies {
readonly logger: Pino.Logger
readonly db: Db
readonly ipfs: IPFS
readonly ethereumRegistryContract: EthereumRegistryContract
}
export interface Configuration {
readonly maximumUnconfirmedTransactionAgeInSeconds: number
}
export interface Arguments {
readonly dependencies: Dependencies
readonly configuration: Configuration
}
export interface Health {
readonly healthy: boolean
}
export interface Business {
readonly getHealth: () => Promise<Health>
readonly createDbIndices: () => Promise<void>
readonly insertClaimIdFilePair: (claimId: string, claimFile: string) => Promise<void>
readonly setBatchDirectory: (claimFiles: ReadonlyArray<string>, ipfsDirectoryHash: string) => Promise<void>
readonly setAnchors: (poetAnchors: ReadonlyArray<PoetBlockAnchor>) => Promise<void>
readonly confirmBatchDirectory: (claimFiles: ReadonlyArray<string>, ipfsDirectoryHash: string) => Promise<void>
readonly confirmClaimFiles: (claimIPFSHashPairs: ReadonlyArray<ClaimIPFSHashPair>) => Promise<void>
readonly uploadNextAnchorReceipt: () => Promise<void>
readonly uploadNextClaimFileAnchorReceiptPair: () => Promise<void>
readonly writeNextDirectoryToEthereum: () => Promise<void>
readonly setRegistryIndex: (
confirmClaimAndAnchorReceiptDirectory: string,
registryIndex: number,
transactionHash: string,
blockHash: string,
blockNumber: number,
) => Promise<void>
readonly getEthereumTransactionReceipts: () => Promise<void>
}
interface DbEntry {
readonly claimId: string
readonly claimFile: string
readonly anchorReceipt?: Partial<PoetBlockAnchor>
readonly anchorReceiptFile?: string
readonly claimFileConfirmed?: boolean
readonly batchDirectoryConfirmed?: boolean
readonly claimAndAnchorReceiptDirectory?: string
readonly registryIndex?: number
readonly registryAdditionTransactionReceipt?: {
readonly transactionHash?: string
readonly transactionCreationDate?: Date
readonly blockHash?: string
readonly blockNumber?: number, // comma due to some tslint randomness, will move to eslint in the future
}
readonly onCidAdded?: {
readonly transactionHash?: string
readonly blockHash?: string
readonly blockNumber?: number, // comma due to some tslint randomness, will move to eslint in the future
}
}
export const Business = ({
dependencies: {
logger,
db,
ipfs,
ethereumRegistryContract,
},
configuration: {
maximumUnconfirmedTransactionAgeInSeconds,
},
}: Arguments): Business => {
const businessLogger: Pino.Logger = childWithFileName(logger, __filename)
const claimAnchorReceiptsCollection: Collection<DbEntry> = db.collection('claimAnchorReceipts')
const getHealth = async () => ({
healthy: true,
})
const createDbIndices = async () => {
await claimAnchorReceiptsCollection.createIndex({ claimId: 1 }, { unique: true })
await claimAnchorReceiptsCollection.createIndex({ claimFile: 1 }, { unique: true })
await claimAnchorReceiptsCollection.createIndex({ 'anchorReceipt.ipfsDirectoryHash': 1 })
await claimAnchorReceiptsCollection.createIndex(
{ claimFileConfirmed: 1, batchDirectoryConfirmed: 1, anchorReceiptFile: 1 },
)
await claimAnchorReceiptsCollection.createIndex(
{ claimAndAnchorReceiptDirectory: 1 },
{ unique: true, sparse: true },
)
}
const insertClaimIdFilePair = async (claimId: string, claimFile: string): Promise<void> => {
await claimAnchorReceiptsCollection.insertOne({ claimId, claimFile })
}
const setBatchDirectory = async (claimFiles: ReadonlyArray<string>, batchDirectory: string) => {
const logger = businessLogger.child({ method: 'setBatchDirectory' })
logger.debug({ claimFiles, batchDirectory }, 'Setting batch directory')
const setBatchDirectoryForClaimFile = (claimFile: string) =>
claimAnchorReceiptsCollection.updateOne(
{ claimFile },
{ $set: { 'anchorReceipt.ipfsDirectoryHash': batchDirectory } },
)
await Promise.all(claimFiles.map(setBatchDirectoryForClaimFile))
logger.info({ batchDirectory, claimFiles }, 'Batch directory set successfully')
}
const setAnchors = async (poetAnchors: ReadonlyArray<PoetBlockAnchor>) => {
const logger = businessLogger.child({ method: 'setAnchors' })
logger.debug({ poetAnchors }, 'Setting anchor receipts')
const setAnchorReceipt = (anchorReceipt: PoetBlockAnchor) =>
claimAnchorReceiptsCollection.updateOne(
{ 'anchorReceipt.ipfsDirectoryHash': anchorReceipt.ipfsDirectoryHash },
{ $set: { anchorReceipt } },
)
await Promise.all(poetAnchors.map(setAnchorReceipt))
logger.info({ poetAnchors }, 'Anchors receipts set')
}
const confirmBatchDirectory = async (
claimFiles: ReadonlyArray<string>,
batchDirectory: string,
) => {
const logger = businessLogger.child({ method: 'confirmBatchDirectory' })
logger.debug({ claimFiles, batchDirectory }, 'Confirming batch directory')
const confirmBatchDirectory = (claimFile: string) =>
claimAnchorReceiptsCollection.updateOne(
{ claimFile, 'anchorReceipt.ipfsDirectoryHash': batchDirectory },
{ $set: { batchDirectoryConfirmed: true } },
)
await Promise.all(claimFiles.map(confirmBatchDirectory))
logger.info({ claimFiles, batchDirectory }, 'Batch directory confirmed')
const findUnexpectedBatchDirectoryMatch = (claimFile: string) =>
claimAnchorReceiptsCollection.findOne(
{ claimFile, 'anchorReceipt.ipfsDirectoryHash': { $ne: batchDirectory } },
{ projection: { _id: 0, claimFile: 1, ipfsDirectoryHash: 1 } },
)
const unexpectedBatchDirectoryMatches = (await Promise.all(claimFiles.map(findUnexpectedBatchDirectoryMatch)))
.filter(identity)
if (unexpectedBatchDirectoryMatches.length)
logger.warn(
{ unexpectedBatchDirectoryMatches, batchDirectory },
'These claims were expected to have a different Batch Directory.',
)
}
const confirmClaimFiles = async (claimIPFSHashPairs: ReadonlyArray<ClaimIPFSHashPair>) => {
const logger = businessLogger.child({ method: 'confirmClaimFiles' })
logger.debug({ claimIPFSHashPairs }, 'Confirming Claim files')
const confirmClaimFile = ({ claim, ipfsFileHash: claimFile }: ClaimIPFSHashPair) =>
claimAnchorReceiptsCollection.updateOne(
{ claimId: claim.id, claimFile },
{ $set: { claimFileConfirmed: true } },
)
await Promise.all(claimIPFSHashPairs.map(confirmClaimFile))
logger.info({ claimIPFSHashPairs }, 'Confirmed Claim files')
const findUnexpectedClaimFile = ({ claim, ipfsFileHash: claimFile }: ClaimIPFSHashPair) =>
claimAnchorReceiptsCollection.findOne(
{ claimId: claim.id, claimFile: { $ne: claimFile } },
{ projection: { _id: 0, claimId: 1, claimFile: 1 } },
)
const unexpectedClaimFileMatches = (await Promise.all(claimIPFSHashPairs.map(findUnexpectedClaimFile)))
.filter(identity)
if (unexpectedClaimFileMatches.length)
logger.warn({ unexpectedClaimFileMatches }, 'These claims were expected be stored in a different file.')
}
const uploadNextAnchorReceipt = async () => {
const logger = businessLogger.child({ method: 'uploadNextAnchorReceipt' })
const entry = await claimAnchorReceiptsCollection.findOne({
claimFileConfirmed: true,
batchDirectoryConfirmed: true,
anchorReceiptFile: null,
})
if (!entry)
return
logger.debug(entry, 'Storing Anchor Receipt in an IPFS file')
const { claimId, claimFile, anchorReceipt } = entry
const anchorReceiptFile = await ipfs.addJson({ claimId, claimFile, ...anchorReceipt })
logger.info({ anchorReceipt, anchorReceiptFile }, 'Stored Anchor Receipt in an IPFS file')
await claimAnchorReceiptsCollection.updateOne({ claimId }, { $set: { anchorReceiptFile } })
}
const uploadNextClaimFileAnchorReceiptPair = async () => {
const logger = businessLogger.child({ method: 'uploadNextClaimFileAnchorReceiptPair' })
const entry = await claimAnchorReceiptsCollection.findOne({
anchorReceiptFile: { $ne: null },
claimAndAnchorReceiptDirectory: null,
})
if (!entry)
return
logger.debug(entry, 'Storing (claim + anchor receipt) in an IPFS directory')
const { claimId, claimFile, anchorReceiptFile } = entry
const claimAndAnchorReceiptDirectory = await ipfs.createDirectory([ claimFile, anchorReceiptFile ])
logger.info({ ...entry, claimAndAnchorReceiptDirectory }, 'Stored (claim + anchor receipt) in an IPFS Directory')
await claimAnchorReceiptsCollection.updateOne({ claimId }, { $set: { claimAndAnchorReceiptDirectory } })
}
const writeNextDirectoryToEthereum = async () => {
const logger = businessLogger.child({ method: 'registerNextDirectory' })
const entry = await claimAnchorReceiptsCollection.findOneAndUpdate(
{
claimAndAnchorReceiptDirectory: { $ne: null },
$or: [
{ 'registryAdditionTransactionReceipt.transactionCreationDate': null },
{ $and: [
{ 'registryAdditionTransactionReceipt.transactionCreationDate': {
$lt: DateTime.utc().minus({ seconds: maximumUnconfirmedTransactionAgeInSeconds }).toJSDate(),
} },
{ 'registryAdditionTransactionReceipt.blockHash': null },
]},
],
},
{
$set: { 'registryAdditionTransactionReceipt.transactionCreationDate': new Date() },
},
)
if (!entry.value)
return
const { claimId, claimAndAnchorReceiptDirectory } = entry.value
logger.debug(
{ claimId, claimAndAnchorReceiptDirectory },
'Adding (claim + anchor receipt) directory to Ethereum',
)
const transactionHash = await ethereumRegistryContract.addCid(claimAndAnchorReceiptDirectory)
logger.info(
{ claimId, claimAndAnchorReceiptDirectory, transactionHash },
'(claim + anchor receipt) transaction sent',
)
await claimAnchorReceiptsCollection.updateOne(
{ claimAndAnchorReceiptDirectory },
{ $set: { 'registryAdditionTransactionReceipt.transactionHash': transactionHash } },
)
}
const setRegistryIndex = async (
claimAndAnchorReceiptDirectory: string,
registryIndex: number,
transactionHash: string,
blockHash: string,
blockNumber: number,
) => {
const logger = businessLogger.child({ method: 'setRegistryIndex' })
await claimAnchorReceiptsCollection.updateOne(
{ claimAndAnchorReceiptDirectory },
{ $set: { registryIndex, onCidAdded: { transactionHash, blockHash, blockNumber } } },
)
logger.info(
{ claimAndAnchorReceiptDirectory, registryIndex, blockNumber, transactionHash },
'Registry index for (claim + anchor receipt) directory set',
)
}
const getEthereumTransactionReceipts = async () => {
const logger = businessLogger.child({ method: 'getEthereumTransactionReceipts' })
logger.trace('Looking for transactions without confirmation')
const entries = await claimAnchorReceiptsCollection.find(
{
'registryAdditionTransactionReceipt.transactionHash': { $ne: null },
'registryAdditionTransactionReceipt.blockHash': null,
},
{ projection: { 'registryAdditionTransactionReceipt.transactionHash': 1 } },
).toArray()
if (!entries.length) {
logger.trace('No transactions without confirmation found')
return
}
const transactionHashes = entries.map(_ => _.registryAdditionTransactionReceipt.transactionHash)
logger.debug({ transactionHashes }, 'These transactions have no known confirmations yet')
const receiptToSimplified = ({ transactionHash, blockHash, blockNumber }: TransactionReceipt) => ({
transactionHash,
blockHash,
blockNumber,
})
const logErrors = (transactionReceipt: TransactionReceipt) => {
logger.error({ transactionReceipt }, 'Error in transaction receipt')
}
const transactionReceiptIsOk = (transactionReceipt: TransactionReceipt) => transactionReceipt.status
const filterAndLogErrors = asyncPipe(
tap(asyncPipe(
filter(complement(transactionReceiptIsOk)),
map(logErrors),
)),
filter(transactionReceiptIsOk),
)
const getReceipts = asyncPipe(
map(ethereumRegistryContract.getTransactionReceipt),
Promise.all.bind(Promise),
filter(identity),
filterAndLogErrors,
map(receiptToSimplified),
) as (transactionHashes: ReadonlyArray<string>) => Promise<ReadonlyArray<Partial<TransactionReceipt>>>
const receipts = await getReceipts(transactionHashes)
if (!receipts.length) {
logger.trace({ transactionHashes }, 'No transactions receipts available yet for these transactions')
return
}
logger.debug({ receipts }, 'Got these transaction receipts')
await Promise.all(receipts.map(({ transactionHash, blockHash, blockNumber }) =>
claimAnchorReceiptsCollection.updateOne(
{ 'registryAdditionTransactionReceipt.transactionHash': transactionHash },
{ $set: {
'registryAdditionTransactionReceipt.blockHash': blockHash,
'registryAdditionTransactionReceipt.blockNumber': blockNumber,
} },
),
))
logger.info({ receipts }, 'Transaction receipts set')
}
return {
getHealth,
createDbIndices,
insertClaimIdFilePair,
setBatchDirectory,
setAnchors,
confirmBatchDirectory,
confirmClaimFiles,
uploadNextAnchorReceipt,
uploadNextClaimFileAnchorReceiptPair,
writeNextDirectoryToEthereum,
setRegistryIndex,
getEthereumTransactionReceipts,
}
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { NodeModel, TextModel, PathModel } from '../../../src/diagram/objects/node-model';
import { ConnectorModel, BpmnFlowModel, ConnectorShapeModel } from '../../../src/diagram/objects/connector-model';
import { Connector } from '../../../src/diagram/objects/connector';
import { PortVisibility } from '../../../src/diagram/enum/enum';
import { Point } from '../../../src/diagram/primitives/point';
import { Segments, AnnotationConstraints, ConnectorConstraints } from '../../../src/diagram/enum/enum';
import { TextStyle } from '../../../src/diagram/core/appearance';
import { PathAnnotationModel } from '../../../src/diagram/objects/annotation-model';
import { MouseEvents } from '../../../spec/diagram/interaction/mouseevents.spec';
import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec';
/**
* Connector Property Change spec
*/
describe('Diagram Control', () => {
describe('Connetor property change', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram' });
document.body.appendChild(ele);
let connector1: ConnectorModel = {
id: 'connector1', type: 'Straight', sourcePoint: { x: 350, y: 300 },
targetPoint: { x: 450, y: 300 }
};
let connectors2: ConnectorModel =
{
id: 'connector2',
type: 'Straight',
annotations: [
{
id: 'label1',
content: 'Default Shape1', style: { color: 'red' },
constraints: ~AnnotationConstraints.InheritReadOnly
}, {
id: 'label1111',
visibility: false,
content: 'Default Shape2', style: { color: 'red' },
offset: 1,
}
],
constraints: ConnectorConstraints.Default | ConnectorConstraints.ReadOnly,
sourcePoint: { x: 100, y: 100 },
targetPoint: { x: 200, y: 200 },
}
diagram = new Diagram({ width: 600, height: 500, connectors: [connector1, connectors2] });
diagram.appendTo('#diagram');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking connector style property change', (done: Function) => {
diagram.connectors[0].style.strokeColor = 'red';
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.style.strokeColor === 'red').toBe(true);
done();
});
it('Checking connector source point change', (done: Function) => {
diagram.connectors[0].sourcePoint = { x: 300, y: 300 };
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.sourcePoint.x === 300 && connector.sourcePoint.y === 300).toBe(true);
done();
});
it('Checking connector target point change', (done: Function) => {
diagram.connectors[0].targetPoint = { x: 550, y: 200 };
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.targetPoint.x === 550 && connector.targetPoint.y === 200).toBe(true);
done();
});
it('Checking connector type change', (done: Function) => {
diagram.connectors[0].type = 'Orthogonal';
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.type === 'Orthogonal').toBe(true);
done();
});
it('Checking connector corner radius change', (done: Function) => {
diagram.connectors[0].cornerRadius = 20;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.cornerRadius === 20).toBe(true);
done();
});
it('Checking connector target Decorator change', (done: Function) => {
diagram.connectors[0].targetDecorator.style.fill = 'red';
diagram.connectors[0].targetDecorator.shape = 'Diamond';
diagram.connectors[0].targetDecorator.width = 15;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.targetDecorator.style.fill === 'red' && connector.targetDecorator.shape === 'Diamond'
&& connector.targetDecorator.width === 15).toBe(true);
done();
});
it('Checking connector source decorator change', (done: Function) => {
diagram.connectors[0].sourceDecorator.shape = 'Diamond';
diagram.connectors[0].targetDecorator.style.strokeWidth = 4;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.sourceDecorator.shape === 'Diamond' && connector.targetDecorator.style.strokeWidth === 4).toBe(true);
done();
});
it('Checking connector annotation', (done: Function) => {
let mouseEvents: MouseEvents = new MouseEvents();
let label: PathAnnotationModel = (diagram.connectors[1] as ConnectorModel).annotations[1];
expect(label.visibility == false).toBe(true);
(diagram.connectors[1] as ConnectorModel).annotations[1].visibility = true,
diagram.dataBind();
let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content');
expect(label.visibility == true).toBe(true);
mouseEvents.clickEvent(diagramCanvas, 150, 150);
mouseEvents.dblclickEvent(diagramCanvas, 150, 150);
let element = document.getElementById('diagram_editTextBoxDiv');
mouseEvents.clickEvent(diagramCanvas, 200, 200);
mouseEvents.dblclickEvent(diagramCanvas, 200, 200);
let element1 = document.getElementById('diagram_editTextBoxDiv');
expect(element && !element1).toBe(true);
done();
});
it('Checking connector type change to bezier', (done: Function) => {
diagram.connectors[0].type = 'Bezier';
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(((connector.wrapper.children[0]) as PathModel).data === 'M300.5 300C360.46 299.81 489.53999999999996 200.19 549.5 200').toBe(true);
done();
});
});
describe('Connetor property change ', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram8' });
document.body.appendChild(ele);
let node: NodeModel = {
id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 300,
shape: {
type: 'Path', data:
'M540.3643,137.9336L546.7973,159.7016L570.3633,159.7296L550.7723,171.9366L558.9053,194.9966L540.3643,179.4996L521.8223,194.9966L529.9553,171.9366L510.3633,159.7296L533.9313,159.7016L540.3643,137.9336z',
} as PathModel,
ports: [{ id: 'port', offset: { x: 0.5, y: 1 }, shape: 'Square' }]
};
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 300,
shape: { type: 'Text', content: 'textelement' } as TextModel,
style: { color: 'green', fontSize: 12, fontFamily: 'sans-serif' } as TextStyle,
ports: [{ id: 'port1', offset: { x: 0.5, y: 1 }, shape: 'Square' }]
};
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 500, offsetY: 300,
shape: { type: 'Text', content: 'textelement' } as TextModel,
style: { color: 'green', fontSize: 12, fontFamily: 'sans-serif' } as TextStyle,
ports: [{ id: 'port2', offset: { x: 0.5, y: 1 }, shape: 'Square' }]
};
let connector1: ConnectorModel = {
id: 'connector1', type: 'Orthogonal', sourceID: node.id,
targetID: node1.id
};
diagram = new Diagram({
width: 600, height: 500, nodes: [node, node1, node2], connectors: [connector1]
});
diagram.appendTo('#diagram8');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking connector source node change', (done: Function) => {
diagram.connectors[0].sourceID = diagram.nodes[2].id;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.sourceID == diagram.nodes[2].id).toBe(true);
done();
});
it('Checking connector target node change', (done: Function) => {
diagram.connectors[0].targetID = diagram.nodes[0].id;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.targetID == diagram.nodes[0].id).toBe(true);
done();
});
it('Checking connector source port change', (done: Function) => {
diagram.connectors[0].sourceID = diagram.nodes[2].id;
diagram.connectors[0].sourcePortID = (diagram.nodes[2] as NodeModel).ports[0].id;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.sourcePortID === (diagram.nodes[2] as NodeModel).ports[0].id).toBe(true);
done();
});
it('Checking connector target port change', (done: Function) => {
diagram.connectors[0].targetID = diagram.nodes[0].id;
diagram.connectors[0].targetPortID = (diagram.nodes[0] as NodeModel).ports[0].id;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(connector.targetPortID === (diagram.nodes[0] as NodeModel).ports[0].id).toBe(true);
done();
});
it('Change the node offset and connect the connector based on node', (done: Function) => {
diagram.nodes[1].offsetX = 600;
diagram.dataBind();
let connector: ConnectorModel = diagram.connectors[0];
expect(diagram.nodes[1].offsetX === 600).toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
describe('Connetor property change ', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'diagram8' });
document.body.appendChild(ele);
let nodes: NodeModel[] = [
{
id: 'node1', width: 100, height: 60, offsetX: 100, offsetY: 100,
ports: [{ id: 'port1', offset: { x: 0, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port2', offset: { x: 0.5, y: 0 }, visibility: PortVisibility.Visible },
{ id: 'port3', offset: { x: 1, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port4', offset: { x: 0.5, y: 1 }, visibility: PortVisibility.Visible },
]
},
{
id: 'node2', width: 100, offsetX: 300, offsetY: 100, ports: [{ id: 'port1', offset: { x: 0, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port2', offset: { x: 0.5, y: 0 }, visibility: PortVisibility.Visible },
{ id: 'port3', offset: { x: 1, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port4', offset: { x: 0.5, y: 1 }, visibility: PortVisibility.Visible },
]
},
{
id: 'node3', width: 100, offsetX: 500, offsetY: 250, ports: [{ id: 'port1', offset: { x: 0, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port2', offset: { x: 0.5, y: 0 }, visibility: PortVisibility.Visible },
{ id: 'port3', offset: { x: 1, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port4', offset: { x: 0.5, y: 1 }, visibility: PortVisibility.Visible },
]
},
{
id: 'node8', width: 100, offsetX: 700, offsetY: 300, ports: [{ id: 'port1', offset: { x: 0, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port2', offset: { x: 0.5, y: 0 }, visibility: PortVisibility.Visible },
{ id: 'port3', offset: { x: 1, y: 0.5 }, visibility: PortVisibility.Visible },
{ id: 'port4', offset: { x: 0.5, y: 1 }, visibility: PortVisibility.Visible },
]
}]
let connectors: ConnectorModel[] = [
{
id: 'Connector1',
sourceID: 'node2', type: 'Orthogonal',
targetID: 'node8', sourcePortID: 'port1', targetPortID: 'port1'
}
];
diagram = new Diagram({
width: 800, height: 400, nodes: nodes, connectors: connectors
});
diagram.appendTo('#diagram8');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking connector source node and target node id change and same port does not be changed', (done: Function) => {
console.log('Checking connector source node and target node id change and same port does not be changed');
diagram.connectors[0].sourceID = 'node3';
diagram.connectors[0].targetID = 'node1';
diagram.dataBind();
expect((diagram.connectors[0] as Connector).intermediatePoints[0].x ==450&&(diagram.connectors[0] as Connector).intermediatePoints[0].y ==250&&(diagram.connectors[0] as Connector).intermediatePoints[1].x ==30&&(diagram.connectors[0] as Connector).intermediatePoints[1].y ==250&&(diagram.connectors[0] as Connector).intermediatePoints[2].x ==30&&(diagram.connectors[0] as Connector).intermediatePoints[2].y ==100&&(diagram.connectors[0] as Connector).intermediatePoints[3].x ==50&&(diagram.connectors[0] as Connector).intermediatePoints[3].y ==100).toBe(true);
done();
});
});
}); | the_stack |
import {values} from 'lodash';
import configureMockStore from 'redux-mock-store';
import expect from 'expect';
import nock from 'nock';
import thunk from 'redux-thunk';
import {defaultActions, defaultHeaders} from '../../src';
import {createActions, getActionName} from '../../src/actions';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
// Configuration
const resourceName = 'user';
const host = 'http://localhost:3000';
const url = `${host}/users/:id`;
const checkActionMethodSignature = (getState, {actionId = ''} = {}) => {
expect(typeof getState).toBe('function');
expect(typeof actionId).toBe('string');
expect(typeof getState()).toBe('object');
};
describe('createActions', () => {
describe('when using a resource', () => {
it('should return an object with properly named keys', () => {
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const expectedKeys = [
'createUser',
'fetchUsers',
'getUser',
'updateUser',
'updateUsers',
'deleteUser',
'deleteUsers'
];
expect(Object.keys(actionFuncs)).toEqual(expectedKeys);
});
it('should return an object with properly typed values', () => {
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const expectedValuesFn = (action) => expect(typeof action).toBe('function');
values(actionFuncs).forEach(expectedValuesFn);
});
});
describe('when not using a resource', () => {
it('should return an object with properly named keys', () => {
const actionFuncs = createActions(defaultActions, {
url
});
const expectedKeys = ['create', 'fetch', 'get', 'update', 'updateMany', 'delete', 'deleteMany'];
expect(Object.keys(actionFuncs)).toEqual(expectedKeys);
});
it('should return an object with properly typed values', () => {
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const expectedValuesFn = (action) => expect(typeof action).toBe('function');
values(actionFuncs).forEach(expectedValuesFn);
});
});
});
describe('defaultActions', () => {
afterEach(() => {
nock.cleanAll();
});
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
describe('crudOperations', () => {
it('.create()', () => {
const actionId = 'create';
const action = getActionName(actionId, {
resourceName
});
const context = {
firstName: 'Olivier'
};
const body = {
ok: true
};
const code = 200;
nock(host).post('/users', context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.fetch()', () => {
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.get()', () => {
const actionId = 'get';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1
};
const body = {
id: 1,
firstName: 'Olivier'
};
const code = 200;
nock(host).get(`/users/${context.id}`).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.update()', () => {
const actionId = 'update';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const body = {
ok: true
};
const code = 200;
nock(host).patch(`/users/${context.id}`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.delete()', () => {
const actionId = 'delete';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1
};
const body = {
ok: true
};
const code = 200;
nock(host).delete(`/users/${context.id}`).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('exoticResponses', () => {
it('.fetch() with an exotic json Content-Type', () => {
const actionId = 'get';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1
};
const body = {
id: 1,
firstName: 'Olivier'
};
const code = 200;
nock(host).get(`/users/${context.id}`).reply(code, body, {
'Content-Type': 'application/problem+json; charset=utf-8'
});
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.fetch() with an empty body', () => {
const actionId = 'delete';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1
};
const code = 200;
nock(host).delete(`/users/${context.id}`).reply(code);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.fetch() with an non-json body', () => {
const actionId = 'delete';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1
};
const body = 'foobar';
const code = 200;
nock(host).delete(`/users/${context.id}`).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
res.receivedAt = null;
expect(res).toMatchSnapshot();
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('errorHandling', () => {
it('.fetch() with request errors', () => {
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
nock(host).get('/users').replyWithError('something awful happened');
const store = mockStore({
users: {}
});
return expect(store.dispatch(actionFuncs[action](context)))
.rejects.toBeDefined()
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.fetch() with JSON response errors', () => {
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = {
err: 'something awful happened'
};
const code = 400;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
let thrownErr;
return expect(
store.dispatch(actionFuncs[action](context)).catch((err) => {
thrownErr = err;
throw err;
})
)
.rejects.toBeDefined()
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(thrownErr.status).toEqual(code);
expect(actions).toMatchSnapshot();
});
});
it('.fetch() with HTML response errors', () => {
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = '<html><body><h1>something awful happened</h1></body></html>';
const code = 400;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
let thrownErr;
return expect(
store.dispatch(actionFuncs[action](context)).catch((err) => {
thrownErr = err;
throw err;
})
)
.rejects.toBeDefined()
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(thrownErr.status).toEqual(code);
expect(actions).toMatchSnapshot();
});
});
});
});
describe('custom actions', () => {
afterEach(() => {
nock.cleanAll();
});
const customActions = {
promote: {
method: 'POST',
url: `${url}/promote`
},
applications: {
name: 'fetchApplications',
gerundName: 'fetchingApplications',
method: 'GET',
isArray: true,
url: `${url}/applications`
},
merge: {
method: 'POST',
isArray: true
},
editFolder: {
method: 'PATCH',
url: `./folders/:folder`
}
};
const actionFuncs = createActions(customActions, {
resourceName,
url
});
it('.promote()', () => {
const actionId = 'promote';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const body = {
ok: true
};
const code = 200;
nock(host).post(`/users/${context.id}/promote`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('with a custom action name', () => {
const action = 'fetchApplications';
const context = {
id: 1
};
const body = [
{
id: 1,
name: 'Foo'
}
];
const code = 200;
nock(host).get(`/users/${context.id}/applications`).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('.merge()', () => {
const actionId = 'merge';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).post('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
expect(res.body).toEqual(actions[1].payload.body);
});
});
it('.editFolder()', () => {
const actionId = 'editFolder';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
folder: 2,
name: 'New Name'
};
const body = {
folder: 2,
name: 'New Name'
};
const code = 200;
nock(host).patch(`/users/${context.id}/folders/${context.folder}`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then((res) => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
expect(res.body).toEqual(actions[1].payload.body);
});
});
});
describe('custom pure actions', () => {
afterEach(() => {
nock.cleanAll();
});
const customActions = {
clear: {
isPure: true,
reduce: (state, _action) => ({
...state,
item: null
})
}
};
const actionFuncs = createActions(customActions, {
resourceName,
url
});
it('.clear()', () => {
const actionId = 'clear';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
expect(actions).toMatchSnapshot();
});
});
});
describe('other options', () => {
afterEach(() => {
nock.cleanAll();
});
describe('`alias` option', () => {
it('should support action override', () => {
const alias = 'grab';
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
alias
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
alias,
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`name` option', () => {
it('should support action override', () => {
const name = 'grabWorkers';
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
name
}
},
{
resourceName,
url
}
);
const action = name;
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
});
describe('fetch options', () => {
afterEach(() => {
nock.cleanAll();
});
describe('`transformResponse` option', () => {
it('should support action options', () => {
const transformResponse = (res) => ({
...res,
body: res.body.map((item) => ({
...item,
foo: 'bar'
}))
});
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
transformResponse
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`url` option', () => {
it('should support action override', () => {
const overridenUrl = `${host}/teams/:id`;
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
url: overridenUrl
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/teams').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support action override via function', () => {
const overridenUrl = (...args) => {
checkActionMethodSignature(...args);
return `${host}/teams/:id`;
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
url: overridenUrl
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/teams').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const overridenUrl = `${host}/teams/:id`;
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/teams').reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
url: overridenUrl
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support relative urls', () => {
const overridenUrl = './merge';
const actionFuncs = createActions(
{
...defaultActions,
update: {
...defaultActions.update,
url: overridenUrl
}
},
{
resourceName,
url
}
);
const actionId = 'update';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const body = {
ok: 1
};
const code = 200;
nock(host).patch(`/users/${context.id}/merge`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support relative urls for array methods', () => {
const overridenUrl = './aggregate';
const actionFuncs = createActions(
{
...defaultActions,
aggregate: {method: 'GET', gerundName: 'aggregating', url: overridenUrl, isArray: true}
},
{
resourceName,
url
}
);
const actionId = 'aggregate';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = {
ok: 1
};
const code = 200;
nock(host).get(`/users/aggregate`).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`method` option', () => {
it('should support action override', () => {
const method = 'PATCH';
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
method
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).patch('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support action override via function', () => {
const method = (...args) => {
checkActionMethodSignature(...args);
return 'PATCH';
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
method
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const type = '@@resource/USER/FETC';
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).patch('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const method = 'PATCH';
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).patch('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
method
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`query` option', () => {
it('should support action override', () => {
const query = {
foo: 'bar'
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
query
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users?foo=bar').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support action override via function', () => {
const query = (...args) => {
checkActionMethodSignature(...args);
return {
foo: 'bar'
};
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
query
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const type = '@@resource/USER/FETCH';
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
const options = {
isArray: true
};
nock(host).get('/users?foo=bar').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const query = {
foo: 'bar'
};
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users?foo=bar').reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
query
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support non-string query params', () => {
const query = {
select: ['firstName', 'lastName'],
populate: [
{
path: 'team',
model: 'Team',
select: ['id', 'name']
}
]
};
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host)
.get(
'/users?select=[%22firstName%22,%22lastName%22]&populate=[%7B%22path%22:%22team%22,%22model%22:%22Team%22,%22select%22:[%22id%22,%22name%22]%7D]'
)
.reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
query
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`params` option', () => {
it('should support context override', () => {
const params = {
id: 1
};
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'update';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {firstName: 'Olivia'};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).patch(`/users/${params.id}`).reply(code, body);
const store = mockStore({});
return store.dispatch(actionFuncs[action](context, {params})).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`headers` option', () => {
Object.assign(defaultHeaders, {
'X-Custom-Default-Header': 'foobar'
});
it('should support defaults override', () => {
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').matchHeader('X-Custom-Default-Header', 'foobar').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support action override', () => {
const headers = {
'X-Custom-Header': 'foobar'
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
headers
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').matchHeader('X-Custom-Header', 'foobar').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support action override via function', () => {
const headers = (...args) => {
checkActionMethodSignature(...args);
return {
'X-Custom-Header': 'foobar'
};
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
headers
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').matchHeader('X-Custom-Header', 'foobar').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const headers = {
'X-Custom-Header': 'foobar'
};
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').matchHeader('X-Custom-Header', 'foobar').reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
headers
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`credentials` option', () => {
it('should support action override', () => {
const credentials = 'include';
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
credentials
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host)
.get('/users')
// .matchHeader('Access-Control-Allow-Origin', '*')
// .matchHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support action override via function', () => {
const credentials = (...args) => {
checkActionMethodSignature(...args);
return 'include';
};
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
credentials
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host)
.get('/users')
// .matchHeader('Access-Control-Allow-Origin', '*')
// .matchHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const credentials = 'include';
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host)
.get('/users')
// .matchHeader('Access-Control-Allow-Origin', '*')
// .matchHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
credentials
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`signal` option', () => {
it('should support action override', () => {
const controller = new AbortController();
const {signal} = controller;
// const timeoutId = setTimeout(() => controller.abort(), 100);
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
signal
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').delayConnection(2000).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`body` option', () => {
it('should support context override', () => {
const contextBody = {
firstName: 'Olivier'
};
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'update';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1
};
const body = {
ok: true
};
const code = 200;
nock(host).patch(`/users/${context.id}`, contextBody).reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
body: contextBody
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
});
describe('reduce options', () => {
afterEach(() => {
nock.cleanAll();
});
describe('`isArray` option', () => {
it('should support action override', () => {
const isArray = true;
const actionFuncs = createActions(
{
...defaultActions,
create: {
...defaultActions.create,
isArray
}
},
{
resourceName,
url
}
);
const actionId = 'create';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {
firstName: 'Olivier'
};
const body = {
ok: 1
};
const code = 200;
nock(host).post('/users', context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const isArray = true;
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'update';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const body = {
ok: 1
};
const code = 200;
nock(host).patch(`/users/${context.id}`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
isArray
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`assignResponse` option', () => {
it('should support action override', () => {
const assignResponse = true;
const actionFuncs = createActions(
{
...defaultActions,
update: {
...defaultActions.update,
assignResponse
}
},
{
resourceName,
url
}
);
const actionId = 'update';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const body = {
ok: 1
};
const code = 200;
nock(host).patch(`/users/${context.id}`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const assignResponse = true;
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const actionId = 'update';
const action = getActionName(actionId, {
resourceName
});
const context = {
id: 1,
firstName: 'Olivier'
};
const body = {
ok: 1
};
const code = 200;
nock(host).patch(`/users/${context.id}`, context).reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
assignResponse
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
// it('.get()', () => {
// const actionId = 'get';
// const action = getActionName(actionId, {
// resourceName
// });
// const context = {
// id: 1
// };
// const body = {
// id: 1,
// firstName: 'Olivier'
// };
// const code = 200;
// nock(host).get(`/users/${context.id}`).reply(code, body);
// const store = mockStore({
// users: {}
// });
// return store.dispatch(actionFuncs[action](context)).then((res) => {
// res.receivedAt = null;
// expect(res).toMatchSnapshot();
// const actions = store.getActions();
// actions[1].payload.receivedAt = null;
// expect(actions).toMatchSnapshot();
// });
// });
describe('`mergeResponse` option', () => {
it('should support action override', () => {
const mergeResponse = true;
const actionId = 'get';
const action = getActionName(actionId, {
resourceName
});
const actionFuncs = createActions(
{
...defaultActions,
[actionId]: {
...defaultActions[actionId],
mergeResponse
}
},
{
resourceName,
url
}
);
const context = {id: 1};
const body = {
id: 1,
firstName: 'John'
};
const code = 200;
nock(host).get(`/users/${context.id}`).reply(code, body);
const store = mockStore();
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
it('should support context override', () => {
const mergeResponse = true;
const actionId = 'get';
const action = getActionName(actionId, {
resourceName
});
const actionFuncs = createActions(defaultActions, {
resourceName,
url
});
const context = {id: 1};
const body = {
id: 1,
firstName: 'John'
};
const code = 200;
nock(host).get(`/users/${context.id}`).reply(code, body);
const store = mockStore({
users: {}
});
return store
.dispatch(
actionFuncs[action](context, {
mergeResponse
})
)
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`invalidateState` option', () => {
it('should support action override', () => {
const invalidateState = true;
const actionFuncs = createActions(
{
...defaultActions,
fetch: {
...defaultActions.fetch,
invalidateState
}
},
{
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
const body = [
{
id: 1,
firstName: 'Olivier'
}
];
const code = 200;
nock(host).get('/users').reply(code, body);
const store = mockStore({
users: {}
});
return store.dispatch(actionFuncs[action](context)).then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
});
});
});
describe('`beforeError` hook', () => {
it('should support action override', () => {
const beforeError = jest.fn((error) => {
return error;
});
const actionFuncs = createActions(
{
...defaultActions
},
{
beforeError: [beforeError],
resourceName,
url
}
);
const actionId = 'fetch';
const action = getActionName(actionId, {
resourceName,
isArray: true
});
const context = {};
nock(host).get('/users').replyWithError('something awful happened');
const store = mockStore({
users: {}
});
return expect(store.dispatch(actionFuncs[action](context)))
.rejects.toBeDefined()
.then(() => {
const actions = store.getActions();
actions[1].payload.receivedAt = null;
expect(actions).toMatchSnapshot();
expect(beforeError.mock.calls.length).toBe(1);
});
});
});
}); | the_stack |
// WebRPC description and code-gen version
export const WebRPCVersion = 'v1'
// Schema version of your RIDL schema
export const WebRPCSchemaVersion = 'v0.4.0'
// Schema hash generated from your RIDL schema
export const WebRPCSchemaHash = 'fc9652e2bc0c3df8d1ce0b4a8e24ab8790e4dae2'
//
// Types
//
export enum ETHTxnStatus {
UNKNOWN = 'UNKNOWN',
DROPPED = 'DROPPED',
QUEUED = 'QUEUED',
SENT = 'SENT',
SUCCEEDED = 'SUCCEEDED',
PARTIALLY_FAILED = 'PARTIALLY_FAILED',
FAILED = 'FAILED'
}
export enum TransferType {
SEND = 'SEND',
RECEIVE = 'RECEIVE',
BRIDGE_DEPOSIT = 'BRIDGE_DEPOSIT',
BRIDGE_WITHDRAW = 'BRIDGE_WITHDRAW',
BURN = 'BURN',
UNKNOWN = 'UNKNOWN'
}
export enum FeeTokenType {
UNKNOWN = 'UNKNOWN',
ERC20_TOKEN = 'ERC20_TOKEN',
ERC1155_TOKEN = 'ERC1155_TOKEN'
}
export enum SortOrder {
DESC = 'DESC',
ASC = 'ASC'
}
export interface Version {
webrpcVersion: string
schemaVersion: string
schemaHash: string
appVersion: string
}
export interface RuntimeStatus {
healthOK: boolean
startTime: string
uptime: number
ver: string
branch: string
commitHash: string
senders: Array<SenderStatus>
checks: RuntimeChecks
}
export interface SenderStatus {
index: number
address: string
active: boolean
}
export interface RuntimeChecks {}
export interface SequenceContext {
factory: string
mainModule: string
mainModuleUpgradable: string
guestModule: string
utils: string
}
export interface WalletConfig {
address: string
signers: Array<WalletSigner>
threshold: number
chainId?: number
}
export interface WalletSigner {
address: string
weight: number
}
export interface MetaTxn {
walletAddress: string
contract: string
input: string
}
export interface MetaTxnLog {
id: number
txnHash: string
txnNonce: string
metaTxnID?: string
txnStatus: ETHTxnStatus
txnRevertReason: string
target: string
input: string
txnArgs: { [key: string]: any }
txnReceipt?: { [key: string]: any }
walletAddress: string
metaTxnNonce: string
gasLimit: number
gasPrice: string
gasUsed: number
updatedAt: string
createdAt: string
}
export interface MetaTxnEntry {
id: number
metaTxnID: string
txnStatus: ETHTxnStatus
txnRevertReason: string
index: number
logs?: Array<any>
updatedAt: string
createdAt: string
}
export interface MetaTxnReceipt {
id: string
status: string
revertReason?: string
index: number
logs: Array<MetaTxnReceiptLog>
receipts: Array<MetaTxnReceipt>
txnReceipt: string
}
export interface MetaTxnReceiptLog {
address: string
topics: Array<string>
data: string
}
export interface Transaction {
txnHash?: string
blockNumber: number
chainId: number
metaTxnID?: string
transfers?: Array<TxnLogTransfer>
users?: { [key: string]: TxnLogUser }
timestamp: string
}
export interface TxnLogUser {
username: string
}
export interface TxnLogTransfer {
transferType: TransferType
contractAddress: string
from: string
to: string
ids: Array<string>
amounts: Array<string>
}
export interface SentTransactionsFilter {
pending?: boolean
failed?: boolean
}
export interface FeeOption {
token: FeeToken
to: string
value: string
gasLimit: number
}
export interface FeeToken {
chainId: number
name: string
symbol: string
type: FeeTokenType
decimals?: number
logoURL: string
contractAddress?: string
originAddress?: string
tokenID?: string
}
export interface Page {
pageSize?: number
page?: number
totalRecords?: number
column?: string
before?: any
after?: any
sort?: Array<SortBy>
}
export interface SortBy {
column: string
order: SortOrder
}
export interface Relayer {
ping(headers?: object): Promise<PingReturn>
version(headers?: object): Promise<VersionReturn>
runtimeStatus(headers?: object): Promise<RuntimeStatusReturn>
getSequenceContext(headers?: object): Promise<GetSequenceContextReturn>
getChainID(headers?: object): Promise<GetChainIDReturn>
sendMetaTxn(args: SendMetaTxnArgs, headers?: object): Promise<SendMetaTxnReturn>
getMetaTxnNonce(args: GetMetaTxnNonceArgs, headers?: object): Promise<GetMetaTxnNonceReturn>
getMetaTxnReceipt(args: GetMetaTxnReceiptArgs, headers?: object): Promise<GetMetaTxnReceiptReturn>
updateMetaTxnGasLimits(args: UpdateMetaTxnGasLimitsArgs, headers?: object): Promise<UpdateMetaTxnGasLimitsReturn>
feeTokens(headers?: object): Promise<FeeTokensReturn>
getMetaTxnNetworkFeeOptions(args: GetMetaTxnNetworkFeeOptionsArgs, headers?: object): Promise<GetMetaTxnNetworkFeeOptionsReturn>
sentTransactions(args: SentTransactionsArgs, headers?: object): Promise<SentTransactionsReturn>
pendingTransactions(args: PendingTransactionsArgs, headers?: object): Promise<PendingTransactionsReturn>
}
export interface PingArgs {}
export interface PingReturn {
status: boolean
}
export interface VersionArgs {}
export interface VersionReturn {
version: Version
}
export interface RuntimeStatusArgs {}
export interface RuntimeStatusReturn {
status: RuntimeStatus
}
export interface GetSequenceContextArgs {}
export interface GetSequenceContextReturn {
data: SequenceContext
}
export interface GetChainIDArgs {}
export interface GetChainIDReturn {
chainID: number
}
export interface SendMetaTxnArgs {
call: MetaTxn
}
export interface SendMetaTxnReturn {
status: boolean
txnHash: string
}
export interface GetMetaTxnNonceArgs {
walletContractAddress: string
space?: string
}
export interface GetMetaTxnNonceReturn {
nonce: string
}
export interface GetMetaTxnReceiptArgs {
metaTxID: string
}
export interface GetMetaTxnReceiptReturn {
receipt: MetaTxnReceipt
}
export interface UpdateMetaTxnGasLimitsArgs {
walletAddress: string
walletConfig: WalletConfig
payload: string
}
export interface UpdateMetaTxnGasLimitsReturn {
payload: string
}
export interface FeeTokensArgs {}
export interface FeeTokensReturn {
isFeeRequired: boolean
tokens: Array<FeeToken>
}
export interface GetMetaTxnNetworkFeeOptionsArgs {
walletConfig: WalletConfig
payload: string
}
export interface GetMetaTxnNetworkFeeOptionsReturn {
options: Array<FeeOption>
}
export interface SentTransactionsArgs {
filter?: SentTransactionsFilter
page?: Page
}
export interface SentTransactionsReturn {
page: Page
transactions: Array<Transaction>
}
export interface PendingTransactionsArgs {
page?: Page
}
export interface PendingTransactionsReturn {
page: Page
transactions: Array<Transaction>
}
//
// Client
//
export class Relayer implements Relayer {
protected hostname: string
protected fetch: Fetch
protected path = '/rpc/Relayer/'
constructor(hostname: string, fetch: Fetch) {
this.hostname = hostname
this.fetch = fetch
}
private url(name: string): string {
return this.hostname + this.path + name
}
ping = (headers?: object): Promise<PingReturn> => {
return this.fetch(this.url('Ping'), createHTTPRequest({}, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
status: <boolean>_data.status
}
})
})
}
version = (headers?: object): Promise<VersionReturn> => {
return this.fetch(this.url('Version'), createHTTPRequest({}, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
version: <Version>_data.version
}
})
})
}
runtimeStatus = (headers?: object): Promise<RuntimeStatusReturn> => {
return this.fetch(this.url('RuntimeStatus'), createHTTPRequest({}, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
status: <RuntimeStatus>_data.status
}
})
})
}
getSequenceContext = (headers?: object): Promise<GetSequenceContextReturn> => {
return this.fetch(this.url('GetSequenceContext'), createHTTPRequest({}, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
data: <SequenceContext>_data.data
}
})
})
}
getChainID = (headers?: object): Promise<GetChainIDReturn> => {
return this.fetch(this.url('GetChainID'), createHTTPRequest({}, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
chainID: <number>_data.chainID
}
})
})
}
sendMetaTxn = (args: SendMetaTxnArgs, headers?: object): Promise<SendMetaTxnReturn> => {
return this.fetch(this.url('SendMetaTxn'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
status: <boolean>_data.status,
txnHash: <string>_data.txnHash
}
})
})
}
getMetaTxnNonce = (args: GetMetaTxnNonceArgs, headers?: object): Promise<GetMetaTxnNonceReturn> => {
return this.fetch(this.url('GetMetaTxnNonce'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
nonce: <string>_data.nonce
}
})
})
}
getMetaTxnReceipt = (args: GetMetaTxnReceiptArgs, headers?: object): Promise<GetMetaTxnReceiptReturn> => {
return this.fetch(this.url('GetMetaTxnReceipt'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
receipt: <MetaTxnReceipt>_data.receipt
}
})
})
}
updateMetaTxnGasLimits = (args: UpdateMetaTxnGasLimitsArgs, headers?: object): Promise<UpdateMetaTxnGasLimitsReturn> => {
return this.fetch(this.url('UpdateMetaTxnGasLimits'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
payload: <string>_data.payload
}
})
})
}
feeTokens = (headers?: object): Promise<FeeTokensReturn> => {
return this.fetch(this.url('FeeTokens'), createHTTPRequest({}, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
isFeeRequired: <boolean>_data.isFeeRequired,
tokens: <Array<FeeToken>>_data.tokens
}
})
})
}
getMetaTxnNetworkFeeOptions = (
args: GetMetaTxnNetworkFeeOptionsArgs,
headers?: object
): Promise<GetMetaTxnNetworkFeeOptionsReturn> => {
return this.fetch(this.url('GetMetaTxnNetworkFeeOptions'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
options: <Array<FeeOption>>_data.options
}
})
})
}
sentTransactions = (args: SentTransactionsArgs, headers?: object): Promise<SentTransactionsReturn> => {
return this.fetch(this.url('SentTransactions'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
page: <Page>_data.page,
transactions: <Array<Transaction>>_data.transactions
}
})
})
}
pendingTransactions = (args: PendingTransactionsArgs, headers?: object): Promise<PendingTransactionsReturn> => {
return this.fetch(this.url('PendingTransactions'), createHTTPRequest(args, headers)).then(res => {
return buildResponse(res).then(_data => {
return {
page: <Page>_data.page,
transactions: <Array<Transaction>>_data.transactions
}
})
})
}
}
export interface WebRPCError extends Error {
code: string
msg: string
status: number
}
const createHTTPRequest = (body: object = {}, headers: object = {}): object => {
return {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify(body || {})
}
}
const buildResponse = (res: Response): Promise<any> => {
return res.text().then(text => {
let data
try {
data = JSON.parse(text)
} catch (err) {
throw { code: 'unknown', msg: `expecting JSON, got: ${text}`, status: res.status } as WebRPCError
}
if (!res.ok) {
throw data // webrpc error response
}
return data
})
}
export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response> | the_stack |
import { Cache } from "@siteimprove/alfa-cache";
import { Device } from "@siteimprove/alfa-device";
import { Graph } from "@siteimprove/alfa-graph";
import { Serializable } from "@siteimprove/alfa-json";
import { Lazy } from "@siteimprove/alfa-lazy";
import { Map } from "@siteimprove/alfa-map";
import { None, Option } from "@siteimprove/alfa-option";
import { Predicate } from "@siteimprove/alfa-predicate";
import { Refinement } from "@siteimprove/alfa-refinement";
import { Sequence } from "@siteimprove/alfa-sequence";
import { Set } from "@siteimprove/alfa-set";
import { Style } from "@siteimprove/alfa-style";
import * as dom from "@siteimprove/alfa-dom";
import * as json from "@siteimprove/alfa-json";
import { Attribute } from "./attribute";
import { Name } from "./name";
import { Role } from "./role";
import { Feature } from "./feature";
import { Container, Element, Inert, Text } from ".";
import * as predicate from "./node/predicate";
const { equals } = Predicate;
/**
* {@link https://w3c.github.io/aria/#accessibility_tree}
*
* @public
*/
export abstract class Node implements Serializable<Node.JSON> {
protected readonly _node: dom.Node;
protected readonly _children: Array<Node>;
protected _parent: Option<Node> = None;
/**
* Whether or not the node is frozen.
*
* @remarks
* As nodes are initialized without a parent and possibly attached to a parent
* after construction, this makes hierarchies of nodes mutable. That is, a
* node without a parent node may be assigned one by being passed as a child
* to a parent node. When this happens, a node becomes frozen. Nodes can also
* become frozen before being assigned a parent by using the `Node#freeze()`
* method.
*/
protected _frozen: boolean = false;
protected constructor(owner: dom.Node, children: Array<Node>) {
this._node = owner;
this._children = children
.map((child) => (child._frozen ? child.clone() : child))
.filter((child) => child._attachParent(this));
}
public get node(): dom.Node {
return this._node;
}
public get name(): Option<Name> {
return None;
}
public get role(): Option<Role> {
return None;
}
public get frozen(): boolean {
return this._frozen;
}
/**
* Freeze the node. This prevents further expansion of the node hierarchy,
* meaning that the node can no longer be passed as a child to a parent node.
*/
public freeze(): this {
this._frozen = true;
return this;
}
public attribute<N extends Attribute.Name>(
refinement: Refinement<Attribute, Attribute<N>>
): Option<Attribute<N>>;
public attribute(predicate: Predicate<Attribute>): Option<Attribute>;
public attribute<N extends Attribute.Name>(name: N): Option<Attribute<N>>;
public attribute(
predicate: Attribute.Name | Predicate<Attribute>
): Option<Attribute> {
return None;
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-parent}
*/
public parent(options: Node.Traversal = {}): Option<Node> {
const parent = this._parent;
if (options.ignored === true) {
return parent;
}
return parent.flatMap((parent) =>
parent.isIgnored() ? parent.parent(options) : Option.of(parent)
);
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-root}
*/
public root(options: Node.Traversal = {}): Node {
for (const parent of this.parent(options)) {
return parent.root(options);
}
return this;
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-child}
*/
public children(options: Node.Traversal = {}): Sequence<Node> {
const children = Sequence.from(this._children);
if (options.ignored === true) {
return children;
}
return children.flatMap((child) =>
child.isIgnored() ? child.children(options) : Sequence.of(child)
);
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-descendant}
*/
public descendants(options: Node.Traversal = {}): Sequence<Node> {
return this.children(options).flatMap((child) =>
Sequence.of(
child,
Lazy.of(() => child.descendants(options))
)
);
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant}
*/
public inclusiveDescendants(options: Node.Traversal = {}): Sequence<Node> {
return Sequence.of(
this,
Lazy.of(() => this.descendants(options))
);
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-ancestor}
*/
public ancestors(options: Node.Traversal = {}): Sequence<Node> {
return this.parent(options)
.map((parent) =>
Sequence.of(
parent,
Lazy.of(() => parent.ancestors(options))
)
)
.getOrElse(() => Sequence.empty());
}
/**
* {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor}
*/
public inclusiveAncestors(options: Node.Traversal = {}): Sequence<Node> {
return Sequence.of(
this,
Lazy.of(() => this.ancestors(options))
);
}
public abstract clone(parent?: Option<Node>): Node;
public abstract isIgnored(): boolean;
public abstract toJSON(): Node.JSON;
/**
* @internal
*/
public _attachParent(parent: Node): boolean {
if (this._frozen || this._parent.isSome()) {
return false;
}
this._parent = Option.of(parent);
this._frozen = true;
return true;
}
}
/**
* @public
*/
export namespace Node {
export interface JSON {
[key: string]: json.JSON;
type: string;
node: string;
children: Array<JSON>;
}
export interface Traversal {
/**
* When `true`, traverse both exposed and ignored nodes.
*/
readonly ignored?: boolean;
}
const cache = Cache.empty<Device, Cache<dom.Node, Node>>();
export function from(node: dom.Node, device: Device): Node {
const _cache = cache.get(device, Cache.empty);
// If the cache already holds an entry for the specified node, then the tree
// that the node participates in has already been built.
if (_cache.has(node)) {
return _cache.get(node).get();
}
const root = node.root({ flattened: true });
// If the cache already holds an entry for the root of the specified node,
// then the tree that the node participates in has already been built, but
// the node itself is not included within the resulting accessibility tree.
if (_cache.has(root)) {
return _cache.get(node, () => Inert.of(node));
}
// Before we start constructing the accessibility tree, we need to resolve
// explicit ownership of elements as specified by the `aria-owns` attribute.
// https://w3c.github.io/aria/#aria-owns
// Find all elements in the tree. As explicit ownership is specified via ID
// references, it cannot cross shadow or document boundaries.
const elements = root.inclusiveDescendants().filter(dom.Element.isElement);
// Build a map from ID -> element to allow fast resolution of ID references.
// The collected references are added to the map in reverse order to ensure
// that the first occurrence of a given ID is what ends up in the map in
// event of duplicates.
const ids = Map.from(
elements
.collect((element) => element.id.map((id) => [id, element] as const))
.reverse()
);
// Do a first pass over `aria-owns` attributes and collect the referenced
// elements.
const references = elements.collect((element) =>
element.attribute("aria-owns").map(
(attribute) =>
[
element,
attribute
.tokens()
.collect((id) => ids.get(id))
// Reject references from the element to itself or its ancestors
// as these would cause cyclic references.
.reject(
(reference) =>
element === reference ||
element.ancestors().includes(reference)
),
] as const
)
);
// Refine the collected `aria-owns` references, constructing a set of
// claimed elements and resolving conflicting claims as needed.
const [claimed, owned] = references.reduce(
([claimed, owned, graph], [element, references]) => {
// Reject all element references that have either already been claimed
// or would introduce a cyclic reference. While authors are not allowed
// to specify a given ID in more than one `aria-owns` attribute, it will
// inevitably happen that multiple `aria-owns` attributes reference the
// same ID. We deal with this on a first come, first serve basis and
// deny anything but the first claim to a given ID.
references = references.reject(
(reference) =>
claimed.has(reference) || graph.hasPath(reference, element)
);
// If there are no references left, this element has no explicit
// ownership.
if (references.isEmpty()) {
return [claimed, owned, graph];
}
// Claim the remaining references.
claimed = references.reduce(
(claimed, reference) => claimed.add(reference),
claimed
);
// Connect the element to each of its references to track cycles.
graph = references.reduce(
(graph, reference) => graph.connect(element, reference),
graph
);
return [claimed, owned.set(element, references), graph];
},
[
Set.empty<dom.Element>(),
Map.empty<dom.Element, Sequence<dom.Element>>(),
Graph.empty<dom.Element>(),
]
);
fromNode(root, device, claimed, owned, State.empty());
return _cache.get(node, () =>
// If the cache still doesn't hold an entry for the specified node, then
// the node doesn't even participate in the tree. Store it as an inert
// node.
Inert.of(node)
);
}
class State {
private static _empty = new State(false, true);
public static empty(): State {
return this._empty;
}
private readonly _isPresentational: boolean;
private readonly _isVisible: boolean;
private constructor(isPresentational: boolean, isVisible: boolean) {
this._isPresentational = isPresentational;
this._isVisible = isVisible;
}
public get isPresentational(): boolean {
return this._isPresentational;
}
public get isVisible(): boolean {
return this._isVisible;
}
public presentational(isPresentational: boolean): State {
if (this._isPresentational === isPresentational) {
return this;
}
return new State(isPresentational, this._isVisible);
}
public visible(isVisible: boolean): State {
if (this._isVisible === isVisible) {
return this;
}
return new State(this._isPresentational, isVisible);
}
}
function fromNode(
node: dom.Node,
device: Device,
claimed: Set<dom.Node>,
owned: Map<dom.Element, Sequence<dom.Node>>,
state: State
): Node {
return cache.get(device, Cache.empty).get(node, () => {
if (dom.Element.isElement(node)) {
// Elements that are explicitly excluded from the accessibility tree
// by means of `aria-hidden=true` are never exposed in the
// accessibility tree, nor are their descendants.
//
// This behaviour is unfortunately not consistent across browsers,
// which we may or may not want to deal with. For now, we pretend that
// all browsers act consistently.
//
// https://github.com/Siteimprove/alfa/issues/184#issuecomment-593878009
if (
node
.attribute("aria-hidden")
.some((attribute) =>
attribute.enumerate("true", "false").some(equals("true"))
)
) {
return Inert.of(node);
}
const style = Style.from(node, device);
// Elements that are not rendered at all by means of `display: none`
// are never exposed in the accessibility tree, nor are their
// descendants.
//
// As we're building the accessibility tree top-down, we only need to
// check the element itself for `display: none` and can safely
// disregard its ancestors as they will already have been checked.
if (
style
.computed("display")
.some(({ values: [outside] }) => outside.value === "none")
) {
return Inert.of(node);
}
let children: (state: State) => Iterable<Node>;
// Children of <iframe> elements act as fallback content in legacy user
// agents and should therefore never be included in the accessibility
// tree.
if (node.name === "iframe") {
children = () => [];
}
// Otherwise, recursively build accessible nodes for the children of the
// element.
else {
// Get the children explicitly owned by the element. Children can be
// explicitly owned using the `aria-owns` attribute.
const explicit = owned
.get(node)
.getOrElse(() => Sequence.empty<dom.Node>());
// Get the children implicitly owned by the element. These are the
// children in the flat tree that are neither claimed already nor
// explicitly owned by the element.
const implicit = node
.children({
flattened: true,
})
.reject((child) => claimed.has(child) || explicit.includes(child));
// The children implicitly owned by the element come first, then the
// children explicitly owned by the element.
children = (state) =>
implicit
.concat(explicit)
.map((child) => fromNode(child, device, claimed, owned, state));
}
// Elements that are not visible by means of `visibility: hidden` or
// `visibility: collapse`, are exposed in the accessibility tree as
// containers as they may contain visible descendants.
if (style.computed("visibility").value.value !== "visible") {
return Container.of(node, children(state.visible(false)));
}
state = state.visible(true);
const role = Role.fromExplicit(node).orElse(() =>
// If the element has no explicit role and instead inherits a
// presentational role then use that, otherwise fall back to the
// implicit role.
state.isPresentational
? Option.of(Role.of("presentation"))
: Role.fromImplicit(node)
);
if (role.some((role) => role.isPresentational())) {
return Container.of(
node,
children(
state.presentational(
// If the implicit role of the presentational element has
// required children then any owned children must also be
// presentational.
Role.fromImplicit(node).some((role) =>
role.hasRequiredChildren()
)
)
)
);
}
let attributes = Map.empty<Attribute.Name, Attribute>();
// First pass: Look up implicit attributes on the role.
if (role.isSome()) {
for (const attribute of role.get().attributes) {
for (const value of role.get().implicitAttributeValue(attribute)) {
attributes = attributes.set(
attribute,
Attribute.of(attribute, value)
);
}
}
}
// Second pass: Look up implicit attributes on the feature mapping.
for (const namespace of node.namespace) {
for (const feature of Feature.from(namespace, node.name)) {
for (const attribute of feature.attributes(node)) {
attributes = attributes.set(attribute.name, attribute);
}
}
}
// Third pass: Look up explicit `aria-*` attributes and set the ones
// that are either global or supported by the role.
for (const { name, value } of node.attributes) {
if (Attribute.isName(name)) {
const attribute = Attribute.of(name, value);
if (
attribute.isGlobal() ||
role.some((role) => role.isAttributeSupported(attribute.name))
) {
attributes = attributes.set(name, attribute);
}
}
}
// If the element has neither attributes, a role, nor a tabindex, it is
// not itself interesting for accessibility purposes. It is therefore
// exposed as a container.
if (attributes.isEmpty() && role.isNone() && node.tabIndex().isNone()) {
return Container.of(node, children(state));
}
// If the element has a role that designates its children as
// presentational then set the state as presentational.
if (role.some((role) => role.hasPresentationalChildren())) {
state = state.presentational(true);
}
return Element.of(
node,
role,
Name.from(node, device),
attributes.values(),
children(state)
);
}
if (dom.Text.isText(node)) {
// As elements with `visibility: hidden` are exposed as containers for
// other elements that _might_ be visible, we need to check the
// visibility of the parent element before deciding to expose the text
// node. If the parent element isn't visible, the text node instead
// becomes inert.
if (!state.isVisible) {
return Inert.of(node);
}
return Text.of(node, Name.from(node, device));
}
return Container.of(
node,
node
.children({
flattened: true,
})
.reject((child) => claimed.has(child))
.map((child) => fromNode(child, device, claimed, owned, state))
);
});
}
export const { hasName, hasRole } = predicate;
} | the_stack |
import { Options } from 'k6/options'
type ExecutorName =
| 'shared-iterations'
| 'per-vu-iterations'
| 'constant-vus'
| 'ramping-vus'
| 'constant-arrival-rate'
| 'ramping-arrival-rate'
| 'externally-controlled'
/**
* @example
* export let options = {
* scenarios: {
* my_cool_scenario: { // arbitrary and unique scenario name, will appear in the result summary tags, etc.
* executor: 'shared-iterations', // name of the executor to use
* // common scenario configuration
* startTime: '10s',
* gracefulStop: '5s',
* env: { EXAMPLEVAR: 'testing' },
* tags: { example_tag: 'testing' },
* // executor-specific configuration
* vus: 10,
* iterations: 200,
* maxDuration: '10s',
* },
* another_scenario: { ... }
* }
* }
*/
export interface K6ScenarioBase {
/**
* Unique executor name. See the list of possible values below
**/
executor: ExecutorName
/**
* Time offset since the start of the test, at which point this scenario should begin execution.
* @default "0s"
**/
startTime?: string
/**
* Time to wait for iterations to finish executing before stopping them forcefully. See the gracefulStop section.
* @default "30s"
*/
gracefulStop?: string
/**
* Name of exported JS function to execute.
* @default "default"
*/
exec?: string
/**
* Environment variables specific to this scenario.
* @default {}
*/
env?: Record<string, any>
/**
* Tags specific to this scenario.
* @default {}
*/
tags?: Record<string, string>
}
/**
* A fixed number of iterations are "shared" between a number of VUs, and the test ends once all iterations are executed.
* This executor is equivalent to the global vus and iterations options.
*
* Note that iterations aren't fairly distributed with this executor, and a VU that executes faster will complete more iterations than others.
*
* When to use:
* This executor is suitable when you want a specific amount of VUs to complete a fixed number of total iterations, and the amount of iterations per VU is not important.
*
* @example
*
* // Execute 200 total iterations shared by 10 VUs with a maximum duration of 10 seconds:
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* contacts: {
* executor: 'shared-iterations',
* vus: 10,
* iterations: 200,
* maxDuration: '10s',
* }
* }
* };
*/
export interface SharedIterationsExector extends K6ScenarioBase {
executor: 'shared-iterations'
/**
* Number of VUs to run concurrently.
* @default 1
*/
vus?: number
/**
* Total number of script iterations to execute across all VUs.
* @default 1
*/
iterations?: number
/**
* Maximum scenario duration before it's forcibly stopped (excluding gracefulStop).
* @default "10m"
*/
maxDuration?: string
}
/**
* Each VU executes an exact number of iterations. The total number of completed iterations will be vus * iterations.
*
* When to use:
* Use this executor if you need a specific amount of VUs to complete the same amount of iterations.
* This can be useful when you have fixed sets of test data that you want to partition between VUs.
*
* @example
*
* // Execute 20 iterations by 10 VUs each, for a total of 200 iterations, with a maximum duration of 1 hour and 30 minutes:
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* contacts: {
* executor: 'per-vu-iterations',
* vus: 10,
* iterations: 20,
* maxDuration: '1h30m',
* }
* }
* };
*/
export interface PerVUIterationsExecutor extends K6ScenarioBase {
executor: 'per-vu-iterations'
/**
* Number of VUs to run concurrently.
* @default 1
*/
vus?: number
/**
* Total number of script iterations to execute across all VUs.
* @default 1
*/
iterations?: number
/**
* Maximum scenario duration before it's forcibly stopped (excluding gracefulStop).
* @default "10m"
*/
maxDuration?: string
}
/**
* A fixed number of VUs execute as many iterations as possible for a specified amount of time. This executor is equivalent to the global vus and duration options.
*
* When to use:
* Use this executor if you need a specific amount of VUs to run for a certain amount of time.
*
* @example
*
* // Run a constant 10 VUs for 45 minutes:
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* my_awesome_api_test: {
* executor: 'constant-vus',
* vus: 10,
* duration: '45m',
* }
* }
* };
*/
export interface ConstantVUExecutor extends K6ScenarioBase {
executor: 'constant-vus'
/**
* Number of VUs to run concurrently.
* @default 1
*/
vus?: number
/**
* Total scenario duration (excluding gracefulStop).
*/
duration: string
}
/**
* A variable number of VUs execute as many iterations as possible for a specified amount of time. This executor is equivalent to the global stages option.
*
* When to use:
* This executor is a good fit if you need VUs to ramp up or down during specific periods of time.
*
* @example
*
* // Run a two-stage test, ramping up from 0 to 100 VUs for 5 seconds, and down to 0 VUs for 5 seconds:
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* contacts: {
* executor: 'ramping-vus',
* startVUs: 0,
* stages: [
* { duration: '5s', target: 100 },
* { duration: '5s', target: 0 },
* ],
* gracefulRampDown: '0s',
* }
* }
* };
*/
export interface RampingVUExecutor extends K6ScenarioBase {
executor: 'ramping-vus'
/**
* Number of VUs to run at test start.
* @default 1
*/
startVUs?: number
/**
* Array of objects that specify the target number of VUs to ramp up or down to.
* @default []
*/
stages?: Array<{ duration: string; target: number }>
/**
* Time to wait for iterations to finish before starting new VUs.
* @default '30s'
*/
gracefulRampDown?: string
}
/**
* A fixed number of iterations are executed in a specified period of time. Since iteration execution time can vary because of test logic or the system-under-test responding more slowly
* this executor will try to compensate by running a variable number of VUs—including potentially initializing more in the middle of the test—in order to meet the configured iteration rate.
*
* This approach is useful for a more accurate representation of RPS, for example.
*
* When to use:
* When you want to maintain a constant number of requests without being affected by the performance of the system under test.
*
* @example
*
* // Execute a constant 200 RPS for 1 minute, allowing k6 to dynamically schedule up to 100 VUs:
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* contacts: {
* executor: 'constant-arrival-rate',
* rate: 200, // 200 RPS, since timeUnit is the default 1s
* duration: '1m',
* preAllocatedVUs: 50,
* maxVUs: 100,
* }
* }
* };
*/
export interface ConstantArrivalRateExecutor extends K6ScenarioBase {
executor: 'constant-arrival-rate'
/**
* Number of iterations to execute each timeUnit period.
*/
rate: number
/**
* Period of time to apply the rate value.
* @default '1s'
*/
timeUnit?: string
/**
* Total scenario duration (excluding gracefulStop).
*/
duration: string
/**
* Number of VUs to pre-allocate before test start in order to preserve runtime resources.
*/
preAllocatedVUs: number
/**
* Maximum number of VUs to allow during the test run.
*/
maxVUs?: number
}
/**
* A variable number of iterations are executed in a specified period of time.
* This is similar to the ramping VUs executor, but for iterations instead, and k6 will attempt to dynamically change the number of VUs to achieve the configured iteration rate.
*
* When to use:
* If you need your tests to not be affected by the system-under-test's performance, and would like to ramp the number of iterations up or down during specific periods of time.
*
* @example
*
* // Execute a variable RPS test, starting at 50, ramping up to 200 and then back to 0, over a 1 minute period:
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* contacts: {
* executor: 'ramping-arrival-rate',
* startRate: 50,
* timeUnit: '1s',
* preAllocatedVUs: 50,
* maxVUs: 100,
* stages: [
* { target: 200, duration: '30s' },
* { target: 0, duration: '30s' },
* ],
* }
* }
* };
*/
export interface RampingArrivalRateExecutor extends K6ScenarioBase {
executor: 'ramping-arrival-rate'
/**
* Number of iterations to execute each timeUnit period at test start.
* @default 0
*/
startRate?: number
/**
* Period of time to apply the startRate the stages target value.
* @default '1s'
*/
timeUnit?: string
/**
* Array of objects that specify the target number of iterations to ramp up or down to.
* @default []
*/
stages: Array<{ duration: string; target: number }>
/**
* Number of VUs to pre-allocate before test start in order to preserve runtime resources.
*/
preAllocatedVUs: number
/**
* Maximum number of VUs to allow during the test run.
*/
maxVUs?: number
}
/**
* Control and scale execution at runtime via k6's REST API or the CLI.
* Previously, the pause, resume, and scale CLI commands were used to globally control k6 execution.
* This executor does the same job by providing a better API that can be used to control k6 execution at runtime.
*
* Note that, passing arguments to the scale CLI command for changing the amount of active or maximum VUs will only affect the externally controlled executor.
*
* When to use:
* If you want to control the number of VUs while the test is running.
*
* Important: this is the only executor that is not supported in k6 cloud, it can only be used locally with k6 run.
*
* @example
*
* export let options = {
* discardResponseBodies: true,
* scenarios: {
* contacts: {
* executor: 'externally-controlled',
* vus: 0,
* maxVUs: 50,
* duration: '10m',
* }
* }
* };
*/
export interface ExternallyControlledExecutor extends K6ScenarioBase {
executor: 'externally-controlled'
/**
* Number of VUs to run concurrently.
*/
vus: number
/**
* Maximum number of VUs to allow during the test run.
*/
maxVUs?: number
/**
* Total test duration
*/
duration: string
}
type K6Scenario =
| SharedIterationsExector
| PerVUIterationsExecutor
| ConstantVUExecutor
| RampingVUExecutor
| ConstantArrivalRateExecutor
| RampingArrivalRateExecutor
| ExternallyControlledExecutor
export interface K6Options extends Options {
scenarios: Record<string, K6Scenario>
}
/**
* =========================
* METRICS (STDOUT JSON)
* =========================
*/
export interface K6AbstractMetric {
type: 'Metric' | 'Point'
metric: Metric
data: object
}
export interface K6Metric extends K6AbstractMetric {
type: 'Metric'
data: K6MetricData
}
export interface K6MetricData {
name?: Metric
type?: DataType
contains?: Contains
tainted?: any
thresholds?: any[]
submetrics?: any
sub?: Sub
}
export interface K6Point extends K6AbstractMetric {
type: 'Point'
data: K6PointData
}
export interface K6PointData {
time?: Date
value?: number
tags?: Tags
}
export enum Contains {
Data = 'data',
Default = 'default',
Time = 'time',
}
export enum Metric {
Checks = 'checks',
DataReceived = 'data_received',
DataSent = 'data_sent',
HTTPReqBlocked = 'http_req_blocked',
HTTPReqConnecting = 'http_req_connecting',
HTTPReqDuration = 'http_req_duration',
HTTPReqReceiving = 'http_req_receiving',
HTTPReqSending = 'http_req_sending',
HTTPReqTLSHandshaking = 'http_req_tls_handshaking',
HTTPReqWaiting = 'http_req_waiting',
HTTPReqs = 'http_reqs',
IterationDuration = 'iteration_duration',
Iterations = 'iterations',
}
export interface Sub {
name: string
parent: string
suffix: string
tags: any[]
}
export interface Tags {
group: string
method?: Method
name?: string
proto?: string
scenario: string
status?: string
url?: string
check?: string
}
export enum Method {
Get = 'GET',
Post = 'POST',
Put = 'PUT',
Patch = 'PATCH',
Delete = 'DELETE',
}
export enum DataType {
Counter = 'counter',
Rate = 'rate',
Trend = 'trend',
Gauge = 'gauge',
}
/**
* =========================
* SUMMARY EXPORT JSON
* =========================
*/
export interface K6Summary {
metrics: Metrics
root_group: RootGroup
}
export interface SummaryMetric {
avg: number
max: number
med: number
min: number
'p(90)': number
'p(95)': number
}
export interface Metrics {
checks: MetricsChecks
data_received: DataReceived
data_sent: DataReceived
http_req_blocked: SummaryMetric
http_req_connecting: SummaryMetric
http_req_duration: SummaryMetric
http_req_receiving: SummaryMetric
http_req_sending: SummaryMetric
http_req_tls_handshaking: SummaryMetric
http_req_waiting: SummaryMetric
http_reqs: DataReceived
iteration_duration: SummaryMetric
iterations: DataReceived
vus: Vus
vus_max: Vus
}
export interface MetricsChecks {
fails: number
passes: number
value: number
}
export interface DataReceived {
count: number
rate: number
}
export interface Vus {
max: number
min: number
value: number
}
export interface RootGroup {
name: string
path: string
id: string
groups: any
checks: Record<string, CheckProperties>
}
export interface CheckProperties {
name: string
path: string
id: string
passes: number
fails: number
} | the_stack |
import { Component, OnInit, OnChanges, OnDestroy, AfterViewInit, Input, TemplateRef, SimpleChanges, ChangeDetectorRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap';
import { WidgetService } from '../../../../../widget.service';
import { JhiEventManager } from 'ng-jhipster';
import { Subscription } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';
import { Media } from '../../../../../../media/media.model';
import { MediaService } from '../../../../../../media/media.service';
import { ResponseWrapper } from '../../../../../../../shared/model/response-wrapper.model';
import { NotificationService } from 'app/shared';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'element-shape',
templateUrl: 'shape.component.html',
styleUrls: ['shape.component.scss']
})
export class ShapeComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@Input() element: Element;
@Input() styleClass: Object;
@Input() classProperties: Object[];
// spinner
showSpinner: boolean = false;
// sizing strategy
sizingStrategy: SizingStrategy = SizingStrategy.FIXED;
/*
* Media library modal
*/
modalRef: BsModalRef;
mediaResults: Media[];
currentMediaSearch: string;
itemsPerPage = 1600;
settings: Object;
category2media: Map<string, Object[]>;
// default size bounds
NODE_MIN_SIZE = 20;
NODE_MAX_SIZE = 100;
NODE_BORDER_MIN_SIZE = 1;
NODE_BORDER_MAX_SIZE = 5;
EDGE_MIN_SIZE = 1;
EDGE_MAX_SIZE = 10;
// Subscriber
eventSubscriber: Subscription;
constructor(private widgetService: WidgetService,
private mediaService: MediaService,
private modalService: BsModalService,
private notificationService: NotificationService,
private eventManager: JhiEventManager,
private cdr: ChangeDetectorRef,
private sanitizer: DomSanitizer) {
this.category2media = new Map();
}
ngOnInit() {
this.registerChangeInMedia();
this.initAccordingToElementAndStyleClass();
this.loadMedia();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.element && changes.styleClass) {
this.initAccordingToElementAndStyleClass();
} else {
console.log('Error: just element or style class changed during new element selection.');
}
}
ngAfterViewInit() { }
ngOnDestroy() {
this.eventManager.destroy(this.eventSubscriber);
}
initAccordingToElementAndStyleClass() {
// setting class style from scratch
if (this.element['type'] === 'v') {
this.settings = {
fieldWeight: this.initFieldWeightFromStyleClass(),
minLinearValue: this.initLinearBound('min'),
maxLinearValue: this.initLinearBound('max'),
shapeWidth: this.initSizeField('width'),
shapeHeight: this.initSizeField('height'),
shapeColor: this.styleClass['style']['background-color'],
borderWidth: this.styleClass['style']['border-width'],
borderColor: this.styleClass['style']['border-color']
};
if (this.styleClass['style']['background-image']) {
const dataImageUrl = this.sanitizer.bypassSecurityTrustUrl(this.styleClass['style']['background-image']);
this.settings['shapeImage'] = dataImageUrl;
}
// sizing strategy init (default value is FIXED, overriding if needed)
if (this.styleClass['style']['width'].includes('mapData') && this.styleClass['style']['height'].includes('mapData')) {
this.sizingStrategy = SizingStrategy.LINEAR;
}
} else {
this.settings = {
fieldWeight: this.initFieldWeightFromStyleClass(),
minLinearValue: this.initLinearBound('min'),
maxLinearValue: this.initLinearBound('max'),
lineWidth: this.initSizeField('width'),
lineColor: this.styleClass['style']['line-color'],
lineStyle: this.styleClass['style']['line-style'],
targetArrowShape: this.styleClass['style']['target-arrow-shape'],
targetArrowColor: this.styleClass['style']['target-arrow-color'],
sourceArrowShape: this.styleClass['style']['source-arrow-shape'],
sourceArrowColor: this.styleClass['style']['source-arrow-color']
};
// sizing strategy init (default value is FIXED, overriding if needed)
if (this.styleClass['style']['width'].includes('mapData')) {
this.sizingStrategy = SizingStrategy.LINEAR;
}
}
// clean pixels suffixes
this.dropSuffixes();
}
loadMedia() {
const page: string = '0';
const size: string = '1600';
this.startSpinner();
this.widgetService.loadMedia(page, size).subscribe((res: Object) => {
for (const index of Object.keys(res)) {
const currentMedia = res[index];
const currentCategory = currentMedia['category'];
if (!this.category2media.get(currentCategory)) {
this.category2media.set(currentCategory, []);
}
this.updateDataUrl(currentMedia);
this.category2media.get(currentCategory).push(currentMedia);
}
this.stopSpinner();
}, (error: HttpErrorResponse) => {
this.stopSpinner();
this.onError(error.error);
});
}
/**
* Modal search
* @param event
*/
handleSearchOnKeydown(event) {
if (event.keyCode === 13) {
this.search(this.currentMediaSearch);
} else if (event.keyCode === 46 || event.keyCode === 8) {
setTimeout(() => {
if (this.currentMediaSearch === '') {
this.clear();
}
}, 10);
}
}
search(query) {
if (!query) {
return this.clear();
}
this.currentMediaSearch = query;
this.loadAll();
}
clear() {
this.currentMediaSearch = '';
this.mediaResults = [];
}
/**
* Loads all the elements for the last selected page (this.page)
*/
loadAll() {
if (this.currentMediaSearch) {
this.mediaService.search({
page: 0,
query: this.currentMediaSearch,
size: this.itemsPerPage,
// sort: this.sort()
}).subscribe(
(res: HttpResponse<Media[]>) => this.onSuccess(res.body, res.headers),
(res: HttpErrorResponse) => this.onError(res.error)
);
return;
}
this.mediaService.query({
page: 0,
size: this.itemsPerPage,
// sort: this.sort()
}).subscribe(
(res: HttpResponse<Media[]>) => this.onSuccess(res.body, res.headers),
(res: HttpErrorResponse) => this.onError(res.error)
);
}
updateDataUrl(media: Media) {
const url = 'data:' + media['fileContentType'].replace(' ', '') + ';base64,' + media['file'];
media['file'] = this.sanitizer.bypassSecurityTrustUrl(url);
}
dropSuffixes() {
if (this.element['type'] === 'v') {
this.settings['shapeWidth'] = this.settings['shapeWidth'].replace('px', '');
this.settings['shapeHeight'] = this.settings['shapeHeight'].replace('px', '');
this.settings['borderWidth'] = this.settings['borderWidth'].replace('px', '');
} else {
this.settings['lineWidth'] = this.settings['lineWidth'].replace('px', '');
}
}
addSuffixes(settings: Object) {
if (this.element['type'] === 'v') {
settings['shapeWidth'] = settings['shapeWidth'] + 'px';
settings['shapeHeight'] = settings['shapeHeight'] + 'px';
settings['borderWidth'] = settings['borderWidth'] + 'px';
} else {
settings['lineWidth'] = settings['lineWidth'] + 'px';
}
settings['minLinearValue'] = settings['minLinearValue'] + 'px';
settings['maxLinearValue'] = settings['maxLinearValue'] + 'px';
}
initFieldWeightFromStyleClass() {
let fieldWeight;
const expression: string = this.styleClass['style']['width'];
if (expression.indexOf('mapData') >= 0) { // checking if 'width' contains a mapData function ('width' contained both in nodes and edges)
// linear size case
fieldWeight = this.extractArgFromMapDataExpression(expression, 0);
if (fieldWeight === 'edgeCount') {
fieldWeight = '@' + fieldWeight;
}
if (fieldWeight.indexOf('record.') >= 0) {
fieldWeight = fieldWeight.replace('record.', '');
}
} else {
// fixed size case
fieldWeight = '<empty>';
}
return fieldWeight;
}
/**
* 0 : fieldName
* 1 : minValue
* 2 : maxValue
* 3 : minMappedValue
* 4 : maxMappedValue
* @param argIndex
*/
extractArgFromMapDataExpression(expression: string, argIndex: number) {
let arg;
if (expression.startsWith('record.')) {
expression = expression.replace('record.', '');
}
expression = expression.replace('mapData(', '').replace(')', '');
const exprArgs: string[] = expression.split(', ');
arg = exprArgs[argIndex];
return arg;
}
/**
* 2 cases:
* - linear size case: bounds are retrieved from the mapData expression
* - fixed size: bounds are initialized to default values for edges and nodes
* @param bound: min | max
*/
initLinearBound(bound: string) {
let value;
if (this.styleClass['style']['width'].indexOf('mapData') >= 0) {
// linear size case,
if (this.element['type'] === 'v') {
if (this.styleClass['style']['width'] && this.styleClass['style']['height']) {
// then extract values form the mapData expression
const expression = this.styleClass['style']['width']; // 'width' field value and 'height' field value are equal
if (bound === 'min') {
value = this.extractArgFromMapDataExpression(expression, 3);
} else {
value = this.extractArgFromMapDataExpression(expression, 4);
}
} else {
// default values
value = this.getDefaultBoundValue(bound);
}
} else {
if (this.styleClass['style']['width']) {
// then extract values from the mapData expression
const expression = this.styleClass['style']['width'];
if (bound === 'min') {
value = this.extractArgFromMapDataExpression(expression, 3);
} else {
value = this.extractArgFromMapDataExpression(expression, 4);
}
} else {
// default values
value = this.getDefaultBoundValue(bound);
}
}
} else {
// fixed size case, use default value for edges and nodes
value = this.getDefaultBoundValue(bound);
}
return value;
}
getDefaultBoundValue(bound: string) {
let boundValue;
if (this.element['type'] === 'v') {
if (bound === 'min') {
boundValue = this.NODE_MIN_SIZE;
} else if (bound === 'max') {
boundValue = this.NODE_MAX_SIZE;
}
} else {
if (bound === 'min') {
boundValue = this.EDGE_MIN_SIZE;
} else if (bound === 'max') {
boundValue = this.EDGE_MAX_SIZE;
}
}
return boundValue;
}
/**
* Control function for linear size range values
*/
forceNumericInputForLinearSizeRanges(currentEditingBound: string) {
let updated: boolean = false;
if (this.element['type'] === 'v') {
// checking node bounds
if (this.settings['minLinearValue'] < this.NODE_MIN_SIZE) {
this.settings['minLinearValue'] = this.NODE_MIN_SIZE;
updated = true;
}
if (this.settings['maxLinearValue'] > this.NODE_MAX_SIZE) {
this.settings['maxLinearValue'] = this.NODE_MAX_SIZE;
updated = true;
}
} else {
// checking edge bounds
if (this.settings['minLinearValue'] < this.EDGE_MIN_SIZE) {
this.settings['minLinearValue'] = this.EDGE_MIN_SIZE;
updated = true;
}
if (this.settings['maxLinearValue'] > this.EDGE_MAX_SIZE) {
this.settings['maxLinearValue'] = this.EDGE_MAX_SIZE;
updated = true;
}
}
if (this.settings['minLinearValue'] >= this.settings['maxLinearValue']) {
if (currentEditingBound === 'min') {
this.settings['minLinearValue'] = this.settings['maxLinearValue'] - 1;
} else if (currentEditingBound === 'max') {
this.settings['maxLinearValue'] = this.settings['minLinearValue'] + 1;
}
updated = true;
}
}
/**
* Control function for linear size range values
*/
forceNumericInputForElementSize(settingsProperty: string) {
let updated: boolean = false;
if (settingsProperty === 'shapeWidth' || settingsProperty === 'shapeHeight') {
if (this.settings[settingsProperty] < this.NODE_MIN_SIZE) {
this.settings[settingsProperty] = this.NODE_MIN_SIZE;
updated = true;
}
if (this.settings[settingsProperty] > this.NODE_MAX_SIZE) {
this.settings[settingsProperty] = this.NODE_MAX_SIZE;
updated = true;
}
} else if (settingsProperty === 'borderWidth') {
if (this.settings[settingsProperty] < this.NODE_BORDER_MIN_SIZE) {
this.settings[settingsProperty] = this.NODE_BORDER_MIN_SIZE;
updated = true;
}
if (this.settings[settingsProperty] > this.NODE_BORDER_MAX_SIZE) {
this.settings[settingsProperty] = this.NODE_BORDER_MAX_SIZE;
updated = true;
}
} else if (settingsProperty === 'lineWidth') {
if (this.settings[settingsProperty] < this.EDGE_MIN_SIZE) {
this.settings[settingsProperty] = this.EDGE_MIN_SIZE;
updated = true;
}
if (this.settings[settingsProperty] > this.EDGE_MAX_SIZE) {
this.settings[settingsProperty] = this.EDGE_MAX_SIZE;
updated = true;
}
}
}
initSizeField(sizeField: string) {
const valueExpression = this.styleClass['style'][sizeField];
if (valueExpression.indexOf('mapData(') < 0) {
// fixed size case
return valueExpression;
} else {
// dynamic sizing case
if (this.element['type'] === 'v') {
return '20'; // width and height default value for nodes
} else {
return '1'; // width default value for edges
}
}
}
getShapeSettings() {
// add suffixes
const settings = JSON.parse(JSON.stringify(this.settings));
settings['sizingStrategy'] = this.sizingStrategy;
this.addSuffixes(settings);
return settings;
}
cleanBackgroundImageField() {
delete this.settings['shapeImage'];
}
openMediaLibrary(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
updateImage(mediaUrl) {
this.settings['shapeImage'] = mediaUrl;
this.modalRef.hide();
}
registerChangeInMedia() {
this.eventSubscriber = this.eventManager.subscribe(
'mediaListModification',
(response) => {
if (response['content']['status'] === 'OK') {
const newMedia = response['content']['media'];
this.updateDataUrl(newMedia);
const category = newMedia['category'];
if (!this.category2media.get(category)) {
this.category2media.set(category, []);
}
this.category2media.get(category).push(newMedia);
}
});
}
private onSuccess(data, headers) {
// updating data urls
for (const media of data) {
this.updateDataUrl(media);
}
this.mediaResults = data;
}
private onError(error) {
console.log(error.message);
const message: string = error.message;
this.notificationService.push('error', 'Shape', message);
}
startSpinner() {
// starting the spinner if not running
if (!this.showSpinner) {
this.showSpinner = true;
}
}
stopSpinner() {
// stopping the spinner if running
if (this.showSpinner) {
this.showSpinner = false;
}
}
}
export const enum SizingStrategy {
FIXED = 'fixed',
LINEAR = 'linear'
} | the_stack |
import Event from "../event"
import { merge } from "../assign"
import getUUID from "../sole"
import forEach from "../each"
import qs from "../qs"
// ===================================================================== 参数整合url, 将多个URLSearchParams字符串合并为一个
export function fixedURL(url: string, paramStr: string): string {
if (paramStr) {
return url + (url.indexOf("?") > -1 ? "&" : "?") + paramStr
}
return url
}
// ===================================================================== 参数转为 字符串
export function getParamString(param?: FormData | IParam | string, dataType?: string): string | FormData {
if (!param) {
return ""
}
// if (param instanceof FormData) {
// return param
// }
if (typeof param == "string") {
return param || ""
}
let str = dataType == "json" ? JSON.stringify(param) : qs.stringify(param as any)
return str
}
// ===================================================================== 获取默认的 Content-Type 的值
export function getDefaultContentType(dataType?: string): string {
if (dataType == "json") {
return "application/json"
}
return "application/x-www-form-urlencoded"
}
// ===================================================================== 安全获取子对象数据
function getSafeData(data: any, property: string): any {
if (property && data) {
let props = property.split(".")
for (let i = 0; i < props.length; i += 1) {
data = data[props[i]]
if (data == null) {
return null
}
}
}
return data
}
// ==================================================================== 接口
interface IFStrObj {
[propName: string]: string
}
interface IParam {
[propName: string]: number | string | boolean | Array<number | string | boolean> | IParam
}
type sendParam = IParam | FormData | string
enum EResType {
// eslint-disable-next-line
json = "json",
// eslint-disable-next-line
text = "text"
}
export interface IFAjaxConf {
baseURL?: string
paths?: IFStrObj
useFetch?: boolean
url?: string
method?: string
dataType?: string
resType?: EResType
param?: IParam | string
header?: IFStrObj
jsonpKey?: string
cache?: boolean
withCredentials?: boolean
}
// ==================================================================== 资源返回类
export class AjaxReq {
baseURL?: string
paths: IFStrObj = {}
useFetch: boolean = true
url: string = ""
method: string = "GET"
dataType: string = ""
resType: EResType = EResType.text
param?: IParam | string | FormData
header: IFStrObj = {}
jsonpKey: string = ""
cache: boolean = false
withCredentials: boolean = true
xhr?: XMLHttpRequest
path: string = ""
orginURL: string = ""
formatURL: string = ""
isFormData: boolean = false
isCross: boolean = false
outFlag: boolean = false;
[propName: string]: any
// constructor() {}
}
export class AjaxRes {
jsonKey: string = "json"
headers?: any = ""
status?: number
text?: string
json?: object
cancel?: boolean
err?: any
result?: any;
[propName: string]: any
// constructor() {}
getData(prot: string, data?: any): any {
if (data === undefined) {
data = this[this.jsonKey]
}
return getSafeData(data, prot)
}
getHeader(key: string): string {
if (typeof this.headers == "string") {
return new RegExp("(?:" + key + "):[ \t]*([^\r\n]*)\r").test(this.headers as string) ? RegExp.$1 : ""
}
return (this.headers.get && this.headers.get(key)) || ""
}
}
export class AjaxCourse {
req: AjaxReq = new AjaxReq()
res: AjaxRes = new AjaxRes()
progress?: ProgressEvent
ajax: Ajax
getDate(this: AjaxCourse): Date {
return this.ajax.parent.getDate()
}
constructor(ajax: Ajax) {
this.ajax = ajax
}
}
export class Ajax extends Event {
_course?: AjaxCourse
conf: IFAjaxConf
parent: AjaxGroup
on(type: string, fn: (arg: AjaxCourse) => void, isPre: boolean = false): void {
this[":on"]<Ajax>(type, fn, isPre)
}
constructor(parent: AjaxGroup, opt?: IFAjaxConf) {
super(parent)
this.parent = parent
this.conf = merge({}, ajaxGlobal.conf, parent.conf, getConf(opt))
}
// 设置参数
setConf(opt: IFAjaxConf = {}): Ajax {
getConf(opt, this.conf)
return this
}
// 中止 请求
abort(): Ajax {
ajaxAbort(this, true)
return this
}
// 超时
timeout(this: Ajax, time: number, callback: IEventOnFn): Ajax {
setTimeout(() => {
let course = this._course
if (course) {
let { req } = course
if (req) {
// 超时 设置中止
ajaxAbort(this)
// 出发超时事件
this.emit("timeout", course)
}
}
}, time)
callback && this.on("timeout", callback)
return this
}
// 发送数据, over 代表 是否要覆盖本次请求
send(this: Ajax, param?: sendParam, over: boolean = false): Ajax {
if (this._course) {
// 存在 _req
if (!over) {
// 不覆盖,取消本次发送
return this
}
// 中止当前的
this.abort()
}
// 制造 req
let course = new AjaxCourse(this)
let req = course.req
this._course = course
// 异步,settime 部分参数可以后置设置生效
setTimeout(() => {
merge(req, this.conf)
requestSend.call(this, param || {}, course)
}, 1)
return this
}
// 返回Promist
then(): Promise<AjaxCourse>
then(thenFn: (course: AjaxCourse) => any): Promise<any>
then(thenFn?: (course: AjaxCourse) => any): Promise<AjaxCourse | any> {
let pse: Promise<AjaxCourse> = new Promise((resolve, reject) => {
this.on("callback", function(course) {
resolve(course)
})
this.on("timeout", function() {
// eslint-disable-next-line
reject({ err: "访问超时", errType: 1 })
})
this.on("abort", function() {
// eslint-disable-next-line
reject({ err: "访问中止", errType: 2 })
})
})
return (thenFn && pse.then(thenFn)) || pse
}
}
type IEventOnFn = (this: Ajax, arg: AjaxCourse) => void
interface shortcutEventObj {
[propName: string]: IEventOnFn
}
type shortcutEvent = shortcutEventObj | IEventOnFn
type groupLoadOnNew = (ajax: Ajax) => void
function groupLoad(target: AjaxGroup, url: string | IFAjaxConf, callback?: IEventOnFn | sendParam, param?: sendParam | groupLoadOnNew, onNew?: groupLoadOnNew) {
let opt = typeof url == "string" ? { url } : url
if (callback && typeof callback != "function") {
onNew = param as groupLoadOnNew
param = callback
callback = undefined
}
let one = new Ajax(target, opt)
onNew && onNew(one)
if (typeof callback == "function") {
one.on("callback", callback)
}
one.send(param as sendParam)
return one
}
let ajaxDateDiff: number = 0
export class AjaxGroup extends Event {
dateDiff: number = ajaxDateDiff
conf: IFAjaxConf = {}
// global?: Global
parent?: Global
// Group?: AjaxGroupConstructor
on(type: string, fn: (arg: AjaxCourse) => void, isPre: boolean = false): void {
this[":on"]<AjaxGroup>(type, fn, isPre)
}
constructor(opt?: IFAjaxConf) {
super(ajaxGlobal)
this.conf = {}
opt && this.setConf(opt)
}
// 设置默认
setConf(opt?: IFAjaxConf): AjaxGroup {
opt && getConf(opt, this.conf)
return this
}
// 创建一个ajax
create(opt?: IFAjaxConf): Ajax {
return new Ajax(this, opt)
}
// 快捷函数
shortcut(opt: IFAjaxConf, events?: shortcutEvent) {
return (callback: IEventOnFn | sendParam, param: sendParam): Ajax => {
return groupLoad(this, opt, callback, param, function(one: Ajax) {
if (events) {
if (typeof events == "function") {
one.on("callback", events)
return
}
for (let n in events) {
one.on(n, events[n])
}
}
})
}
}
// 创建并加载
load(url: string | IFAjaxConf, callback?: IEventOnFn | sendParam, param?: sendParam): Ajax {
return groupLoad(this, url, callback, param)
}
// promise
fetch(opt?: IFAjaxConf, param?: sendParam): Promise<any> {
return this.create(opt)
.send(param)
.then()
}
setDate(date: string | Date): void {
if (typeof date == "string") {
date = new Date(date.replace(/(\d)T(\d)/, "$1 $2").replace(/\.\d+$/, ""))
}
this.dateDiff = ajaxDateDiff = date.getTime() - new Date().getTime()
}
// 获取 服务器时间
getDate(): Date {
return new Date(this.dateDiff + new Date().getTime())
}
}
export class Global extends Event {
conf: IFAjaxConf = { useFetch: true, resType: EResType.json, jsonpKey: "callback", cache: true }
on(type: string, fn: (arg: AjaxCourse) => void, isPre: boolean = false): void {
this[":on"]<Global>(type, fn, isPre)
}
// constructor() {
// super()
// }
setConf(conf: IFAjaxConf) {
getConf(conf, this.conf)
}
// eslint-disable-next-line
isFormData(data: any) {
// eslint-disable-next-line
console.log("no isFormData Fn")
return false
}
// eslint-disable-next-line
fetchExecute(course: AjaxCourse, ajax: Ajax) {
// eslint-disable-next-line
console.log("no fetchExecute Fn")
}
}
export let ajaxGlobal = new Global()
// 统一设置参数
function getConf({ baseURL, paths, useFetch, url, method, dataType, resType, param = {}, header = {}, jsonpKey, cache, withCredentials }: IFAjaxConf = {}, val: IFAjaxConf = {}): IFAjaxConf {
if (baseURL) {
val.baseURL = baseURL
}
if (paths) {
val.paths = paths
}
if (typeof useFetch == "boolean") {
val.useFetch = useFetch
}
if (url) {
// url ==> req
val.url = url
}
if (method) {
// 方法 ==> req
val.method = method.toUpperCase()
}
if (param) {
// 参数 ==> req
val.param = param
}
if (header) {
// 请求头设置 ==> req
val.header = header
}
if (dataType) {
// 缓存 get ==> req
val.dataType = dataType
}
if (resType) {
// 返回数据类型
val.resType = resType
}
if (jsonpKey) {
val.jsonpKey = jsonpKey
}
if (typeof cache == "boolean") {
val.cache = cache
}
if (typeof withCredentials == "boolean") {
val.withCredentials = withCredentials
}
return val
}
// 中止
function ajaxAbort(target: Ajax, flag: boolean = false): void {
let course = target._course
if (course) {
let { req } = course
// 设置outFlag,会中止回调函数的回调
req.outFlag = true
if (req.xhr) {
// xhr 可以原声支持 中止
req.xhr.abort()
req.xhr = undefined
}
delete target._course
flag && target.emit("abort", course)
}
}
// 发送数据整理
function requestSend(this: Ajax, param: sendParam, course: AjaxCourse) {
let { req } = course
// console.log("xxxx", param, req);
if (req.outFlag) {
// 已经中止
return
}
// 方法
req.method = String(req.method || "get").toUpperCase()
// 之前发出
this.emit("before", course)
req.path = ""
req.orginURL = req.url || ""
// let paths = req.paths || {}
// 短路径替换
req.formatURL = req.orginURL
// 自定义req属性
.replace(/^<([\w,:]*)>/, function(s0: string, s1: string) {
s1.split(/,+/).forEach(function(key: string) {
let [k1, k2] = key.toLowerCase().split(/:+/)
if (k2 === undefined) {
k2 = k1
k1 = "method"
}
req[k1] = k2
})
return ""
})
// 短路经
.replace(/^(\w+):(?!\/\/)/, (s0: string, s1: string) => {
req.path = s1
return req.paths[s1] || s0
})
let httpReg = new RegExp("^(:?http(:?s)?:)?//", "i")
if (req.baseURL && !httpReg.test(req.url)) {
// 有baseURL 并且不是全量地址
req.formatURL = req.baseURL + req.formatURL
}
// 确认短路径后
this.emit("path", course)
// 是否为 FormData
let isFormData = ajaxGlobal.isFormData(param)
// if (FormData && param instanceof FormData) {
// isFormData = true
// }
req.isFormData = isFormData
// 请求类型
let dataType = (req.dataType = String(req.dataType || "").toLowerCase())
if (isFormData) {
// FormData 将参数都添加到 FormData中
forEach(req.param, function(value, key) {
let fd = <FormData>param
fd.append(key as string, value)
})
req.param = param
} else {
if (typeof param == "string") {
// 参数为字符串,自动格式化为 object,后面合并后在序列化
param = dataType == "json" ? JSON.parse(param) : qs.parse(param)
}
merge(req.param as IParam, (param as IParam) || {})
}
// 数据整理完成
this.emit("open", course)
// 还原,防止复写, 防止在 open中重写这些参数
req.isFormData = isFormData
req.dataType = dataType
let method = String(req.method || "get").toUpperCase()
req.method = method
if (method == "GET") {
let para = req.param as IParam
if (para && req.cache === false && !para._r_) {
// 加随机数,去缓存
para._r_ = getUUID()
}
}
req.url = req.formatURL
ajaxGlobal.fetchExecute(course, this)
}
// 结束 统一处理返回的数据
export function responseEnd(this: Ajax, course: AjaxCourse): void {
let { req, res } = course
if (!res.json && res.text) {
// 尝试格式为 json字符串
try {
res.json = JSON.parse(res.text)
} catch (e) {
res.json = {}
}
}
if (req.resType == "json") {
res.result = res.json
}
let date = res.getHeader("Date")
if (date) {
// console.log("this.parent", this)
this.parent.setDate(date)
}
delete this._course
// 出发验证事件
this.emit("verify", course)
if (res.cancel === true) {
// 验证事件中设置 res.cancel 为false,中断处理
return
}
// callback事件,可以看做函数回调
this.emit("callback", course)
} | the_stack |
import { Client as DBClient } from 'pg';
import { InventorySubgraph } from '../../services/subgraph';
import { makeInventoryData } from '../helpers';
import Web3 from 'web3';
import { registry, setupHub } from '../helpers/server';
const { toWei } = Web3.utils;
const stubNonce = 'abc:123';
let stubAuthToken = 'def--456';
let stubTimestamp = process.hrtime.bigint();
let stubWeb3Available = true;
let stubRelayAvailable = true;
let stubInventorySubgraph: () => InventorySubgraph;
let defaultContractMethods = {
cardpayVersion() {
return {
async call() {
return Promise.resolve('any');
},
};
},
};
let contractPauseMethod = (isPaused: boolean) => ({
paused() {
return {
async call() {
return Promise.resolve(isPaused);
},
};
},
});
let stubMarketContract: () => any;
class StubAuthenticationUtils {
generateNonce() {
return stubNonce;
}
buildAuthToken() {
return stubAuthToken;
}
extractVerifiedTimestamp(_nonce: string) {
return stubTimestamp;
}
validateAuthToken(encryptedAuthToken: string) {
return handleValidateAuthToken(encryptedAuthToken);
}
}
class StubSubgraph {
async getInventory(reservedPrepaidCards: string[], issuer?: string | undefined): Promise<InventorySubgraph> {
let result = stubInventorySubgraph();
// this replicates the subgraph's where clause for issuer
if (issuer) {
result = {
data: {
skuinventories: (result.data.skuinventories = result.data.skuinventories.filter(
(i) => i.sku.issuer.id === issuer
)),
},
};
}
// this replicates the subgraph's where clause for reserved cards
for (let inventory of result.data.skuinventories) {
inventory.prepaidCards = inventory.prepaidCards.filter((p) => !reservedPrepaidCards.includes(p.prepaidCardId));
}
return Promise.resolve(result);
}
}
class StubWeb3 {
isAvailable() {
return Promise.resolve(stubWeb3Available);
}
getInstance() {
return {
eth: {
net: {
getId() {
return 77; // sokol network id
},
},
Contract: class {
get methods() {
return stubMarketContract();
}
},
},
};
}
}
class StubRelay {
isAvailable() {
return Promise.resolve(stubRelayAvailable);
}
}
let stubUserAddress = '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13';
let stubIssuer = '0xb21851B00bd13C008f703A21DFDd292b28A736b3';
function handleValidateAuthToken(encryptedString: string) {
if (encryptedString === 'abc123--def456--ghi789') {
return stubUserAddress;
}
return;
}
describe('GET /api/inventory', function () {
let db: DBClient;
this.beforeEach(function () {
registry(this).register('authentication-utils', StubAuthenticationUtils);
registry(this).register('subgraph', StubSubgraph);
registry(this).register('web3-http', StubWeb3);
registry(this).register('relay', StubRelay);
});
let { getContainer, request } = setupHub(this);
this.beforeEach(async function () {
let dbManager = await getContainer().lookup('database-manager');
db = await dbManager.getClient();
await db.query(`DELETE FROM reservations`);
await db.query(`DELETE FROM wallet_orders`);
stubMarketContract = () => ({
...defaultContractMethods,
...contractPauseMethod(false),
});
stubRelayAvailable = true;
stubWeb3Available = true;
});
it(`retrieves inventory for an authenticated client for all SKUs`, async function () {
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [
'0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC',
'0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad',
]),
makeInventoryData(
'sku2',
'200',
toWei('2'),
['0x483F081bB0C25A5B216D1A4BD9CE0196092A0575'],
'did:cardstack:test1'
),
],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 2,
},
},
{
type: 'inventories',
id: 'sku2',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku2',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 200,
'ask-price': toWei('2'),
'customization-DID': 'did:cardstack:test1',
reloadable: false,
transferrable: false,
quantity: 1,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`does not return inventory when contract paused`, async function () {
stubMarketContract = () => ({
...defaultContractMethods,
...contractPauseMethod(true),
});
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [
'0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC',
'0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad',
]),
],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 0,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`does not return inventory when RPC node is unavailable`, async function () {
stubWeb3Available = false;
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [
'0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC',
'0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad',
]),
],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 0,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`does not return inventory when relay server is unavailable`, async function () {
stubRelayAvailable = false;
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [
'0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC',
'0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad',
]),
],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 0,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`can filter inventory by issuer`, async function () {
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [
'0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC',
'0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad',
]),
makeInventoryData(
'sku2',
'200',
toWei('2'),
['0x483F081bB0C25A5B216D1A4BD9CE0196092A0575'],
'did:cardstack:test1',
stubIssuer
),
],
},
});
await request()
.get(`/api/inventories?filter[issuer]=${stubIssuer}`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku2',
attributes: {
issuer: stubIssuer,
sku: 'sku2',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 200,
'ask-price': toWei('2'),
'customization-DID': 'did:cardstack:test1',
reloadable: false,
transferrable: false,
quantity: 1,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`does not include pending reservations in the inventory count`, async function () {
let prepaidCard1 = '0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC';
let prepaidCard2 = '0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad';
await db.query(`INSERT INTO reservations (user_address, sku) VALUES ($1, $2)`, [stubUserAddress, 'sku1']);
stubInventorySubgraph = () => ({
data: {
skuinventories: [makeInventoryData('sku1', '100', toWei('1'), [prepaidCard1, prepaidCard2])],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 1,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`does includes expired reservations in the inventory count`, async function () {
let prepaidCard1 = '0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC';
let prepaidCard2 = '0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad';
await db.query(
`INSERT INTO reservations (user_address, sku, updated_at) VALUES ($1, $2, now() - interval '10 minutes')`,
[stubUserAddress, 'sku1']
);
await db.query(
`INSERT INTO reservations (user_address, sku, updated_at) VALUES ($1, $2, now() - interval '61 minutes')`,
[stubUserAddress, 'sku1']
);
stubInventorySubgraph = () => ({
data: {
skuinventories: [makeInventoryData('sku1', '100', toWei('1'), [prepaidCard1, prepaidCard2])],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 1,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`does not include recently provisioned prepaid cards in the inventory count when the subgraph has not synced yet`, async function () {
let prepaidCard1 = '0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC';
let prepaidCard2 = '0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad';
await db.query(`INSERT INTO reservations (user_address, sku, prepaid_card_address) VALUES ($1, $2, $3)`, [
stubUserAddress,
'sku1',
prepaidCard1,
]);
stubInventorySubgraph = () => ({
data: {
// in this scenario, the provisioned prepaid card still appears in the subgraph inventory
skuinventories: [makeInventoryData('sku1', '100', toWei('1'), [prepaidCard1, prepaidCard2])],
},
});
});
it(`can reflect no inventory available`, async function () {
let prepaidCard1 = '0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC';
await db.query(`INSERT INTO reservations (user_address, sku) VALUES ($1, $2)`, [stubUserAddress, 'sku1']);
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [prepaidCard1]),
makeInventoryData('sku2', '200', toWei('2'), []),
],
},
});
await request()
.get(`/api/inventories`)
.set('Authorization', 'Bearer abc123--def456--ghi789')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(200)
.expect({
data: [
{
type: 'inventories',
id: 'sku1',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku1',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 100,
'ask-price': toWei('1'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 0,
},
},
{
type: 'inventories',
id: 'sku2',
attributes: {
issuer: '0x2f58630CA445Ab1a6DE2Bb9892AA2e1d60876C13',
sku: 'sku2',
'issuing-token-symbol': 'DAI',
'issuing-token-address': '0xFeDc0c803390bbdA5C4C296776f4b574eC4F30D1',
'face-value': 200,
'ask-price': toWei('2'),
'customization-DID': null,
reloadable: false,
transferrable: false,
quantity: 0,
},
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
it(`returns 401 when client is not authenticated`, async function () {
stubInventorySubgraph = () => ({
data: {
skuinventories: [
makeInventoryData('sku1', '100', toWei('1'), [
'0x024db5796C3CaAB34e9c0995A1DF17A91EECA6cC',
'0x04699Ff48CC6531727A12344c30F3eD1062Ff3ad',
]),
],
},
});
await request()
.get('/api/custodial-wallet')
.set('Accept', 'application/vnd.api+json')
.set('Content-Type', 'application/vnd.api+json')
.expect(401)
.expect({
errors: [
{
status: '401',
title: 'No valid auth token',
},
],
})
.expect('Content-Type', 'application/vnd.api+json');
});
}); | the_stack |
export const SP: ISPComponents;
/**
* SharePoint Components
*/
export interface ISPComponents {
/**
* ### How to create a callout
* ```ts
* Helper.SP.CalloutManager.init().then(() => {
* // Create the callout
* let callout = Helper.SP.CalloutManager.createNewIfNecessary({
* ID: "UniqueId",
* launchPoint: document.querySelector("input[value='Run']"),
* title: "My Custom Callout",
* content: "<p>This is the content of the callout. An element can be applied instead of a string."
* });
* });
* ```
*/
CalloutManager: ICalloutManager,
/**
* ### How to create a modal dialog
* ```ts
* Helper.SP.ModalDialog.showWaitScreenWithNoClose("Loading the Data").then(dlg => {
* // Do Stuff and then close the dialog
* dlg.close();
* });
* ```
*/
ModalDialog: IModalDialog,
/**
* ### How to create a notification
* ```ts
* Helper.SP.Notify.addNotifition("This is a notification.", false);
* ```
*/
Notify: INotify,
/**
* ### How to wait for a library to be loaded
* ```ts
* Helper.SP.SOD.executeOrDelayUntilScriptLoaded(() => {
* // Do Stuff
* }, "gd-sprest");
* ```
*/
SOD: ISOD,
/**
* ### How to create a status
* ```ts
* Helper.SP.Status.addStatus("Success", "This is a custom status.");
* ```
*/
Status: IStatus
}
/**
* Callout
*/
export interface ICallout {
/** Adds a link to the actions panel of the callout window. */
addAction(action: ICalloutAction): any;
/**
* Adds an event handler to the callout.
* Examples - opened, opening, closed and closing
*/
addEventCallback(eventName: string, callback: (callout: ICallout) => void): any;
/** Closes the callout. */
close(useAnimation: boolean): any;
/** Do not call this method, use the CalloutManager to remove the callout. */
destroy();
/** Returns the action menu of the callout. */
getActionMenu(): ICalloutActionMenu;
/** Returns the beak orientation of the callout. */
getBeakOrientation(): string;
/** Returns the bounding box element of the callout. */
getBoundingBox(): HTMLElement;
/** Returns the html of the content. */
getContent(): string;
/** Returns the content element. */
getContentElement(): HTMLElement;
/** Returns the content width of the callout. */
getContentWidth(): number;
/** Returns the unique id of the callout. */
getID(): string;
/** Returns the launch point element of the callout. */
getLaunchPoint(): HTMLElement;
/** Returns the open options of the callout. */
getOpenOptions(): ICalloutOpenOptions;
/** Gets the position of the callout. */
getPositionAlgorithm(): any;
/** Returns the title of the callout. */
getTitle(): string;
/** Returns true if the callout is closed. */
isClosed(): boolean
/** Returns true if the callout is closing. */
isClosing(): boolean;
/** Returns true if the callout is opened. */
isOpen(): boolean;
/** Returns true if the callout is opening or opened. */
isOpenOrOpening(): boolean;
/** Returns true if the callout is in the "Opening" state. */
isOpening(): boolean;
/** Displays the callout. */
open(useAnimation?: boolean): any;
/** Re-renders the actions menu. Call after the actions menu is changed. */
refreshActions();
/**
* Sets options for the callout.
* Note - Not all options can be changed for the callout after its creation. */
set(options: ICalloutOptions): any;
/** Displays the callout if it's hidden, hides it otherwise. */
toggle();
}
/**
* Callout Action
*/
export interface ICalloutAction {
getDisabledToolTip(): string;
getIsDisabledCallback(): (action: ICalloutAction) => boolean;
getIsMenu(): boolean;
getIsVisibleCallback(): (action: ICalloutAction) => boolean;
getMenuEntries(): Array<ICalloutActionMenuEntry>;
getText(): string;
getToolTop(): string;
isEnabled(): boolean;
isVisible(): boolean;
render();
set(options: ICalloutActionOptions);
}
/**
* Callout Action Menu
*/
export interface ICalloutActionMenu {
constructor(actionId: any): ICalloutActionMenu;
addAction(action: ICalloutAction): any;
calculateActionWidth();
getActions(): Array<ICalloutAction>;
refreshActions();
render();
}
/**
* Callout Action Options
*/
export interface ICalloutActionOptions {
disabledTooltip?: string;
isEnabledCallback?: (action: ICalloutAction) => boolean;
isVisibleCallback?: (action: ICalloutAction) => boolean;
menuEntries?: Array<ICalloutActionMenu>;
onClickCallback?: (event: Event, action: ICalloutAction) => any;
text?: string;
tooltip?: string;
}
/**
* Callout Action Menu Entry
*/
export interface ICalloutActionMenuEntry {
onClickCallback: (actionMenuEntry: ICalloutActionMenuEntry, actionMenuEntryIndex: number) => void;
iconUrl?: string;
text: string;
}
/**
* Callout Manager
*/
export interface ICalloutManager {
/** Closes all callouts on the page. */
closeAll();
/** Returns true if the associated callout is open. */
containsOneCalloutOpen(el: HTMLElement);
/** Creates an action menu entry. */
createAction(options: ICalloutActionOptions): ICalloutAction;
/** Creates an action menu entries. */
createMenuEntries(options: Array<ICalloutActionMenuEntry>): Array<ICalloutActionMenu>;
/** Creates a new callout. */
createNew(options: ICalloutOptions);
/** Checks if the callout id exists, before creating it. */
createNewIfNecessary(options: ICalloutOptions): ICallout;
/** Performs an action on each callout on the page. */
forEach(callback: (callout: ICallout) => void);
/** Finds the closest launch point and returns the callout associated with it. */
getFromCalloutDescendant(descendant: HTMLElement): ICallout;
/** Returns the callout from the specified launch point. */
getFromLaunchPoint(launchPoint: HTMLElement): ICallout;
/** Returns the callout for the specified launch point, null if it doesn't exist. */
getFromLaunchPointIfExists(launchPoint: HTMLElement): ICallout;
/** Returns true if at least one callout is defined on the page is opened or opening. */
isAtLeastOneCalloutOn(): boolean;
/** Returns true if at least one callout is opened on the page. */
isAtLeastOneCalloutOpen(): boolean;
/**
* Method to ensure the core script is loaded.
*/
init(): PromiseLike<void>;
/** Removes the callout and destroys it. */
remove(callout: ICallout): any;
}
/**
* Callout Options
*/
export interface ICalloutOptions {
/** The unique id of the callout. */
ID: string;
/** The orientation of the callout. The valid options are: topBottom (default) or leftRight */
beakOrientation?: string;
/** */
boundingBox?: Element;
/** The html to be displayed in the callout. */
content?: string;
/** Element to be displayed in the callout. */
contentElement?: Element;
/** The width in pixels. Default - 350px */
contentWidth?: number;
/** The element to apply the callout to. */
launchPoint: Element;
/** Event triggered after the callout is closed. */
onClosedCallback?(callout: ICallout);
/** Event triggered before the callout is closed. */
onClosingCallback?(callout: ICallout);
/** Event triggered after the callout is shown. */
onOpenedCallback?(callout: ICallout);
/** Event triggered after the callout is rendered, but before it is positioned and shown. */
onOpeningCallback?(callout: ICallout);
/** Defines the callout opening behavior. */
openOptions?: ICalloutOpenOptions;
/** Sets the position of the callout during the opening event. */
positionAlgorithm?(callout: ICallout);
/** The title of the callout. */
title?: string;
}
/**
* Callout Open Options
*/
export interface ICalloutOpenOptions {
/** Closes the callout on blur. */
closeCalloutOnBlur?: boolean;
/** The event name. Example: 'click' */
event?: string;
/** Close button will be shown within the callout window. */
showCloseButton?: boolean;
}
/**
* Dialog Options
*/
export interface IDialogOptions {
/** A Boolean value that specifies whether the dialog can be maximized. true if the Maximize button is shown; otherwise, false. */
allowMaximize?: boolean;
/** An object that contains data that are passed to the dialog. */
args?: any;
/** A Boolean value that specifies whether the dialog platform handles dialog sizing. */
autoSize?: boolean;
/** A function pointer that specifies the return callback function. The function takes two parameters, a dialogResult of type SP.UI.DialogResult Enumeration and a returnValue of type object that contains any data returned by the dialog. */
dialogReturnValueCallback?: (dialogResult?: number, returnVal?: any) => void;
/** An integer value that specifies the height of the dialog. If height is not specified, the height of the dialog is autosized by default. If autosize is false, the dialog height is set to 576 pixels. */
height?: number;
/** An html element to display in the dialog. If both html and url are specified, url takes precedence. Either url or html must be specified. */
html?: Element;
/** A Boolean value that specifies whether the Close button appears on the dialog. */
showClose?: boolean;
/** A Boolean value that specifies whether the dialog opens in a maximized state. true the dialog opens maximized. Otherwise, the dialog is opened at the requested sized if specified; otherwise, the default size, if specified; otherwise, the autosized size. */
showMaximized?: boolean;
/** A string that contains the title of the dialog. */
title?: string;
/** A string that contains the URL of the page that appears in the dialog. If both url and html are specified, url takes precedence. Either url or html must be specified. */
url?: string;
/** An integer value that specifies the width of the dialog. If width is not specified, the width of the dialog is autosized by default. If autosize is false, the width of the dialog is set to 768 pixels. */
width?: number;
/** An integer value that specifies the x-offset of the dialog. This value works like the CSS left value. */
x?: number;
/** An integer value that specifies the y-offset of the dialog. This value works like the CSS top value. */
y?: number;
}
/**
* @cateogry Modal Dialog
*/
export interface IModalDialog {
/**
* Closes the most recently opened modal dialog with the specified dialog result and return value.
* @param dialogResult - One of the enumeration values that specifies the result of the modal dialog.
* @param returnVal - The return value of the modal dialog.
*/
commonModalDialogClose(dialogResult?: number, returnVal?: any);
/**
* Displays a modal dialog with the specified URL, options, callback function, and arguments.
* @param url - The URL of the page to be shown in the modal dialog.
* @param options - The options to create the modal dialog.
* @param callback - The callback function that runs when the modal dialog is closed.
* @param args - The arguments to the modal dialog.
*/
commonModalDialogOpen(url: string, options?: IDialogOptions, callback?: (dialogResult?: number, returnVal?: any) => void, args?: any);
/**
* Method to ensure the core script is loaded
*/
load(): PromiseLike<void>;
/**
* Displays a modal dialog with the specified URL, callback function, width, and height.
* @param url - The URL of the page to be shown in the modal dialog.
* @param callback - The callback function that runs when the modal dialog is closed.
* @param width - The width of the modal dialog.
* @param height - The height of the modal dialog.
*/
OpenPopUpPage(url: string, callback?: (dialogResult?: number, returnVal?: any) => void, width?: number, height?: number);
/**
* Refreshes the parent page of the modal dialog when the dialog is closed by clicking OK.
* @param dialogResult - The result of the modal dialog.
*/
RefreshPage(dialogResult?: number);
/**
* Displays a modal dialog with specified dialog options.
* @param options - The options to create the modal dialog.
*/
showModalDialog(options: IDialogOptions): PromiseLike<IModalDialogObj>;
/**
* Displays a modal dialog using the page at the specified URL.
* @param url - The URL of the page to be shown in the modal dialog.
*/
ShowPopupDialog(url: string);
/**
* Displays a wait screen dialog that has a Cancel button using the specified parameters.
* @param title - The title of the wait screen dialog.
* @param message - The message that is shown in the wait screen dialog.
* @param callback - The callback function that runs when the wait screen dialog is closed.
* @param height - The height of the wait screen dialog.
* @param width - The width of the wait screen dialog.
*/
showWaitScreenSize(title: string, message?: string, callback?: () => void, height?: number, width?: number): PromiseLike<IModalDialogObj>;
/**
* Displays a wait screen dialog that does not have a Cancel button using the specified parameters.
* @param title - The title of the wait screen dialog.
* @param message - The message that is shown in the wait screen dialog.
* @param height - The height of the wait screen dialog.
* @param width - The width of the wait screen dialog.
*/
showWaitScreenWithNoClose(title: string, message?: string, height?: number, width?: number): PromiseLike<IModalDialogObj>;
}
/**
* Modal Dialog Object
*/
export interface IModalDialogObj {
/**
* Auto-sizes the modal dialog.
*/
autoSize();
/**
* Auto-sizes the modal dialog.
* Can't find documentation on this.
*/
autoSizeSupressScrollbar(d: any);
/**
* Closes the most recently opened modal dialog with the specified dialog result.
* @param dialogResult - One of the enumeration values that specifies the result of the modal dialog.
*/
close(dialogResult?: number);
/** Gets the allow maximized property. */
get_allowMaximize(): boolean;
/** Gets the modal dialog arguments. */
get_args(): any;
/** Gets the closed property. */
get_closed(): boolean;
/** Gets the modal dialog element. */
get_dialogElement(): HTMLDivElement;
/** Need to find documentation. */
get_firstTabStop(): any;
/** Gets the iframe element. */
get_frameElement(): HTMLIFrameElement;
/** Gets the html property. */
get_html(): HTMLElement;
/** True if the maximized/restore button is visible. */
get_isMaximized(): boolean;
/** Need to find documentation. */
get_lastTabStop(): any;
/** Gets the return value. */
get_returnValue(): any;
/** True if the close button is visible. */
get_showClose(): boolean;
/** Gets the title property. */
get_title(): string;
/** Gets the url property. */
get_url(): string;
/**
* Hides the dialog
*/
hide();
/**
* Sets the return value
*/
set_returnValue(value: any);
/**
* Sets the title
*/
set_title(title: string);
/**
* Sets the sub title of the close dialog
*/
setSubTitle(value: string);
/**
* Sets the title of the close dialog
*/
setTitle(value: string);
/**
* Shows the dialog
*/
show();
}
/**
* Notify
*/
export interface INotify {
/**
* Adds a notification to the page. By default, notifications appear for five seconds.
* @param html - The message inside the notification.
* @param sticky - Specifies whether the notification stays on the page until removed.
* @returns A promise containing the ID of the notification that was added to the page.
*/
addNotification(html: string, sticky?: boolean): PromiseLike<string>;
/**
* Method to ensure the core script is loaded
*/
load(): PromiseLike<void>;
/**
* Removes the specified notification from the page.
* @param id - The notification to remove from the page.
*/
removeNotification(id: string);
}
/**
* Script on Demand (SOD)
*/
export interface ISOD {
/**
* Executes the specified function in the specified file with the optional arguments.
* @param key - The name of the file containing the JavaScript function.
* @param functionName - The function to execute.
* @param args - The optional arguments to the function.
*/
execute(key: string, functionName: string, ...args);
/**
* Ensures that the specified file that contains the specified function is loaded and then runs the specified callback function.
* @param key - The name of the file containing the function that is executed.
* @param functionName - The name of the function that is executed.
* @param fn - The function that is called once functionName has finished executing.
*/
executeFunc(key: string, functionName: string, fn: Function);
/**
* Executes the specified function if the specified event has occurred; otherwise, adds the function to the pending job queue.
* @param func - The function to execute.
* @param eventName - The name of the event.
*/
executeOrDelayUntilEventNotified(func: Function, eventName: string);
/**
* Executes the specified function if the file containing it is loaded; otherwise, adds it to the pending job queue.
* @param func - The function to execute.
* @param depScriptFileName - The name of the file containing the function.
*/
executeOrDelayUntilScriptLoaded(func: Function, depScriptFileName: string);
/**
* Records the event and executes any jobs in the pending job queue that are waiting on the event.
* @param eventName - The name of the event.
*/
notifyEventAndExecuteWaitingJobs(eventName: string);
/**
* Records that the script file is loaded and executes any jobs in the pending job queue that are waiting for the script file to be loaded.
* @param scriptFileName - The name of the script file.
*/
notifyScriptLoadedAndExecuteWaitingJobs(scriptFileName: string);
/**
* Registers the specified file at the specified URL.
* @param key - The name of the file to register.
* @param url - The relative (to the server root) URL of the file.
*/
registerSod(key: string, url: string);
/**
* Registers the specified file as a dependency of another file.
* @param key - The name of the file to which the other file is dependent.
* @param dep - The name of the dependent file.
*/
registerSodDep(key: string, dep: string);
}
/**
* Status
*/
export interface IStatus {
/**
* Adds a status message to the page.
* @param title - The title of the status message.
* @param html - The contents of the status message.
* @param prepend - Specifies whether the status message will appear at the beginning of the list.
*/
addStatus(title: string, html?: string, prepend?: boolean): PromiseLike<string>;
/**
* Appends text to an existing status message.
* @param id - The ID of the status message to remove.
* @param title - The title of the status message.
* @param html - The contents of the status message.
*/
appendStatus(id: string, title: string, html: string): PromiseLike<string>;
/**
* Method to ensure the core script is loaded
*/
load(): PromiseLike<void>;
/**
* Removes all status messages from the page.
* @param hide - Specifies that the status messages should be hidden.
*/
removeAllStatus(hide?: boolean);
/**
* Removes the specified status message.
* @param id - The ID of the status message to remove.
*/
removeStatus(id: string);
/**
* Sets the priority color of the specified status message.
* @param id - The ID of the status message to remove.
* @param color - The color to set for the status message. The following table lists the values and their priority.
*/
setStatusPriColor(id: string, color: string);
/**
* Updates the specified status message.
* @param id - The ID of the status message to remove.
* @param html - The contents of the status message.
*/
updateStatus(id: string, html: string);
} | the_stack |
import { HttpClient, HttpClientModule, HttpHeaders, HttpParams, HttpRequest, HttpResponse } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { inject, TestBed } from '@angular/core/testing';
import * as Ro from '@nakedobjects/restful-objects';
import * as momentNs from 'moment';
import { ConfigService } from './config.service';
import { MaskService } from './mask.service';
const moment = momentNs;
const supportedDateFormats = ['D/M/YYYY', 'D/M/YY', 'D MMM YYYY', 'D MMMM YYYY', 'D MMM YY', 'D MMMM YY'];
describe('MaskService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ConfigService, MaskService]
}));
beforeEach(() => {
// 0. set up the test environment
TestBed.configureTestingModule({
imports: [
// no more boilerplate code w/ custom providers needed :-)
HttpClientModule,
HttpClientTestingModule
],
providers: [
ConfigService,
MaskService
]
});
});
// beforeEach(() => {
// TestBed.configureTestingModule({
// providers: [
// MockBackend,
// BaseRequestOptions,
// {
// provide: HttpClient,
// deps: [MockBackend, BaseRequestOptions],
// useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => new Http(backend, defaultOptions)
// },
// ConfigService,
// MaskService]
// });
// });
function testMask(maskService: MaskService, input: any, mask: string, format: Ro.FormatType, expectedResult: string) {
const result = maskService.toLocalFilter(mask, format).filter(input);
expect(result).toBe(expectedResult);
}
function testDefaultMask(maskService: MaskService, input: any, format: Ro.FormatType, expectedResult: string) {
testMask(maskService, input, '', format, expectedResult);
}
describe('default string', () => {
it('masks empty', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, '', 'string', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, null, 'string', '')));
it('masks a string', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, 'a string', 'string', 'a string')));
});
describe('default int', () => {
it('masks empty', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, '', 'int', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, null, 'int', '')));
it('masks 0', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, 0, 'int', '0')));
it('masks 101', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, 101, 'int', '101')));
it('masks 1002', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, 1002, 'int', '1,002')));
it('masks 10003', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, 10003, 'int', '10,003')));
// TODO fix
// it("masks max int", inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, Number.MAX_VALUE, "int",
// tslint:disable-next-line:max-line-length
// "179,769,313,486,232,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000")));
});
const arbitaryDate1 = new Date(Date.UTC(1985, 5, 4, 16, 27, 10));
const arbitaryDate2 = new Date(Date.UTC(2003, 1, 20, 1, 13, 55));
const arbitaryDate3 = new Date(Date.UTC(2016, 7, 5, 23, 45, 8));
describe('default date-time', () => {
let ts1: string;
let ts2: string;
let ts3: string;
beforeEach(inject([MaskService], (maskService: MaskService) => {
maskService.setDateMaskMapping('test', 'date-time', 'D MMM YYYY HH:mm:ss');
const f = maskService.toLocalFilter('test', 'date-time');
ts1 = f.filter(arbitaryDate1); // "4 Jun 1985 05:27:10"
ts2 = f.filter(arbitaryDate2); // "20 Feb 2003 01:13:55"
ts3 = f.filter(arbitaryDate3); // "6 Aug 2016 12:45:08"
}));
it('masks empty', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, '', 'date-time', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, null, 'date-time', '')));
// these tests are locale specific UTC -> GMT/BST
it('masks arbitaryDate1', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, arbitaryDate1, 'date-time', ts1)));
it('masks arbitaryDate2', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, arbitaryDate2, 'date-time', ts2)));
it('masks arbitaryDate3', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, arbitaryDate3, 'date-time', ts3)));
});
describe('default time', () => {
it('masks empty', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, '', 'time', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, null, 'time', '')));
// these tests are UTC => UTC
it('masks arbitaryDate1', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, arbitaryDate1, 'time', '16:27')));
it('masks arbitaryDate2', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, arbitaryDate2, 'time', '01:13')));
it('masks arbitaryDate3', inject([MaskService], (maskService: MaskService) => testDefaultMask(maskService, arbitaryDate3, 'time', '23:45')));
});
describe('custom date-time', () => {
beforeEach(inject([MaskService], (maskService: MaskService) => {
maskService.setDateMaskMapping('customdt', 'date-time', 'M DD YYYY hh-mm-ss', '+1000');
}));
it('masks empty', inject([MaskService], (maskService: MaskService) => testMask(maskService, '', 'customdt', 'date-time', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testMask(maskService, null, 'customdt', 'date-time', '')));
// these tests are locale specific UTC -> +1000
it('masks arbitaryDate1', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate1, 'customdt', 'date-time', '6 05 1985 02-27-10')));
it('masks arbitaryDate2', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate2, 'customdt', 'date-time', '2 20 2003 11-13-55')));
it('masks arbitaryDate3', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate3, 'customdt', 'date-time', '8 06 2016 09-45-08')));
});
describe('custom date', () => {
beforeEach(inject([MaskService], (maskService: MaskService) => {
maskService.setDateMaskMapping('customd', 'date', 'M DD YYYY', '+1100');
}));
it('masks empty', inject([MaskService], (maskService: MaskService) => testMask(maskService, '', 'customd', 'date', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testMask(maskService, null, 'customd', 'date', '')));
// these tests are locale specific UTC -> +1000
it('masks arbitaryDate1', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate1, 'customd', 'date', '6 05 1985')));
it('masks arbitaryDate2', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate2, 'customd', 'date', '2 20 2003')));
it('masks arbitaryDate3', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate3, 'customd', 'date', '8 06 2016')));
});
describe('custom time', () => {
beforeEach(inject([MaskService], (maskService: MaskService) => {
maskService.setDateMaskMapping('customt', 'time', 'hh-mm-ss', '+0030');
}));
it('masks empty', inject([MaskService], (maskService: MaskService) => testMask(maskService, '', 'customt', 'time', '')));
it('masks null', inject([MaskService], (maskService: MaskService) => testMask(maskService, null, 'customt', 'time', '')));
// these tests are UTC => UTC
it('masks arbitaryDate1', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate1, 'customt', 'time', '04-57-10')));
it('masks arbitaryDate2', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate2, 'customt', 'time', '01-43-55')));
it('masks arbitaryDate3', inject([MaskService], (maskService: MaskService) => testMask(maskService, arbitaryDate3, 'customt', 'time', '12-15-08')));
});
describe('Moment', () => {
function testFormat(toTest: string, valid: boolean, expected: Date) {
const m = moment(toTest, supportedDateFormats, 'en-GB', true);
expect(m.isValid()).toBe(valid);
if (valid) {
expect(m.toDate().toISOString()).toBe(expected.toISOString());
}
}
describe('test formats', () => {
it('formats', () => testFormat('1/1/2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('7/8/2016', true, new Date(2016, 7, 7)));
it('formats', () => testFormat('8/7/2016', true, new Date(2016, 6, 8)));
it('formats', () => testFormat('1/1/16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('7/8/16', true, new Date(2016, 7, 7)));
it('formats', () => testFormat('8/7/16', true, new Date(2016, 6, 8)));
it('formats', () => testFormat('01/01/16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('07/08/16', true, new Date(2016, 7, 7)));
it('formats', () => testFormat('08/07/16', true, new Date(2016, 6, 8)));
it('formats', () => testFormat('1 Jan 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 January 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 jan 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 january 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 JAN 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 JANUARY 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 Jan 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 January 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 jan 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 january 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 JAN 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 JANUARY 2016', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 Jan 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 January 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 jan 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 january 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 JAN 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('1 JANUARY 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 Jan 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 January 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 jan 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 january 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 JAN 16', true, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 JANUARY 16', true, new Date(2016, 0, 1)));
// not valid
it('formats', () => testFormat('01 Janua 16', false, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 janu 16', false, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 januar 16', false, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 JANUA 16', false, new Date(2016, 0, 1)));
it('formats', () => testFormat('01 JA 16', false, new Date(2016, 0, 1)));
});
});
}); | the_stack |
import { binToHex, hexToBin } from '../format/hex';
import {
bigIntToBinUint256BEClamped,
bigIntToBinUint64LE,
} from '../format/numbers';
import { deriveHdPrivateNodeFromSeed, encodeHdPrivateKey } from '../key/hd-key';
import {
Output,
TransactionContextCommon,
} from '../transaction/transaction-types';
import { CompilerDefaults } from './compiler-defaults';
import {
AnyCompilationEnvironmentIgnoreOperations,
CompilationData,
Scenario,
} from './compiler-types';
import { compileScriptRaw } from './language/compile';
import { CompilationError } from './language/language-types';
import { stringifyErrors } from './language/language-utils';
import {
AuthenticationTemplateKey,
AuthenticationTemplateScenario,
AuthenticationTemplateScenarioData,
AuthenticationTemplateScenarioOutput,
} from './template-types';
/**
* The contents of an `AuthenticationTemplateScenario` without the `name` and
* `description`.
*/
export type ScenarioDefinition = Pick<
AuthenticationTemplateScenario,
'data' | 'transaction' | 'value'
>;
type RequiredTwoLevels<T> = {
[P in keyof T]-?: Required<T[P]>;
};
/**
* All scenarios extend the default scenario, so the `data`, `transaction` (and
* all `transaction` properties), and `value` properties are guaranteed to be
* defined in an extended scenario definition.
*/
export type ExtendedScenarioDefinition = Required<
Pick<ScenarioDefinition, 'data'>
> &
RequiredTwoLevels<Pick<ScenarioDefinition, 'transaction'>> &
Required<Pick<ScenarioDefinition, 'value'>>;
/*
* & {
* value: Uint8Array;
* };
*/
/**
* Given a compilation environment, generate the default scenario which is
* extended by all the environments scenarios.
*
* For details on default scenario generation, see
* `AuthenticationTemplateScenario.extends`.
*
* @param environment - the compilation environment from which to generate the
* default scenario
*/
// eslint-disable-next-line complexity
export const generateDefaultScenarioDefinition = <
Environment extends AnyCompilationEnvironmentIgnoreOperations<
TransactionContext
>,
TransactionContext
>(
environment: Environment
): string | ExtendedScenarioDefinition => {
const { variables, entityOwnership } = environment;
const keyVariableIds =
variables === undefined
? []
: Object.entries(variables)
.filter(
(entry): entry is [string, AuthenticationTemplateKey] =>
entry[1].type === 'Key'
)
.map(([id]) => id);
const entityIds =
entityOwnership === undefined
? []
: Object.keys(
Object.values(entityOwnership).reduce(
(all, entityId) => ({ ...all, [entityId]: true }),
{}
)
);
const valueMap = [...keyVariableIds, ...entityIds]
.sort(([idA], [idB]) => idA.localeCompare(idB))
.reduce<{ [variableOrEntityId: string]: Uint8Array }>(
(all, id, index) => ({
...all,
[id]: bigIntToBinUint256BEClamped(BigInt(index + 1)),
}),
{}
);
const privateKeys =
variables === undefined
? undefined
: Object.entries(variables).reduce<{ [id: string]: string }>(
(all, [variableId, variable]) =>
variable.type === 'Key'
? {
...all,
[variableId]: binToHex(valueMap[variableId]),
}
: all,
{}
);
const defaultScenario: ExtendedScenarioDefinition = {
data: {
currentBlockHeight: CompilerDefaults.defaultScenarioCurrentBlockHeight as const,
currentBlockTime: CompilerDefaults.defaultScenarioCurrentBlockTime as const,
...(privateKeys === undefined || Object.keys(privateKeys).length === 0
? {}
: { keys: { privateKeys } }),
},
transaction: {
inputs: [{ unlockingBytecode: true }],
locktime: CompilerDefaults.defaultScenarioTransactionLocktime as const,
outputs: [
{
lockingBytecode: CompilerDefaults.defaultScenarioTransactionOutputsLockingBytecodeHex as const,
},
],
version: CompilerDefaults.defaultScenarioTransactionVersion as const,
},
value: CompilerDefaults.defaultScenarioValue as const,
};
const hasHdKeys =
variables === undefined
? false
: Object.values(variables).findIndex(
(variable) => variable.type === 'HdKey'
) !== -1;
if (!hasHdKeys) {
return defaultScenario;
}
const { sha256, sha512 } = environment;
if (sha256 === undefined) {
return 'An implementations of "sha256" is required to generate defaults for HD keys, but the "sha256" property is not included in this compilation environment.';
}
if (sha512 === undefined) {
return 'An implementations of "sha512" is required to generate defaults for HD keys, but the "sha512" property is not included in this compilation environment.';
}
const crypto = { sha256, sha512 };
const hdPrivateKeys = entityIds.reduce((all, entityId) => {
/**
* The first 5,000,000,000 seeds have been tested, scenarios are
* unlikely to exceed this number of entities.
*/
const assumeValid = true;
const masterNode = deriveHdPrivateNodeFromSeed(
crypto,
valueMap[entityId],
assumeValid
);
const hdPrivateKey = encodeHdPrivateKey(crypto, {
network: 'mainnet',
node: masterNode,
});
return { ...all, [entityId]: hdPrivateKey };
}, {});
return {
...defaultScenario,
data: {
...defaultScenario.data,
hdKeys: {
addressIndex: CompilerDefaults.defaultScenarioAddressIndex as const,
hdPrivateKeys,
},
},
};
};
/**
* Extend the `data` property of a scenario definition with values from a parent
* scenario definition. Returns the extended value for `data`.
*
* @param parentData - the scenario `data` which is extended by the child
* scenario
* @param childData - the scenario `data` which may override values from the
* parent scenario
*/
// eslint-disable-next-line complexity
export const extendScenarioDefinitionData = (
parentData: NonNullable<AuthenticationTemplateScenario['data']>,
childData: NonNullable<AuthenticationTemplateScenario['data']>
) => {
return {
...parentData,
...childData,
...(parentData.bytecode === undefined && childData.bytecode === undefined
? {}
: {
bytecode: {
...parentData.bytecode,
...childData.bytecode,
},
}),
...(parentData.hdKeys === undefined && childData.hdKeys === undefined
? {}
: {
hdKeys: {
...parentData.hdKeys,
...childData.hdKeys,
...(parentData.hdKeys?.hdPrivateKeys === undefined &&
childData.hdKeys?.hdPrivateKeys === undefined
? {}
: {
hdPrivateKeys: {
...parentData.hdKeys?.hdPrivateKeys,
...childData.hdKeys?.hdPrivateKeys,
},
}),
...(parentData.hdKeys?.hdPublicKeys === undefined &&
childData.hdKeys?.hdPublicKeys === undefined
? {}
: {
hdPublicKeys: {
...parentData.hdKeys?.hdPublicKeys,
...childData.hdKeys?.hdPublicKeys,
},
}),
},
}),
...(parentData.keys === undefined && childData.keys === undefined
? {}
: {
keys: {
privateKeys: {
...parentData.keys?.privateKeys,
...childData.keys?.privateKeys,
},
},
}),
};
};
/**
* Extend a child scenario definition with values from a parent scenario
* definition. Returns the extended values for `data`, `transaction`, and
* `value`.
*
* @param parentScenario - the scenario which is extended by the child scenario
* @param childScenario - the scenario which may override values from the parent
* scenario
*/
// eslint-disable-next-line complexity
export const extendScenarioDefinition = <
ParentScenarioType extends AuthenticationTemplateScenario
>(
parentScenario: ParentScenarioType,
childScenario: AuthenticationTemplateScenario
) => {
return {
...(parentScenario.data === undefined && childScenario.data === undefined
? {}
: {
data: extendScenarioDefinitionData(
parentScenario.data ?? {},
childScenario.data ?? {}
),
}),
...(parentScenario.transaction === undefined &&
childScenario.transaction === undefined
? {}
: {
transaction: {
...parentScenario.transaction,
...childScenario.transaction,
},
}),
...(parentScenario.value === undefined && childScenario.value === undefined
? {}
: { value: childScenario.value ?? parentScenario.value }),
} as ParentScenarioType extends ExtendedScenarioDefinition
? ExtendedScenarioDefinition
: ScenarioDefinition;
};
/**
* Generate the full scenario which is extended by the provided scenario
* identifier. Scenarios for which `extends` is `undefined` extend the default
* scenario for the provided compilation environment.
*
* @param scenarioId - the identifier of the scenario for from which to select
* the extended scenario
* @param environment - the compilation environment from which to generate the
* extended scenario
* @param sourceScenarioIds - an array of scenario identifiers indicating the
* path taken to arrive at the current scenario - used to detect and prevent
* cycles in extending scenarios (defaults to `[]`)
*/
// eslint-disable-next-line complexity
export const generateExtendedScenario = <
Environment extends AnyCompilationEnvironmentIgnoreOperations<
TransactionContext
>,
TransactionContext
>({
environment,
scenarioId,
sourceScenarioIds = [],
}: {
environment: Environment;
scenarioId?: string;
sourceScenarioIds?: string[];
}): string | ExtendedScenarioDefinition => {
if (scenarioId === undefined) {
return generateDefaultScenarioDefinition<Environment, TransactionContext>(
environment
);
}
if (sourceScenarioIds.includes(scenarioId)) {
return `Cannot extend scenario "${scenarioId}": scenario "${scenarioId}" extends itself. Scenario inheritance path: ${sourceScenarioIds.join(
' → '
)}`;
}
const scenario = environment.scenarios?.[scenarioId];
if (scenario === undefined) {
return `Cannot extend scenario "${scenarioId}": a scenario with the identifier ${scenarioId} is not included in this compilation environment.`;
}
const parentScenario =
scenario.extends === undefined
? generateDefaultScenarioDefinition<Environment, TransactionContext>(
environment
)
: generateExtendedScenario<Environment, TransactionContext>({
environment,
scenarioId: scenario.extends,
sourceScenarioIds: [...sourceScenarioIds, scenarioId],
});
if (typeof parentScenario === 'string') {
return parentScenario;
}
return extendScenarioDefinition(parentScenario, scenario);
};
/**
* Derive standard `CompilationData` properties from an extended scenario
* definition.
* @param definition - a scenario definition which has been extended by the
* default scenario definition
*/
// eslint-disable-next-line complexity
export const extendedScenarioDefinitionToCompilationData = (
definition: ScenarioDefinition & Required<Pick<ScenarioDefinition, 'data'>>
): CompilationData => ({
...(definition.data.currentBlockHeight === undefined
? {}
: {
currentBlockHeight: definition.data.currentBlockHeight,
}),
...(definition.data.currentBlockTime === undefined
? {}
: {
currentBlockTime: definition.data.currentBlockTime,
}),
...(definition.data.hdKeys === undefined
? {}
: {
hdKeys: {
...(definition.data.hdKeys.addressIndex === undefined
? {}
: {
addressIndex: definition.data.hdKeys.addressIndex,
}),
...(definition.data.hdKeys.hdPrivateKeys !== undefined &&
Object.keys(definition.data.hdKeys.hdPrivateKeys).length > 0
? {
hdPrivateKeys: definition.data.hdKeys.hdPrivateKeys,
}
: {}),
...(definition.data.hdKeys.hdPublicKeys === undefined
? {}
: {
hdPublicKeys: definition.data.hdKeys.hdPublicKeys,
}),
},
}),
...(definition.data.keys?.privateKeys !== undefined &&
Object.keys(definition.data.keys.privateKeys).length > 0
? {
keys: {
privateKeys: Object.entries(definition.data.keys.privateKeys).reduce(
(all, [id, hex]) => ({ ...all, [id]: hexToBin(hex) }),
{}
),
},
}
: {}),
});
/**
* Extend a `CompilationData` object with the compiled result of the bytecode
* scripts provided by a `AuthenticationTemplateScenarioData`.
*
* @param compilationData - the compilation data to extend
* @param environment - the compilation environment in which to compile the
* scripts
* @param scenarioDataBytecodeScripts - the `data.bytecode` property of an
* `AuthenticationTemplateScenarioData`
*/
export const extendCompilationDataWithScenarioBytecode = <
Environment extends AnyCompilationEnvironmentIgnoreOperations<
TransactionContext
>,
TransactionContext
>({
compilationData,
environment,
scenarioDataBytecodeScripts,
}: {
compilationData: CompilationData<TransactionContext>;
environment: Environment;
scenarioDataBytecodeScripts: NonNullable<
AuthenticationTemplateScenarioData['bytecode']
>;
}) => {
const prefixBytecodeScriptId = (id: string) =>
`${CompilerDefaults.scenarioBytecodeScriptPrefix}${id}`;
const bytecodeScripts = Object.entries(scenarioDataBytecodeScripts).reduce<{
[bytecodeScriptIdentifier: string]: string;
}>((all, [id, script]) => {
return {
...all,
[prefixBytecodeScriptId(id)]: script,
};
}, {});
const bytecodeScriptExtendedEnvironment: Environment = {
...environment,
scripts: {
...environment.scripts,
...bytecodeScripts,
},
};
const bytecodeCompilations: (
| {
bytecode: Uint8Array;
id: string;
}
| {
errors: [CompilationError] | CompilationError[];
id: string;
}
)[] = Object.keys(scenarioDataBytecodeScripts).map((id) => {
const result = compileScriptRaw({
data: compilationData,
environment: bytecodeScriptExtendedEnvironment,
scriptId: prefixBytecodeScriptId(id),
});
if (result.success) {
return {
bytecode: result.bytecode,
id,
};
}
return {
errors: result.errors,
id,
};
});
const failedResults = bytecodeCompilations.filter(
(
result
): result is {
errors: [CompilationError] | CompilationError[];
id: string;
} => 'errors' in result
);
if (failedResults.length > 0) {
return `${failedResults
.map(
(result) =>
`Compilation error while generating bytecode for "${
result.id
}": ${stringifyErrors(result.errors)}`
)
.join('; ')}`;
}
const compiledBytecode = (bytecodeCompilations as {
bytecode: Uint8Array;
id: string;
}[]).reduce<{
[fullIdentifier: string]: Uint8Array;
}>((all, result) => ({ ...all, [result.id]: result.bytecode }), {});
return {
...(Object.keys(compiledBytecode).length > 0
? { bytecode: compiledBytecode }
: {}),
...compilationData,
} as CompilationData<TransactionContext>;
};
/**
* The default `lockingBytecode` value for scenario outputs is a new empty
* object (`{}`).
*/
const getScenarioOutputDefaultLockingBytecode = () => ({});
/**
* Generate a scenario given a compilation environment. If neither `scenarioId`
* or `unlockingScriptId` are provided, the default scenario for the compilation
* environment will be generated.
*
* Returns either the full `CompilationData` for the selected scenario or an
* error message (as a `string`).
*
* @param scenarioId - the ID of the scenario to generate – if `undefined`, the
* default scenario
* @param unlockingScriptId - the ID of the unlocking script under test by this
* scenario – if `undefined` but required by the scenario, an error will be
* produced
* @param environment - the compilation environment from which to generate the
* scenario
*/
// eslint-disable-next-line complexity
export const generateScenarioCommon = <
Environment extends AnyCompilationEnvironmentIgnoreOperations
>({
environment,
scenarioId,
unlockingScriptId,
}: {
environment: Environment;
scenarioId?: string;
unlockingScriptId?: string;
}): Scenario | string => {
const { scenario, scenarioName } =
scenarioId === undefined
? { scenario: {}, scenarioName: `the default scenario` }
: {
scenario: environment.scenarios?.[scenarioId],
scenarioName: `scenario "${scenarioId}"`,
};
if (scenario === undefined) {
return `Cannot generate ${scenarioName}: a scenario with the identifier ${
scenarioId as string
} is not included in this compilation environment.`;
}
const parentScenario = generateExtendedScenario<
Environment,
TransactionContextCommon
>({ environment, scenarioId });
if (typeof parentScenario === 'string') {
return `Cannot generate ${scenarioName}: ${parentScenario}`;
}
const extendedScenario = extendScenarioDefinition(parentScenario, scenario);
const partialCompilationData = extendedScenarioDefinitionToCompilationData(
extendedScenario
);
const fullCompilationData = extendCompilationDataWithScenarioBytecode({
compilationData: partialCompilationData,
environment,
scenarioDataBytecodeScripts: extendedScenario.data.bytecode ?? {},
});
if (typeof fullCompilationData === 'string') {
return `Cannot generate ${scenarioName}: ${fullCompilationData}`;
}
const testedInputs = extendedScenario.transaction.inputs.filter(
(input) => input.unlockingBytecode === true
);
if (testedInputs.length !== 1) {
return `Cannot generate ${scenarioName}: the specific input under test in this scenario is ambiguous – "transaction.inputs" must include exactly one input which has "unlockingBytecode" set to "true".`;
}
const testedInputIndex = extendedScenario.transaction.inputs.findIndex(
(input) => input.unlockingBytecode
);
const outputs = extendedScenario.transaction.outputs.map<
Required<AuthenticationTemplateScenarioOutput>
>((output) => ({
lockingBytecode:
output.lockingBytecode ?? getScenarioOutputDefaultLockingBytecode(),
satoshis: output.satoshis ?? CompilerDefaults.defaultScenarioOutputSatoshis,
}));
const compiledOutputResults = outputs.map<string | Output>(
// eslint-disable-next-line complexity
(output, index) => {
const satoshis =
typeof output.satoshis === 'string'
? hexToBin(output.satoshis)
: bigIntToBinUint64LE(BigInt(output.satoshis));
if (typeof output.lockingBytecode === 'string') {
return {
lockingBytecode: hexToBin(output.lockingBytecode),
satoshis,
};
}
const specifiedLockingScriptId = output.lockingBytecode.script;
const impliedLockingScriptId =
unlockingScriptId === undefined
? undefined
: environment.unlockingScripts?.[unlockingScriptId];
const scriptId =
typeof specifiedLockingScriptId === 'string'
? specifiedLockingScriptId
: impliedLockingScriptId;
if (scriptId === undefined) {
if (unlockingScriptId === undefined) {
return `Cannot generate locking bytecode for output ${index}: this output is set to use the script unlocked by the unlocking script under test, but an unlocking script ID was not provided for scenario generation.`;
}
return `Cannot generate locking bytecode for output ${index}: the locking script unlocked by "${unlockingScriptId}" is not provided in this compilation environment.`;
}
const overriddenDataDefinition =
output.lockingBytecode.overrides === undefined
? undefined
: extendScenarioDefinitionData(
extendedScenario.data,
output.lockingBytecode.overrides
);
const overriddenCompilationData =
overriddenDataDefinition === undefined
? undefined
: extendCompilationDataWithScenarioBytecode({
compilationData: extendedScenarioDefinitionToCompilationData({
data: overriddenDataDefinition,
}),
environment,
scenarioDataBytecodeScripts:
overriddenDataDefinition.bytecode ?? {},
});
if (typeof overriddenCompilationData === 'string') {
return `Cannot generate locking bytecode for output ${index}: ${overriddenCompilationData}`;
}
const data =
overriddenCompilationData === undefined
? fullCompilationData
: overriddenCompilationData;
const result = compileScriptRaw({ data, environment, scriptId });
if (!result.success) {
return `Cannot generate locking bytecode for output ${index}: ${stringifyErrors(
result.errors
)}`;
}
return { lockingBytecode: result.bytecode, satoshis };
}
);
const outputCompilationErrors = compiledOutputResults.filter(
(result): result is string => typeof result === 'string'
);
if (outputCompilationErrors.length > 0) {
return `Cannot generate ${scenarioName}: ${outputCompilationErrors.join(
'; '
)}`;
}
const compiledOutputs = compiledOutputResults as Output[];
const sourceSatoshis =
typeof extendedScenario.value === 'number'
? bigIntToBinUint64LE(BigInt(extendedScenario.value))
: hexToBin(extendedScenario.value);
return {
data: fullCompilationData,
program: {
inputIndex: testedInputIndex,
sourceOutput: { satoshis: sourceSatoshis },
spendingTransaction: {
inputs: extendedScenario.transaction.inputs.map((input) => ({
outpointIndex:
input.outpointIndex ??
CompilerDefaults.defaultScenarioInputOutpointIndex,
outpointTransactionHash: hexToBin(
input.outpointTransactionHash ??
CompilerDefaults.defaultScenarioInputOutpointTransactionHash
),
sequenceNumber:
input.sequenceNumber ??
CompilerDefaults.defaultScenarioInputSequenceNumber,
unlockingBytecode: hexToBin(
typeof input.unlockingBytecode === 'string'
? input.unlockingBytecode
: CompilerDefaults.defaultScenarioInputUnlockingBytecodeHex
),
})),
locktime: extendedScenario.transaction.locktime,
outputs: compiledOutputs,
version: extendedScenario.transaction.version,
},
},
};
}; | the_stack |
import classNames from 'classnames';
import * as React from 'react';
import ReactTable, { ComponentPropsGetterC, TableCellRenderer } from 'react-table';
import 'react-table/react-table.css';
import './Table.css';
import { throttle } from '../../util/AsyncUtils/AsyncUtils';
import { identity, isEqual } from '../../util/FunctionalUtils/FunctionalUtils';
import { DetailRow } from './DetailRow/DetailRow';
import { Expander } from './Expander';
import { Pagination, ZeroIndexedNumber } from './Pagination/Pagination';
import {
getColumnId,
transformConfig,
} from './config';
import {
DEFAULT_COLUMN_WEIGHT,
DEFAULT_EXPANDER_WIDTH,
DEFAULT_MIN_COLUMN_WIDTH,
DEFAULT_MIN_TABLE_WIDTH,
DEFAULT_PAGE_SIZE,
DEFAULT_RESIZE_HANDLE_THROTTLE,
} from './constants';
import {
ColumnAlignment,
IActionInfo,
IAdditionalRowConfig,
IColumnConfig,
IGetRowState,
IRowsConfig,
IRowConfig,
IRowInfo,
} from './interfaces';
import { CellType } from './Cell';
import { FooterType } from './Footer';
import { NoData } from './NoData/NoData';
export type { IActionInfo, IColumnConfig, IRowConfig, IRowsConfig, IAdditionalRowConfig };
export { CellType, FooterType };
export { ColumnAlignment };
export { mergeConfigs } from './config';
// tslint:disable:line interface-over-type-literal
type ExpandDescriptor = { [key: string]: string | ExpandDescriptor };
interface ITableState<T> {
columns: IRowConfig<T>;
foldedColumns: IRowConfig<T>;
expanded: ExpandDescriptor;
page?: number;
perPage?: number;
}
interface ITableProps<T> {
ExtraComponent?: React.ComponentType<T>;
BeforePaginationComponent?: React.ComponentType<{}>;
Expander?: TableCellRenderer;
expanderWidth?: number;
columns: IRowConfig<T>;
data: T[];
foldableColumns?: boolean;
getTheadThProps?: ComponentPropsGetterC;
minWidth?: number;
pagination?: boolean;
page?: number;
pages?: number;
perPage?: number;
totalCount?: number;
getRowState?: IGetRowState<T>;
containerClass?: string;
noDataContent?: string;
automaticPagination?: boolean;
onPageChange?(index: number): void;
onPageSizeChange?(size: number): void;
}
export class Table<T> extends React.Component<ITableProps<T>, ITableState<T>> {
public static defaultProps = {
foldableColumns: false,
minWidth: DEFAULT_MIN_TABLE_WIDTH,
page: 1,
pages: 1,
pagination: false,
perPage: 20,
};
state = {
columns: this.props.columns,
expanded: {},
foldedColumns: [],
page: this.props.page ? this.props.page - 1 : 0,
perPage: this.props.perPage ? this.props.perPage : DEFAULT_PAGE_SIZE,
};
private divRef: HTMLDivElement | null = null;
private onResize = throttle(() => this.calculateFoldedColumns(), DEFAULT_RESIZE_HANDLE_THROTTLE);
private get rowCount(): number {
return this.props.data ? this.props.data.length : 0;
}
private get pages(): number {
return this.props.automaticPagination
? Math.max(1, Math.ceil(this.props.data.length / this.perPage))
: this.props.pages!;
}
private get page(): number {
if (this.props.automaticPagination) {
return this.state.page;
}
if (this.props.pagination) {
return this.props.page || 0; // react tables pages start from 0
}
return 0;
}
private get perPage(): number {
if (this.props.automaticPagination) {
return this.state.perPage;
}
if (this.props.pagination) {
return this.props.perPage || DEFAULT_PAGE_SIZE;
}
return this.rowCount;
}
componentDidMount() {
window.addEventListener('resize', this.onResize, false);
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
}
componentWillReceiveProps(nextProps: ITableProps<T>) {
let newState = {};
if (
(this.props.data !== nextProps.data) ||
(this.state.columns !== nextProps.columns)
) {
newState = {
...newState,
columns: nextProps.columns,
expanded: {},
};
}
if (nextProps.automaticPagination) {
if (this.props.page !== nextProps.page) {
this.setState({ page: nextProps.page! - 1 || 0 });
}
if (this.props.perPage !== nextProps.perPage) {
this.setState({ perPage: nextProps.perPage || DEFAULT_PAGE_SIZE });
}
if (this.props.data !== nextProps.data) {
this.setState({ page: 0 });
}
}
if (Object.keys(newState).length > 0) {
const collapseExpanders = this.props.data !== nextProps.data;
this.setState(newState, () => {
this.calculateFoldedColumns(collapseExpanders);
});
}
}
public render() {
const { expanded } = this.state;
const data = this.props.data || [];
const cssClasses = classNames(this.props.containerClass, 'TableContainer');
return (
<div ref={this.onTableDivRef} style={{ minWidth: this.props.minWidth, }} className={cssClasses}>
<ReactTable
NoDataComponent={this.constructNoDataComponent}
LoadingComponent={() => null} /* circumvent the react-table always loading bug */
data={data}
showPagination={this.props.pagination}
page={this.page}
pageSize={this.perPage}
pages={this.pages}
onExpandedChange={this.onExpanded}
onPageChange={this.onPageChange}
onPageSizeChange={this.onPageSizeChange}
onFilteredChange={this.onFilteredChange}
expanded={expanded}
resizable={false}
expanderDefaults={{
filterable: false,
resizable: false,
sortable: false,
width: this.props.expanderWidth || DEFAULT_EXPANDER_WIDTH,
}}
columns={this.getColumnsConfig()}
getTrGroupProps={this.getRowState as any}
sortable={false}
minRows={0}
defaultPageSize={this.perPage}
className='' // '-striped -highlight'
SubComponent={this.getSubComponent() ?? undefined}
manual={!this.props.automaticPagination}
PaginationComponent={this.renderPagination}
getTheadThProps={this.props.getTheadThProps}
/>
</div>
);
}
private renderPagination = (props: any) => {
const { data, BeforePaginationComponent, totalCount } = this.props;
return BeforePaginationComponent ? (
<React.Fragment>
{ data && data.length > 0 ? <BeforePaginationComponent /> : null}
<Pagination {...props} totalCount={totalCount} />
</React.Fragment>
) : (
<Pagination {...props} totalCount={totalCount} />
);
}
// #TODO @bigd -> type me !!1!
// Find a way to get internal table state typed and passed to first arg here
private getRowState = (tableState: any, rowInfo: IRowInfo<T>) => {
return {
className: classNames(
this.canExpand() && rowInfo && tableState.expanded[rowInfo.viewIndex] ? '-expanded' : '',
this.props.getRowState && this.props.getRowState(rowInfo),
),
};
}
private getSubComponent = () => {
if (this.canExpand()) {
return (d: IRowInfo<T>) => (
<DetailRow
data={d}
foldedColumns={this.state.foldedColumns}
ExtraComponent={this.props.ExtraComponent}
hasFoldedColumns={this.props.foldableColumns}
getRowState={this.props.getRowState}
/>
);
} else {
return null;
}
}
private canExpand = () => {
return this.state.foldedColumns.length || this.props.ExtraComponent;
}
private onExpanded = (expanded: ExpandDescriptor) => {
this.setState({ expanded });
}
private onPageChange = (index: ZeroIndexedNumber) => {
const page = Math.max(0, index);
if (this.props.onPageChange) {
this.props.onPageChange(page);
}
if (this.props.automaticPagination) {
this.setState({ page });
}
// clear the expanded flags index on page change
this.setState({ expanded: {} });
}
private onPageSizeChange = (size: ZeroIndexedNumber) => {
if (this.props.onPageSizeChange) {
this.props.onPageSizeChange(size);
}
if (this.props.automaticPagination) {
this.setState({ perPage: size, page: 0 });
}
// clear the expanded flags index on page size change
this.setState({ expanded: {} });
}
private onFilteredChange = () => {
// clear the expanded flags index on filtered change
this.setState({ expanded: {} });
}
private calculateFoldedColumns = (collapseExpanders = false) => {
if (this.divRef) {
const { foldableColumns } = this.props;
const width = this.divRef.offsetWidth;
let breakpointWidth = DEFAULT_EXPANDER_WIDTH;
const newFoldedColumns: IRowConfig<T> = foldableColumns
? this.state.columns
.map(identity) // because js sort is stupid and inplace
.sort((a: IColumnConfig<T>, b: IColumnConfig<T>) => (b.weight || DEFAULT_COLUMN_WEIGHT) - (a.weight || DEFAULT_COLUMN_WEIGHT))
.reduce((foldedColumns: IRowConfig<T>, column: IColumnConfig<T>) => {
breakpointWidth += (column.minWidth || DEFAULT_MIN_COLUMN_WIDTH);
if (breakpointWidth > width && foldedColumns.length < (this.state.columns.length - 1)) {
return [...foldedColumns, column];
} else {
return foldedColumns;
}
}, []) as IRowConfig<T>
: [];
if (!isEqual(this.state.foldedColumns.map(getColumnId), newFoldedColumns.map(getColumnId))) {
this.setState({
// collapse expanders if everything fits in the table and there is no extra else keep the state
expanded: (this.canExpand() && !collapseExpanders) ? this.state.expanded : {},
foldedColumns: newFoldedColumns,
});
}
}
}
private onTableDivRef = (div: HTMLDivElement | null) => {
this.divRef = div;
if (div !== null) {
this.calculateFoldedColumns();
}
}
private getColumnsConfig() {
const { columns, data } = this.props;
const { foldedColumns } = this.state;
const config = transformConfig(columns, data)
.map((column) => ({
...column,
show: !foldedColumns.map(getColumnId).includes(column.id),
}));
if (this.canExpand()) {
return config.concat([{ Expander: this.props.Expander || Expander, expander: true }]);
} else {
return config;
}
}
private constructNoDataComponent = () => {
return <NoData />;
}
} | the_stack |
import { ParameterDetails } from "../../models/parameterDetails";
import {
OperationDetails,
OperationRequestDetails
} from "../../models/operationDetails";
import {
ImplementationLocation,
SchemaType,
ParameterLocation,
Parameter
} from "@autorest/codemodel";
import { wrapString, IndentationType } from "./stringUtils";
import { ClassDeclaration, InterfaceDeclaration } from "ts-morph";
import { ParameterWithDescription } from "./docsUtils";
import {
NameType,
normalizeName,
normalizeTypeName
} from "../../utils/nameUtils";
import { getParameterDescription } from "../../utils/getParameterDescription";
import { getLanguageMetadata } from "../../utils/languageHelpers";
import { getAutorestOptions } from "../../autorestSession";
interface ParameterFilterOptions {
includeOptional?: boolean;
includeClientParams?: boolean;
includeUriParameters?: boolean;
includeGlobalParameters?: boolean;
includeConstantParameters?: boolean;
includeGroupedParameters?: boolean;
// Whether the contentType parameter should always be included.
includeContentType?: boolean;
}
/**
* Helper function to filter pre-processed parameters, to be used to find matching parameters
* within an operation
* @param parameters original list of parameters to filter
* @param operation operation to look up the parameter in
* @param param2 Object with filtering options
*/
export function filterOperationParameters(
parameters: ParameterDetails[],
operation: OperationDetails,
{
includeOptional,
includeClientParams,
includeGlobalParameters,
includeConstantParameters,
includeGroupedParameters,
includeContentType
}: ParameterFilterOptions = {}
) {
const isContentType = (param: ParameterDetails) =>
param.name === "contentType" && param.location === ParameterLocation.Header;
const optionalFilter = (param: ParameterDetails) =>
!!(includeOptional || param.required);
const constantFilter = (param: ParameterDetails) =>
(includeContentType && isContentType(param)) ||
!!(includeConstantParameters || param.schemaType !== SchemaType.Constant);
const clientParamFilter = (param: ParameterDetails) =>
!!(
includeClientParams ||
param.implementationLocation !== ImplementationLocation.Client
);
const globalFilter = (param: ParameterDetails) =>
!!(includeGlobalParameters || !param.isGlobal);
const isInOperation = (param: ParameterDetails) =>
!!(param.operationsIn && param.operationsIn[operation.fullName]);
// We may want to filter out any parameter that is grouped by here.
// This is so that we can place the group parameter instead.
// We already have logic to group optional parameters
const groupedFilter = (param: ParameterDetails) =>
!!(includeGroupedParameters || !param.parameter.groupedBy);
return parameters.filter(
param =>
groupedFilter(param) &&
globalFilter(param) &&
isInOperation(param) &&
optionalFilter(param) &&
constantFilter(param) &&
clientParamFilter(param)
);
}
export function formatJsDocParam(parameters: Partial<ParameterDetails>[]) {
return parameters.map(p =>
wrapString(`@param ${p.name} ${p.description}`, {
indentationType: IndentationType.JSDocParam,
paramNameLength: p.name?.length
})
);
}
/**
* Gets a list of parameter declarations for each overload the operation supports,
* and the list of parameter declarations for the base operation.
*/
export function getOperationParameterSignatures(
operation: OperationDetails,
parameters: ParameterDetails[],
importedModels: Set<string>,
operationGroupClass: ClassDeclaration | InterfaceDeclaration
) {
const operationParameters = filterOperationParameters(parameters, operation, {
includeContentType: true
}).filter(p => !p.isFlattened);
const operationRequests = operation.requests;
const overloadParameterDeclarations: ParameterWithDescription[][] = [];
const hasMultipleOverloads = operationRequests.length > 1;
for (const request of operationRequests) {
const requestMediaType = request.mediaType;
// filter out parameters that belong to a different media type
const requestParameters = operationParameters.filter(
({ targetMediaType }) =>
!targetMediaType || requestMediaType === targetMediaType
);
// Convert parameters into TypeScript parameter declarations.
const parameterDeclarations = requestParameters.reduce<
ParameterWithDescription[]
>((acc, param) => {
const { usedModels } = param.typeDetails;
let type = normalizeTypeName(param.typeDetails);
if (
param.typeDetails.isConstant &&
param.typeDetails.typeName === "string" &&
param.typeDetails.defaultValue
) {
type = `"${param.typeDetails.defaultValue}"`;
}
// If the type collides with the class name, use the alias
const uniqueTypeName =
operationGroupClass.getName() === type ? `${type}Model` : type;
const typeName = param.nullable
? uniqueTypeName + " | null"
: uniqueTypeName;
// If any models are used, add them to the named import list
if (usedModels.length) {
usedModels.forEach(model => importedModels.add(model));
}
const newParameter = {
name: param.name,
description: getParameterDescription(param, operation.fullName),
type: typeName,
hasQuestionToken: !param.required,
isContentType: Boolean(
param.serializedName === "Content-Type" && param.location === "header"
)
};
// Make sure required parameters are added before optional
const newParameterPosition = param.required
? findLastRequiredParamIndex(acc) + 1
: acc.length;
acc.splice(newParameterPosition, 0, newParameter);
return acc;
}, []);
trackParameterGroups(
operation,
parameters,
importedModels,
parameterDeclarations
);
// Sort the parameter declarations to match the signature the CodeModel suggests.
const orderedParameterDeclarations = sortOperationParameters(
operation,
request,
parameterDeclarations
);
// add optional parameter
const optionalParameter = getOptionsParameter(
operation,
parameters,
importedModels,
{
mediaType: hasMultipleOverloads ? requestMediaType : undefined
}
);
orderedParameterDeclarations.push(optionalParameter);
overloadParameterDeclarations.push(orderedParameterDeclarations);
}
// Create the parameter declarations for the base method signature.
const baseMethodParameters = getBaseMethodParameterDeclarations(
overloadParameterDeclarations
);
return { overloadParameterDeclarations, baseMethodParameters };
}
function findLastRequiredParamIndex(
params: ParameterWithDescription[]
): number {
for (let i = params.length; i--; ) {
if (!params[i].hasQuestionToken) {
return i;
}
}
return -1;
}
function trackParameterGroups(
operation: OperationDetails,
parameters: ParameterDetails[],
importedModels: Set<string>,
parameterDeclarations: ParameterWithDescription[]
) {
const groupedParameters = getGroupedParameters(
operation,
parameters,
importedModels
).filter(gp => !gp.hasQuestionToken);
// Make sure required parameters are added before optional
const lastRequiredIndex =
findLastRequiredParamIndex(parameterDeclarations) + 1;
if (groupedParameters.length) {
parameterDeclarations.splice(lastRequiredIndex, 0, ...groupedParameters);
}
}
/**
* This function gets the parameter groups specified in the swagger
* by the parameter grouping extension x-ms-parameter-grouping
*/
function getGroupedParameters(
operation: OperationDetails,
parameters: ParameterDetails[],
importedModels: Set<string>
): ParameterWithDescription[] {
const parameterGroups: Parameter[] = [];
// We get the parameters that are used by this specific operation, including
// any optional ones.
// We extract these from the parameters collection to make sure we reuse them
// when needed, instead of creating duplicate ones.
filterOperationParameters(parameters, operation, {
includeGroupedParameters: true
})
.filter(({ parameter }) => parameter.groupedBy)
// Get optional grouped properties and store them in parameterGroups
.forEach(({ parameter: { groupedBy } }) => {
if (!groupedBy || !groupedBy.required) {
return;
}
const groupNAme = getLanguageMetadata(groupedBy.language).name;
// Make sure we only store the same group once
if (
parameterGroups.some(
p => getLanguageMetadata(p.language).name === groupNAme
)
) {
return;
}
parameterGroups.push(groupedBy);
});
return parameterGroups
.filter(({ required }) => required)
.map(({ language }) => {
const { name, description } = getLanguageMetadata(language);
const type = normalizeName(name, NameType.Interface);
// Add the model for import
importedModels.add(type);
return {
name,
type,
description
};
});
}
/**
* Sorts the list of operation parameters to match the order described by the CodeModel.
* @param operation Details about an operation.
* @param request Details about an operation overload.
* @param parameterDeclarations List of required parameter declarations for the provided operation overload.
*/
function sortOperationParameters(
operation: OperationDetails,
request: OperationRequestDetails,
parameterDeclarations: ParameterWithDescription[]
): ParameterWithDescription[] {
// Get a sorted list of parameter names for this operation/request.
// Note that this may inlcude parameters that aren't displayed, e.g. constant types.
const expectedParameterOrdering = [
...operation.parameters,
...(request.parameters ?? [])
]
// Only parameters that are implemented on the method should be considered.
.filter(param => param.implementation === ImplementationLocation.Method)
.map(param => getLanguageMetadata(param.language).name);
const orderedParameterDeclarations: typeof parameterDeclarations = [];
for (const parameterName of expectedParameterOrdering) {
const index = parameterDeclarations.findIndex(
p => p.name === parameterName
);
if (index === -1) {
// No matching parameter found.
// Common cases where this occurs is if a parameter
// is optional, or a constant.
continue;
}
orderedParameterDeclarations.push(
...parameterDeclarations.splice(index, 1)
);
}
// push any remaining parameters into the ordered parameter list
orderedParameterDeclarations.push(...parameterDeclarations);
return orderedParameterDeclarations;
}
/**
* This function takes care of Typescript generator specific Optional parameters grouping.
*
* In the Typescript generator we always group optional parameters to provide a simpler interface.
* This function is responsible for the default optional parameter grouping, which groups into an
* options bag any optional parameter, including optional grouped parameters.
*/
function getOptionsParameter(
operation: OperationDetails,
parameters: ParameterDetails[],
importedModels: Set<string>,
{
isOptional = true,
mediaType
}: { isOptional?: boolean; mediaType?: string } = {}
): ParameterWithDescription {
const { useCoreV2 } = getAutorestOptions();
let type: string = !useCoreV2
? "coreHttp.OperationOptions"
: "coreClient.OperationOptions";
const operationParameters = filterOperationParameters(parameters, operation, {
includeOptional: true,
includeGroupedParameters: true
});
const mediaPrefix = mediaType ? `$${mediaType}` : "";
type = `${operation.typeDetails.typeName}${mediaPrefix}OptionalParams`;
importedModels.add(type);
return {
name: "options",
type,
hasQuestionToken: isOptional,
description: "The options parameters."
};
}
/**
* Given a list of operation parameter declarations per overload,
* returns a list of the parameter declarations that should appear
* in the operation's base signature.
*
* If `overloadParameterDeclarations` contains the parameter declarations for
* just a single overload, then the return value will be the same as the 1st
* element in `overloadParameterDeclarations`.
* @param overloadParameterDeclarations
*/
function getBaseMethodParameterDeclarations(
overloadParameterDeclarations: ParameterWithDescription[][]
): ParameterWithDescription[] {
if (!overloadParameterDeclarations.length) {
return [];
}
if (overloadParameterDeclarations.length === 1) {
return [...overloadParameterDeclarations[0]];
}
const baseMethodArg: ParameterWithDescription = {
name: "args",
isRestParameter: true,
description: "Includes all the parameters for this operation.",
type: overloadParameterDeclarations
.map(overloadParams => {
return `[ ${overloadParams
.map(p => (p.hasQuestionToken ? `${p.type}?` : p.type))
.join(", ")} ]`;
})
.join(" | ")
};
return [baseMethodArg];
} | the_stack |
var util = require('util')
, EventEmitter = require('events')
// Userland modules
, async = require('async')
, _ = require('underscore')
// Local modules
, customUtils = require('./customUtils')
, model = require('./model')
, Executor = require('./executor')
, Index = require('./indexes')
, Persistence = require('./persistence')
, Cursor = require('./cursor')
;
/**
* Create a new collection
*
* @param {String} options.filename Optional, datastore will be in-memory only if not provided
* @param {Boolean} options.timestampData Optional, defaults to false. If set to true, createdAt and updatedAt will be created and populated automatically (if not specified by user)
* @param {Boolean} options.inMemoryOnly Optional, defaults to false
* @param {Boolean} options.autoload Optional, defaults to false
* @param {Function} options.onload Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown
* @param {Function} options.idGenerator Optional, if set, this function will be used for generating IDs. It takes no arguments and should return a unique string.
* @param {Function} options.afterSerialization Optional, serialization hook. Must be symmetrical to `options.beforeDeserialization`.
* @param {Function} options.beforeDeserialization Optional, deserialization hook. Must be symmetrical to options.afterSerialization`.
* @param {Number} options.corruptAlertThreshold Optional, threshold after which an alert is thrown if too much data is corrupt
* @param {Function} options.compareStrings Optional, string comparison function that overrides default for sorting
* @param {Object} options.storage Optional, custom storage engine for the database files. Must implement all methods exported by the standard "storage" module included in NestDB
*
* @fires Datastore.created
* @fires Datastore#loaded
* @fires Datastore#compacted
* @fires Datastore#inserted
* @fires Datastore#updated
* @fires Datastore#removed
* @fires Datastore#destroyed
* @fires Datastore.destroyed
*
* Event Emitter
* - Static Events
* - "created": Emitted whenever a Datastore is fully loaded OR newly created
* - callback: function(db) { ... }
* - context: Datastore
* - "destroyed": Emitted whenever a Datastore is fully destroyed
* - callback: function(db) { ... }
* - context: Datastore
*
* - Instance Events
* - "loaded": Emitted when this Datastore is fully loaded
* - callback: function() { ... }
* - context: this (a.k.a. `db`)
* - "compacted": Emitted whenever a compaction operation is completed for this Datastore
* - callback: function() { ... }
* - context: this (a.k.a. `db`)
* - "inserted": Emitted whenever a new document is inserted for this Datastore
* - callback: function(newDoc) { ... }
* - context: this (a.k.a. `db`)
* - "updated": Emitted whenever an existing document is updated for this Datastore
* - callback: function(newDoc, oldDoc) { ... }
* - context: this (a.k.a. `db`)
* - "removed": Emitted whenever an existing document is removed for this Datastore
* - callback: function(oldDoc) { ... }
* - context: this (a.k.a. `db`)
* - "destroyed": Emitted when this Datastore is fully destroyed
* - callback: function() { ... }
* - context: this (a.k.a. `db`)
*/
function Datastore(options) {
if (!(this instanceof Datastore)) {
return new Datastore(options);
}
EventEmitter.call(this);
options = options || {};
var filename = options.filename;
this.inMemoryOnly = options.inMemoryOnly || false;
this.autoload = options.autoload || false;
this.timestampData = options.timestampData || false;
if (typeof options.idGenerator === 'function') {
this._idGenerator = options.idGenerator;
}
// Determine whether in memory or persistent
if (!filename || typeof filename !== 'string' || filename.length === 0) {
this.filename = null;
this.inMemoryOnly = true;
} else {
this.filename = filename;
}
// String comparison function
this.compareStrings = options.compareStrings;
// Persistence handling
this.persistence = new Persistence({ db: this
, afterSerialization: options.afterSerialization
, beforeDeserialization: options.beforeDeserialization
, corruptAlertThreshold: options.corruptAlertThreshold
, storage: options.storage
});
// This new executor is ready if we don't use persistence
// If we do, it will only be ready once `load` is called
this.executor = new Executor();
if (this.inMemoryOnly) { this.executor.ready = true; }
// Indexed by field name, dot notation can be used
// _id is always indexed and since _ids are generated randomly the underlying
// binary is always well-balanced
this.indexes = {};
this.indexes._id = new Index({ fieldName: '_id', unique: true });
this.ttlIndexes = {};
// Queue a load of the database right away and call the onload handler
// By default (no onload handler), if there is an error there, no operation will be possible so warn the user by throwing an exception
if (this.autoload) {
this.load(options.onload);
}
}
util.inherits(Datastore, EventEmitter);
//
// Also forcibly alter the Datastore (NeDB) object itself to be a static EventEmitter
//
EventEmitter.call(Datastore);
Object.keys(EventEmitter.prototype)
.forEach(function (key) {
if (typeof EventEmitter.prototype[key] === 'function') {
Datastore[key] = EventEmitter.prototype[key].bind(Datastore);
}
});
/**
* Load the database from the datafile, and trigger the execution of buffered commands if any
*
* @fires Datastore.created
* @fires Datastore#loaded
* @fires Datastore#compacted
*/
Datastore.prototype.load = function (cb) {
var self = this
, callback = cb || function (err) { if (err) { throw err; } }
, eventedCallback = function (err) {
async.setImmediate(function () {
if (!err) {
// Ensure there are listeners registered before making any unnecessary function calls to `emit`
if (self.constructor.listeners('created').length > 0) {
self.constructor.emit('created', self);
}
if (self.listeners('loaded').length > 0) {
self.emit('loaded');
}
}
callback(err);
});
};
this.executor.push({ this: this.persistence, fn: this.persistence.loadDatabase, arguments: [eventedCallback] }, true);
};
/**
* Backward compatibility with NeDB
* @deprecated
*/
Datastore.prototype.loadDatabase = Datastore.prototype.load;
/**
* Get an array of all the data in the database
*/
Datastore.prototype.getAllData = function () {
return this.indexes._id.getAll();
};
/**
* Reset all currently defined indexes
*/
Datastore.prototype.resetIndexes = function (newData) {
var self = this;
Object.keys(this.indexes).forEach(function (i) {
self.indexes[i].reset(newData);
});
};
/**
* Ensure an index is kept for this field. Same parameters as lib/indexes
* For now this function is synchronous, we need to test how much time it takes
* We use an async API for consistency with the rest of the code
* @param {String} options.fieldName
* @param {Boolean} options.unique
* @param {Boolean} options.sparse
* @param {Number} options.expireAfterSeconds - Optional, if set this index becomes a TTL index (only works on Date fields, not arrays of Date)
* @param {Function} cb Optional callback, signature: err
*/
Datastore.prototype.ensureIndex = function (options, cb) {
var err
, callback = cb || function () {};
options = options || {};
if (!options.fieldName) {
err = new Error("Cannot create an index without a fieldName");
err.missingFieldName = true;
return callback(err);
}
if (this.indexes[options.fieldName]) { return callback(null); }
this.indexes[options.fieldName] = new Index(options);
if (options.expireAfterSeconds !== undefined) { this.ttlIndexes[options.fieldName] = options.expireAfterSeconds; } // With this implementation index creation is not necessary to ensure TTL but we stick with MongoDB's API here
try {
this.indexes[options.fieldName].insert(this.getAllData());
} catch (e) {
delete this.indexes[options.fieldName];
return callback(e);
}
// We may want to force all options to be persisted including defaults, not just the ones passed the index creation function
this.persistence.persistNewState([{ $$indexCreated: options }], function (err) {
if (err) { return callback(err); }
return callback(null);
});
};
/**
* Remove an index
* @param {String} fieldName
* @param {Function} cb Optional callback, signature: err
*/
Datastore.prototype.removeIndex = function (fieldName, cb) {
var callback = cb || function () {};
delete this.indexes[fieldName];
this.persistence.persistNewState([{ $$indexRemoved: fieldName }], function (err) {
if (err) { return callback(err); }
return callback(null);
});
};
/**
* Add one or several document(s) to all indexes
*/
Datastore.prototype.addToIndexes = function (doc) {
var i, failingIndex, error
, keys = Object.keys(this.indexes)
;
for (i = 0; i < keys.length; i += 1) {
try {
this.indexes[keys[i]].insert(doc);
} catch (e) {
failingIndex = i;
error = e;
break;
}
}
// If an error happened, we need to rollback the insert on all other indexes
if (error) {
for (i = 0; i < failingIndex; i += 1) {
this.indexes[keys[i]].remove(doc);
}
throw error;
}
};
/**
* Remove one or several document(s) from all indexes
*/
Datastore.prototype.removeFromIndexes = function (doc) {
var self = this;
Object.keys(this.indexes).forEach(function (i) {
self.indexes[i].remove(doc);
});
};
/**
* Update one or several documents in all indexes
* To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
* If one update violates a constraint, all changes are rolled back
*/
Datastore.prototype.updateIndexes = function (oldDoc, newDoc) {
var i, failingIndex, error
, keys = Object.keys(this.indexes)
;
for (i = 0; i < keys.length; i += 1) {
try {
this.indexes[keys[i]].update(oldDoc, newDoc);
} catch (e) {
failingIndex = i;
error = e;
break;
}
}
// If an error happened, we need to rollback the update on all other indexes
if (error) {
for (i = 0; i < failingIndex; i += 1) {
this.indexes[keys[i]].revertUpdate(oldDoc, newDoc);
}
throw error;
}
};
/**
* Return the list of candidates for a given query
* Crude implementation for now, we return the candidates given by the first usable index if any
* We try the following query types, in this order: basic match, $in match, comparison match
* One way to make it better would be to enable the use of multiple indexes if the first usable index
* returns too much data. I may do it in the future.
*
* Returned candidates will be scanned to find and remove all expired documents
*
* @param {Query} query
* @param {Boolean} dontExpireStaleDocs Optional, defaults to false, if true don't remove stale docs. Useful for the remove function which shouldn't be impacted by expirations
* @param {Function} callback Signature err, candidates
*/
Datastore.prototype.getCandidates = function (query, dontExpireStaleDocs, callback) {
var indexNames = Object.keys(this.indexes)
, self = this
, usableQueryKeys;
if (typeof dontExpireStaleDocs === 'function') {
callback = dontExpireStaleDocs;
dontExpireStaleDocs = false;
}
async.waterfall([
// STEP 1: get candidates list by checking indexes from most to least frequent usecase
function (cb) {
// For a basic match
usableQueryKeys = [];
Object.keys(query).forEach(function (k) {
if (typeof query[k] === 'string' || typeof query[k] === 'number' || typeof query[k] === 'boolean' || _.isDate(query[k]) || query[k] === null) {
usableQueryKeys.push(k);
}
});
usableQueryKeys = _.intersection(usableQueryKeys, indexNames);
if (usableQueryKeys.length > 0) {
return cb(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]]));
}
// For a $in match
usableQueryKeys = [];
Object.keys(query).forEach(function (k) {
if (query[k] && query[k].hasOwnProperty('$in')) {
usableQueryKeys.push(k);
}
});
usableQueryKeys = _.intersection(usableQueryKeys, indexNames);
if (usableQueryKeys.length > 0) {
return cb(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]].$in));
}
// For a comparison match
usableQueryKeys = [];
Object.keys(query).forEach(function (k) {
if (query[k] && (query[k].hasOwnProperty('$lt') || query[k].hasOwnProperty('$lte') || query[k].hasOwnProperty('$gt') || query[k].hasOwnProperty('$gte'))) {
usableQueryKeys.push(k);
}
});
usableQueryKeys = _.intersection(usableQueryKeys, indexNames);
if (usableQueryKeys.length > 0) {
return cb(null, self.indexes[usableQueryKeys[0]].getBetweenBounds(query[usableQueryKeys[0]]));
}
// By default, return all the DB data
return cb(null, self.getAllData());
}
// STEP 2: remove all expired documents
, function (docs) {
if (dontExpireStaleDocs) { return callback(null, docs); }
var expiredDocsIds = [], validDocs = [], ttlIndexesFieldNames = Object.keys(self.ttlIndexes);
docs.forEach(function (doc) {
var valid = true;
ttlIndexesFieldNames.forEach(function (i) {
if (doc[i] !== undefined && _.isDate(doc[i]) && Date.now() > doc[i].getTime() + self.ttlIndexes[i] * 1000) {
valid = false;
}
});
if (valid) { validDocs.push(doc); } else { expiredDocsIds.push(doc._id); }
});
async.eachSeries(expiredDocsIds, function (_id, cb) {
self._remove({ _id: _id }, {}, function (err) {
if (err) { return callback(err); }
return cb();
});
}, function (err) {
return callback(null, validDocs);
});
}]);
};
/**
* Insert a new document
*
* @private
* @see Datastore#insert
*/
Datastore.prototype._insert = function (newDoc, cb) {
var preparedDoc
, self = this
, origCallback = cb || function () {}
, callback = function (err, newDocs) {
var context = this
, args = arguments
;
async.setImmediate(function () {
if (!err) {
var newDocsArr = Array.isArray(newDocs) ? newDocs : [newDocs];
// Ensure there are listeners registered before making a bunch of unnecessary function calls to `emit`
if (self.listeners('inserted').length > 0) {
newDocsArr.forEach(function (newDoc) {
self.emit('inserted', newDoc);
});
}
}
origCallback.apply(context, args);
});
}
;
try {
preparedDoc = this.prepareDocumentForInsertion(newDoc)
this._insertInCache(preparedDoc);
} catch (e) {
return callback(e);
}
this.persistence.persistNewState(Array.isArray(preparedDoc) ? preparedDoc : [preparedDoc], function (err) {
if (err) { return callback(err); }
return callback(null, model.deepCopy(preparedDoc));
});
};
/**
* Default implementation for generating a unique _id
* @protected
*/
Datastore.prototype._idGenerator = function () {
return customUtils.uid(16);
};
/**
* Create a new _id that's not already in use
*/
Datastore.prototype.createNewId = function () {
var tentativeId;
// Try as many times as needed to get an unused _id. As explained in customUtils, the probability of this ever happening is extremely small, so this is O(1)
do {
tentativeId = this._idGenerator();
}
while (this.indexes._id.getMatching(tentativeId).length > 0);
return tentativeId;
};
/**
* Prepare a document (or array of documents) to be inserted in a database
* Meaning adds _id and timestamps if necessary on a copy of newDoc to avoid any side effect on user input
* @private
*/
Datastore.prototype.prepareDocumentForInsertion = function (newDoc) {
var preparedDoc, self = this;
if (Array.isArray(newDoc)) {
preparedDoc = [];
newDoc.forEach(function (doc) { preparedDoc.push(self.prepareDocumentForInsertion(doc)); });
} else {
preparedDoc = model.deepCopy(newDoc);
if (preparedDoc._id === undefined) { preparedDoc._id = this.createNewId(); }
var now = new Date();
if (this.timestampData && preparedDoc.createdAt === undefined) { preparedDoc.createdAt = now; }
if (this.timestampData && preparedDoc.updatedAt === undefined) { preparedDoc.updatedAt = now; }
model.checkObject(preparedDoc);
}
return preparedDoc;
};
/**
* If newDoc is an array of documents, this will insert all documents in the cache
* @private
*/
Datastore.prototype._insertInCache = function (preparedDoc) {
if (Array.isArray(preparedDoc)) {
this._insertMultipleDocsInCache(preparedDoc);
} else {
this.addToIndexes(preparedDoc);
}
};
/**
* If one insertion fails (e.g. because of a unique constraint), roll back all previous
* inserts and throws the error
* @private
*/
Datastore.prototype._insertMultipleDocsInCache = function (preparedDocs) {
var i, failingI, error;
for (i = 0; i < preparedDocs.length; i += 1) {
try {
this.addToIndexes(preparedDocs[i]);
} catch (e) {
error = e;
failingI = i;
break;
}
}
if (error) {
for (i = 0; i < failingI; i += 1) {
this.removeFromIndexes(preparedDocs[i]);
}
throw error;
}
};
/**
* Insert a new document
*
* @param {Object} newDoc New document to be inserted
* @param {Function} cb Optional callback, signature: err, insertedDoc
*
* @fires Datastore#inserted
*/
Datastore.prototype.insert = function () {
this.executor.push({ this: this, fn: this._insert, arguments: arguments });
};
/**
* Count all documents matching the query
* @param {Object} query MongoDB-style query
*/
Datastore.prototype.count = function(query, callback) {
var cursor = new Cursor(this, query, function(err, docs, callback) {
if (err) { return callback(err); }
return callback(null, docs.length);
});
if (typeof callback === 'function') {
cursor.exec(callback);
} else {
return cursor;
}
};
/**
* Find all documents matching the query
* If no callback is passed, we return the cursor so that user can limit, skip and finally exec
* @param {Object} query MongoDB-style query
* @param {Object} projection MongoDB-style projection
*/
Datastore.prototype.find = function (query, projection, callback) {
switch (arguments.length) {
case 1:
projection = {};
// callback is undefined, will return a cursor
break;
case 2:
if (typeof projection === 'function') {
callback = projection;
projection = {};
} // If not assume projection is an object and callback undefined
break;
}
var cursor = new Cursor(this, query, function(err, docs, callback) {
var res = [], i;
if (err) { return callback(err); }
for (i = 0; i < docs.length; i += 1) {
res.push(model.deepCopy(docs[i]));
}
return callback(null, res);
});
cursor.projection(projection);
if (typeof callback === 'function') {
cursor.exec(callback);
} else {
return cursor;
}
};
/**
* Find one document matching the query
* @param {Object} query MongoDB-style query
* @param {Object} projection MongoDB-style projection
*/
Datastore.prototype.findOne = function (query, projection, callback) {
switch (arguments.length) {
case 1:
projection = {};
// callback is undefined, will return a cursor
break;
case 2:
if (typeof projection === 'function') {
callback = projection;
projection = {};
} // If not assume projection is an object and callback undefined
break;
}
var cursor = new Cursor(this, query, function(err, docs, callback) {
if (err) { return callback(err); }
if (docs.length === 1) {
return callback(null, model.deepCopy(docs[0]));
} else {
return callback(null, null);
}
});
cursor.projection(projection).limit(1);
if (typeof callback === 'function') {
cursor.exec(callback);
} else {
return cursor;
}
};
/**
* Update all docs matching query
*
* @private
* @see Datastore#update
*/
Datastore.prototype._update = function (query, updateQuery, options, cb) {
var callback
, self = this
, numReplaced = 0
, multi
, upsert
, i
;
if (typeof options === 'function') { cb = options; options = {}; }
callback = cb || function () {};
multi = options.multi !== undefined ? options.multi : false;
upsert = options.upsert !== undefined ? options.upsert : false;
async.waterfall([
function (cb) { // If upsert option is set, check whether we need to insert the doc
if (!upsert) { return cb(); }
// Need to use an internal function not tied to the executor to avoid deadlock
var cursor = new Cursor(self, query);
cursor.limit(1)._exec(function (err, docs) {
if (err) { return callback(err); }
if (docs.length === 1) {
return cb();
} else {
var toBeInserted;
try {
model.checkObject(updateQuery);
// updateQuery is a simple object with no modifier, use it as the document to insert
toBeInserted = updateQuery;
} catch (e) {
// updateQuery contains modifiers, use the find query as the base,
// strip it from all operators and update it according to updateQuery
try {
toBeInserted = model.modify(model.deepCopy(query, true), updateQuery);
} catch (err) {
return callback(err);
}
}
return self._insert(toBeInserted, function (err, newDoc) {
if (err) { return callback(err); }
return callback(null, 1, newDoc, true);
});
}
});
}
, function () { // Perform the update
var modifiedDoc
, modifications = []
, createdAt
, eventedCallback = function(err /*, numReplaced, updatedDocs, upserted */) {
var context = this
, args = arguments
;
async.setImmediate(function () {
if (!err) {
if (modifications && modifications.length > 0) {
// Ensure there are listeners registered before making a bunch of unnecessary function calls to `emit`
if (self.listeners('updated').length > 0) {
modifications.forEach(function (mod) {
self.emit('updated', mod.newDoc, mod.oldDoc);
});
}
}
}
callback.apply(context, args);
});
}
;
self.getCandidates(query, function (err, candidates) {
if (err) { return eventedCallback(err); }
// Preparing update (if an error is thrown here neither the datafile nor
// the in-memory indexes are affected)
try {
for (i = 0; i < candidates.length; i += 1) {
if (model.match(candidates[i], query) && (multi || numReplaced === 0)) {
numReplaced += 1;
if (self.timestampData) { createdAt = candidates[i].createdAt; }
modifiedDoc = model.modify(candidates[i], updateQuery);
if (self.timestampData) {
modifiedDoc.createdAt = createdAt;
modifiedDoc.updatedAt = new Date();
}
modifications.push({ oldDoc: candidates[i], newDoc: modifiedDoc });
}
}
} catch (err) {
return eventedCallback(err);
}
// Change the docs in memory
try {
self.updateIndexes(modifications);
} catch (err) {
return eventedCallback(err);
}
// Update the datafile
var updatedDocs = _.pluck(modifications, 'newDoc');
self.persistence.persistNewState(updatedDocs, function (err) {
if (err) { return eventedCallback(err); }
if (!options.returnUpdatedDocs) {
return eventedCallback(null, numReplaced);
} else {
var updatedDocsDC = [];
updatedDocs.forEach(function (doc) { updatedDocsDC.push(model.deepCopy(doc)); });
if (!multi) { updatedDocsDC = updatedDocsDC[0]; }
return eventedCallback(null, numReplaced, updatedDocsDC);
}
});
});
}]);
};
/**
* Update all docs matching query
*
* @param {Object} query
* @param {Object} updateQuery
* @param {Object} options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* options.upsert If true, document is inserted if the query doesn't match anything
* options.returnUpdatedDocs Defaults to false, if true return as third argument the array of updated matched documents (even if no change actually took place)
* @param {Function} cb Optional callback, signature: (err, numAffected, affectedDocuments, upsert)
* If update was an upsert, upsert flag is set to `true`
* affectedDocuments can be one of the following:
* * For an upsert, the upserted document
* * For an update with returnUpdatedDocs option false, null
* * For an update with returnUpdatedDocs true and multi false, the updated document
* * For an update with returnUpdatedDocs true and multi true, the array of updated documents
*
* @fires Datastore#updated
* @fires Datastore#inserted
*/
Datastore.prototype.update = function () {
this.executor.push({ this: this, fn: this._update, arguments: arguments });
};
/**
* Remove all docs matching the query
*
* @private
* @see Datastore#remove
*/
Datastore.prototype._remove = function (query, options, cb) {
var origCallback
, callback
, self = this
, numRemoved = 0
, removalDocs = []
, removedFullDocs = []
, multi
;
if (typeof options === 'function') { cb = options; options = {}; }
origCallback = cb || function () {};
multi = options.multi !== undefined ? options.multi : false;
callback = function(err /*, numRemoved */) {
var context = this
, args = arguments
;
async.setImmediate(function () {
if (!err) {
if (removedFullDocs && removedFullDocs.length > 0) {
// Ensure there are listeners registered before making a bunch of unnecessary function calls to `emit`
if (self.listeners('removed').length > 0) {
removedFullDocs.forEach(function (oldDoc) {
self.emit('removed', oldDoc);
});
}
}
}
origCallback.apply(context, args);
});
};
this.getCandidates(query, true, function (err, candidates) {
if (err) { return callback(err); }
try {
candidates.forEach(function (d) {
if (model.match(d, query) && (multi || numRemoved === 0)) {
numRemoved += 1;
removalDocs.push({ $$deleted: true, _id: d._id });
removedFullDocs.push(d);
self.removeFromIndexes(d);
}
});
} catch (err) { return callback(err); }
self.persistence.persistNewState(removalDocs, function (err) {
if (err) { return callback(err); }
return callback(null, numRemoved);
});
});
};
/**
* Remove all docs matching the query
*
* @param {Object} query
* @param {Object} options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* @param {Function} cb Optional callback, signature: err, numRemoved
*
* @fires Datastore#removed
*/
Datastore.prototype.remove = function () {
this.executor.push({ this: this, fn: this._remove, arguments: arguments });
};
/**
* Remove all docs and then destroy the database's persistent datafile, if any
*
* @param {Function} cb Optional callback, signature: err
*
* @private
* @see Datastore#destroy
*/
Datastore.prototype._destroy = function (cb) {
var self = this
, callback = cb || function () {};
self._remove({}, { multi: true }, function (err /*, numRemoved */) {
if (err) {
return callback(err);
}
self.persistence.destroyDatabase(callback);
});
};
/**
* Remove all docs and then destroy the database's persistent datafile, if any
*
* @param {Function} cb Optional callback, signature: err
*
* @fires Datastore#destroyed
* @fires Datastore.destroyed
*/
Datastore.prototype.destroy = function (cb) {
var self = this
, callback = cb || function () {}
, eventedCallback = function (err) {
async.setImmediate(function () {
if (!err) {
// Ensure there are listeners registered before making any unnecessary function calls to `emit`
if (self.listeners('destroyed').length > 0) {
self.emit('destroyed');
}
if (self.constructor.listeners('destroyed').length > 0) {
self.constructor.emit('destroyed', self);
}
}
callback(err);
});
};
this.executor.push({ this: this, fn: this._destroy, arguments: [eventedCallback] });
};
/**
* Augment `Datastore` with user-defined extensions/patches
* @param {Function|Object} ext Must either be a function that takes one argument of `Datastore`, or a non-empty object
*/
Datastore.plugin = function (ext) {
if (typeof ext === 'function') { // function style for plugins
ext(Datastore);
} else if (typeof ext !== 'object' || !ext || Object.keys(ext).length === 0){
throw new Error('Invalid plugin: got \"' + ext + '\", expected an object or a function');
} else {
Object.keys(ext).forEach(function (id) { // object style for plugins
Datastore.prototype[id] = ext[id];
});
}
return Datastore;
};
module.exports = Datastore; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PrivateEndpointConnections } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SearchManagementClient } from "../searchManagementClient";
import {
PrivateEndpointConnection,
PrivateEndpointConnectionsListByServiceNextOptionalParams,
PrivateEndpointConnectionsListByServiceOptionalParams,
PrivateEndpointConnectionsUpdateOptionalParams,
PrivateEndpointConnectionsUpdateResponse,
PrivateEndpointConnectionsGetOptionalParams,
PrivateEndpointConnectionsGetResponse,
PrivateEndpointConnectionsDeleteOptionalParams,
PrivateEndpointConnectionsDeleteResponse,
PrivateEndpointConnectionsListByServiceResponse,
PrivateEndpointConnectionsListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing PrivateEndpointConnections operations. */
export class PrivateEndpointConnectionsImpl
implements PrivateEndpointConnections {
private readonly client: SearchManagementClient;
/**
* Initialize a new instance of the class PrivateEndpointConnections class.
* @param client Reference to the service client
*/
constructor(client: SearchManagementClient) {
this.client = client;
}
/**
* Gets a list of all private endpoint connections in the given service.
* @param resourceGroupName The name of the resource group within the current subscription. You can
* obtain this value from the Azure Resource Manager API or the portal.
* @param searchServiceName The name of the Azure Cognitive Search service associated with the
* specified resource group.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
searchServiceName: string,
options?: PrivateEndpointConnectionsListByServiceOptionalParams
): PagedAsyncIterableIterator<PrivateEndpointConnection> {
const iter = this.listByServicePagingAll(
resourceGroupName,
searchServiceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
searchServiceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
searchServiceName: string,
options?: PrivateEndpointConnectionsListByServiceOptionalParams
): AsyncIterableIterator<PrivateEndpointConnection[]> {
let result = await this._listByService(
resourceGroupName,
searchServiceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
searchServiceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
searchServiceName: string,
options?: PrivateEndpointConnectionsListByServiceOptionalParams
): AsyncIterableIterator<PrivateEndpointConnection> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
searchServiceName,
options
)) {
yield* page;
}
}
/**
* Updates a Private Endpoint connection to the search service in the given resource group.
* @param resourceGroupName The name of the resource group within the current subscription. You can
* obtain this value from the Azure Resource Manager API or the portal.
* @param searchServiceName The name of the Azure Cognitive Search service associated with the
* specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection to the Azure
* Cognitive Search service with the specified resource group.
* @param privateEndpointConnection The definition of the private endpoint connection to update.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
searchServiceName: string,
privateEndpointConnectionName: string,
privateEndpointConnection: PrivateEndpointConnection,
options?: PrivateEndpointConnectionsUpdateOptionalParams
): Promise<PrivateEndpointConnectionsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
searchServiceName,
privateEndpointConnectionName,
privateEndpointConnection,
options
},
updateOperationSpec
);
}
/**
* Gets the details of the private endpoint connection to the search service in the given resource
* group.
* @param resourceGroupName The name of the resource group within the current subscription. You can
* obtain this value from the Azure Resource Manager API or the portal.
* @param searchServiceName The name of the Azure Cognitive Search service associated with the
* specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection to the Azure
* Cognitive Search service with the specified resource group.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
searchServiceName: string,
privateEndpointConnectionName: string,
options?: PrivateEndpointConnectionsGetOptionalParams
): Promise<PrivateEndpointConnectionsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
searchServiceName,
privateEndpointConnectionName,
options
},
getOperationSpec
);
}
/**
* Disconnects the private endpoint connection and deletes it from the search service.
* @param resourceGroupName The name of the resource group within the current subscription. You can
* obtain this value from the Azure Resource Manager API or the portal.
* @param searchServiceName The name of the Azure Cognitive Search service associated with the
* specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection to the Azure
* Cognitive Search service with the specified resource group.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
searchServiceName: string,
privateEndpointConnectionName: string,
options?: PrivateEndpointConnectionsDeleteOptionalParams
): Promise<PrivateEndpointConnectionsDeleteResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
searchServiceName,
privateEndpointConnectionName,
options
},
deleteOperationSpec
);
}
/**
* Gets a list of all private endpoint connections in the given service.
* @param resourceGroupName The name of the resource group within the current subscription. You can
* obtain this value from the Azure Resource Manager API or the portal.
* @param searchServiceName The name of the Azure Cognitive Search service associated with the
* specified resource group.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
searchServiceName: string,
options?: PrivateEndpointConnectionsListByServiceOptionalParams
): Promise<PrivateEndpointConnectionsListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, searchServiceName, options },
listByServiceOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group within the current subscription. You can
* obtain this value from the Azure Resource Manager API or the portal.
* @param searchServiceName The name of the Azure Cognitive Search service associated with the
* specified resource group.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
searchServiceName: string,
nextLink: string,
options?: PrivateEndpointConnectionsListByServiceNextOptionalParams
): Promise<PrivateEndpointConnectionsListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, searchServiceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections/{privateEndpointConnectionName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.PrivateEndpointConnection
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.privateEndpointConnection,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.searchServiceName,
Parameters.subscriptionId,
Parameters.privateEndpointConnectionName
],
headerParameters: [
Parameters.accept,
Parameters.clientRequestId,
Parameters.contentType
],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections/{privateEndpointConnectionName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PrivateEndpointConnection
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.searchServiceName,
Parameters.subscriptionId,
Parameters.privateEndpointConnectionName
],
headerParameters: [Parameters.accept, Parameters.clientRequestId],
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections/{privateEndpointConnectionName}",
httpMethod: "DELETE",
responses: {
200: {
bodyMapper: Mappers.PrivateEndpointConnection
},
404: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.searchServiceName,
Parameters.subscriptionId,
Parameters.privateEndpointConnectionName
],
headerParameters: [Parameters.accept, Parameters.clientRequestId],
serializer
};
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PrivateEndpointConnectionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.searchServiceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept, Parameters.clientRequestId],
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PrivateEndpointConnectionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.searchServiceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept, Parameters.clientRequestId],
serializer
}; | the_stack |
declare module '@tonejs/midi' {
/**
* Return the index of the element at or before the given property
* @param {Array} array
* @param {*} value
* @param {string} prop
*/
function search(array: Array<any>, value: any, prop?: string): void;
/**
* Does a binary search to insert the note
* in the correct spot in the array
* @param {Array} array
* @param {Object} event
* @param {string=} prop
*/
function insert(array: Array<any>, event: any, prop?: string): void;
/**
* @typedef ControlChangeEvent
* @property {number} controllerType
* @property {number=} value
* @property {number=} absoluteTime
*/
type ControlChangeEvent = {
controllerType: number;
value?: number;
absoluteTime?: number;
};
/**
* Represents a control change event
*/
class ControlChange {
constructor(event: ControlChangeEvent, header: Header);
/** @type {number}
*/
ticks: number;
/** @type {number}
*/
value: number;
/**
* The controller number
* @readonly
* @type {number}
*/
readonly number: number;
/**
* return the common name of the control number if it exists
* @type {?string}
* @readonly
*
*/
readonly name: string;
/**
* The time of the event in seconds
* @type {number}
*/
time: number;
}
/**
* Automatically creates an alias for named control values using Proxies
* @returns {Object}
*/
function ControlChanges(): any;
/**
* @param {Midi} midi
* @returns {Uint8Array}
*/
function encode(midi: Midi): Uint8Array;
/**
* @typedef TempoEvent
* @property {number} ticks
* @property {number} bpm
* @property {number} [time]
*/
type TempoEvent = {
ticks: number;
bpm: number;
time?: number;
};
/**
* @typedef TimeSignatureEvent
* @property {number} ticks
* @property {number[]} timeSignature
* @property {number} [measures]
*/
type TimeSignatureEvent = {
ticks: number;
timeSignature: number[];
measures?: number;
};
/** Represents the parsed midi file header
*/
class Header {
constructor(midiData?: any);
/** @type {TempoEvent[]}
*/
tempos: TempoEvent[];
/** @type {TimeSignatureEvent[]}
*/
timeSignatures: TimeSignatureEvent[];
/** @type {string}
*/
name: string;
/** @type {Array}
*/
meta: Array<any>;
/**
* This must be invoked after any changes are made to the tempo array
* or the timeSignature array for the updated values to be reflected.
*/
update(): void;
/**
* @param {number} ticks
* @returns {number}
*/
ticksToSeconds(ticks: number): number;
/**
* @param {number} ticks
* @returns {number}
*/
ticksToMeasures(ticks: number): number;
/**
* The number of ticks per quarter note
* @type {number}
* @readonly
*/
readonly ppq: number;
/**
* @param {number} seconds
* @returns {number}
*/
secondsToTicks(seconds: number): number;
/**
* @returns {Object}
*/
toJSON(): any;
/**
* @param {Object} json
*/
fromJSON(json: any): void;
}
/**
* Describes the midi instrument of a track
*/
class Instrument {
constructor(trackData: Array<any>, track: Track);
/**@type {number}
*/
number: number;
/** @type {string}
*/
name: string;
/** @type {string}
*/
family: string;
/** @type {boolean}
*/
percussion: boolean;
/**
* @returns {Object}
*/
toJSON(): any;
/**
* @param {Object} json
*/
fromJSON(json: any): void;
}
/**
* The main midi parsing class
*/
class Midi {
constructor(midiArray?: ArrayLike<number> | ArrayBuffer);
/**
* Download and parse the MIDI file. Returns a promise
* which resolves to the generated midi file
* @param {string} url The url to fetch
* @returns {Promise<Midi>}
*/
static fromUrl(url: string): Promise<Midi>;
/** @type {Header}
*/
header: Header;
/** @type {Array<Track>}
*/
tracks: Track[];
/**
* The name of the midi file, taken from the first track
* @type {string}
*/
name: string;
/**
* The total length of the file in seconds
* @type {number}
*/
duration: number;
/**
* The total length of the file in ticks
* @type {number}
*/
durationTicks: number;
/**
* Add a track to the midi file
* @returns {Track}
*/
addTrack(): Track;
/**
* Encode the midi as a Uint8Array.
* @returns {Uint8Array}
*/
toArray(): Uint8Array;
/**
* Convert the midi object to JSON.
* @returns {Object}
*/
toJSON(): any;
/**
* Parse a JSON representation of the object. Will overwrite the current
* tracks and header.
* @param {Object} json
*/
fromJSON(json: any): void;
/**
* Clone the entire object midi object
* @returns {Midi}
*/
clone(): Midi;
}
/**
* @param {number} midi
* @returns {string}
*/
function midiToPitch(midi: number): string;
/**
* @param {number} midi
* @returns {string}
*/
function midiToPitchClass(midi: number): string;
/**
* @param {string} pitch
* @returns {number}
*/
function pitchClassToMidi(pitch: string): number;
/**
* @type {function}
*/
var pitchToMidi: (...params: any[]) => any;
/**
* @typedef NoteOnEvent
* @property {number} ticks
* @property {number} velocity
* @property {number} midi
*/
type NoteOnEvent = {
ticks: number;
velocity: number;
midi: number;
};
/**
* @typedef NoteOffEvent
* @property {number} ticks
* @property {number} velocity
*/
type NoteOffEvent = {
ticks: number;
velocity: number;
};
/**
* A Note consists of a noteOn and noteOff event
*/
class Note {
constructor(noteOn: NoteOnEvent, noteOff: NoteOffEvent, header: Header);
/**
* The notes midi value
* @type {number}
*/
midi: number;
/**
* The normalized velocity (0-1)
* @type {number}
*/
velocity: number;
/**
* The velocity of the note off
* @type {number}
*/
noteOffVelocity: number;
/**
* The start time in ticks
* @type {number}
*/
ticks: number;
/**
* The duration in ticks
* @type {number}
*/
durationTicks: number;
/**
* The note name and octave in scientific pitch notation, e.g. "C4"
* @type {string}
*/
name: string;
/**
* The notes octave number
* @type {number}
*/
octave: number;
/**
* The pitch class name. e.g. "A"
* @type {string}
*/
pitch: string;
/**
* The duration of the segment in seconds
* @type {number}
*/
duration: number;
/**
* The time of the event in seconds
* @type {number}
*/
time: number;
/**
* The number of measures (and partial measures) to this beat.
* Takes into account time signature changes
* @type {number}
* @readonly
*/
readonly bars: number;
}
/**
* @typedef MidiEvent
* @property {string} type
* @property {number=} velocity
* @property {number} absoluteTime
* @property {number=} noteNumber
* @property {string=} text
* @property {number=} controllerType
* @property {number} value
*/
type MidiEvent = {
type: string;
velocity?: number;
absoluteTime: number;
noteNumber?: number;
text?: string;
controllerType?: number;
value: number;
};
/**
* @typedef {Array<MidiEvent>} TrackData
*/
type TrackData = MidiEvent[];
/**
* A Track is a collection of notes and controlChanges
*/
class Track {
constructor(trackData: TrackData, header: Header);
/** @type {string}
*/
name: string;
/** @type {Instrument}
*/
instrument: Instrument;
/** @type {Array<Note>}
*/
notes: Note[];
/** @type {number}
*/
channel: number;
/** @type {Object<string,Array<ControlChange>>}
*/
controlChanges: {
[key: string]: ControlChange[];
};
/**
* Add a note to the notes array
* @param {NoteParameters} props The note properties to add
* @returns {Track} this
*/
addNote(props: NoteParameters): Track;
/**
* Add a control change to the track
* @param {CCParameters} props
* @returns {Track} this
*/
addCC(props: CCParameters): Track;
/**
* The end time of the last event in the track
* @type {number}
* @readonly
*/
readonly duration: number;
/**
* The end time of the last event in the track in ticks
* @type {number}
* @readonly
*/
readonly durationTicks: number;
/**
* @param {Object} json
*/
fromJSON(json: any): void;
/**
* @returns {Object}
*/
toJSON(): any;
}
/**
* @typedef NoteParameters
* @property {number=} time
* @property {number=} ticks
* @property {number=} duration
* @property {number=} durationTicks
* @property {number=} midi
* @property {string=} pitch
* @property {number=} octave
* @property {string=} name
* @property {number=} noteOffVelocity
* @property {number} [velocity=1]
* @property {number} [channel=1]
*/
type NoteParameters = {
time?: number;
ticks?: number;
duration?: number;
durationTicks?: number;
midi?: number;
pitch?: string;
octave?: number;
name?: string;
noteOffVelocity?: number;
velocity?: number;
channel?: number;
};
/**
* @typedef CCParameters
* @property {number=} time
* @property {number=} ticks
* @property {number} value
* @property {number} number
*/
type CCParameters = {
time?: number;
ticks?: number;
value: number;
number: number;
};
export = Midi;
// export as namespace Midi;
} | the_stack |
* ************************************
*
* @module expressParser.ts
* @author Amir Marcel, Christopher Johnson, Corey Van Splinter, Sean Arseneault
* @date 12/8/2020
* @description Defines ExpressParser class. Finds all express endpoints with a given root
* file and port and returns an object with all information about the endpoints
*
* ************************************
*/
import { getRanges } from './utils/ast';
// Regex patterns used for file parsing
import { FILENAME_AND_PATH, ROUTE_PARAMS } from '../constants/expressPatterns';
// File and path manipulation functions
import { readFile, findImportedFiles, getLocalRoute } from './utils/genericFileOps';
// Express specific file operations
import {
findExpressImport,
findExpressServer,
findRouters,
findRoutes,
findRouterPath,
} from './utils/expressFileOps';
import { ext } from '../extensionVariables';
/** Class representing parsed express server data */
class ExpressParser {
serverPort: number;
serverFile: any;
supportFiles: Map<string, File>;
expressData: ExpressData[];
routerData: Map<string, RouterData>;
routes: Route[];
/**
* Creates a new ExpressParser object
* @param {string} serverPath The path of the top-level server file
* @param {number} portNum The port number on which the server is running
*/
constructor(serverPath: string, portNum: number) {
this.serverPort = portNum;
this.serverFile = this.initializeServerFile(serverPath);
this.supportFiles = new Map();
this.expressData = [];
this.routerData = new Map();
this.routes = [];
}
/**
* Creates a File object containing info about the server file
* @param {string} serverPath The path of the top-level server file
* @return {File} A File object containing info about the server file
*/
initializeServerFile(serverPath: string): Partial<File> {
const SPLIT_PATH = serverPath.match(FILENAME_AND_PATH);
if (SPLIT_PATH !== null)
return { path: SPLIT_PATH[1], fileName: SPLIT_PATH[2], contents: '' };
// Return a File object with no values for the file name and path
return { path: '', fileName: '', contents: '' };
}
/**
* Parses all endpoints from the express server
* @return {MasterDataObject} A WorkspaceObj object containing info for all endpoints in the server
*/
parse() {
this.serverFile.contents = readFile(this.serverFile);
this.findSupportFiles();
this.findExpressImports();
this.findServerName();
this.findRouterFiles(this.serverFile);
this.supportFiles.forEach((file) => this.findRouterFiles(file));
this.findAllRoutes();
this.findRouteEndLines();
return this.buildMasterDataObject();
}
/**
* Finds all files imported by the top-level server file, and all files that they import
*/
findSupportFiles() {
// Enqueue all local files that are imported by the top-level server file
let queue = this.addSupportFiles(findImportedFiles(this.serverFile));
let currentFile = queue.shift();
while (currentFile !== undefined) {
// Read and store the contents of each file and enqueue all files they import
queue = queue.concat(this.readSupportFile(currentFile));
currentFile = queue.shift();
}
}
/**
* Adds any imported files to the list of support files, if they haven't already been added
* @param {File[]} importedFiles The files to add to the list of support files
* @return {string[]} An array containing the names of the files that were successfully added
*/
addSupportFiles(importedFiles: File[]): string[] {
const addedFiles = [];
for (const importedFile of importedFiles) {
const FILE_NAME = importedFile.path.concat(importedFile.fileName);
// Only add files that haven't already been added to the list of support files
if (this.supportFiles.get(FILE_NAME) === undefined) {
this.supportFiles.set(FILE_NAME, importedFile);
addedFiles.push(FILE_NAME);
}
}
return addedFiles;
}
/**
* Reads the contents of the specified file into memory and
* adds any files it imports to the list of support files
* @param {string} fileName The file to read
* @return {string[]} An array containing the names of the imported files that were added
*/
readSupportFile(fileName: string): string[] {
let addedFiles: string[] = [];
const FILE = this.supportFiles.get(fileName);
if (FILE !== undefined) {
// Read the file contents and enqueue any imported files that need to be read
FILE.contents = readFile(FILE);
addedFiles = this.addSupportFiles(findImportedFiles(FILE));
}
return addedFiles;
}
/**
* Finds and stores any express import statements in the code base,
* starting at the top-level server file
*/
findExpressImports() {
// Search the top-level serverfile for any express importes
const IMPORT_NAME = findExpressImport(this.serverFile);
if (IMPORT_NAME !== undefined) {
this.storeExpressImport(this.serverFile, IMPORT_NAME);
}
// Search the support files for any express import statements
this.searchSupportFilesForExpress();
}
/**
* Finds and stores any express import statements in the support files
*/
searchSupportFilesForExpress() {
const FILE_LIST = this.supportFiles.entries();
let currentFile = FILE_LIST.next().value;
while (currentFile !== undefined) {
const IMPORT_NAME = findExpressImport(currentFile[1]);
if (IMPORT_NAME !== undefined) {
// If the file imports express, store the details of the express import
this.storeExpressImport(currentFile[1], IMPORT_NAME);
}
currentFile = FILE_LIST.next().value;
}
}
/**
* Stores the filename and variable name associated with the express import
* @param file The file containing the express import statement
* @param importName The name of the variable assigned to the express import
*/
storeExpressImport(file: File, importName: string) {
const filePath = file.path.concat(file.fileName);
this.expressData.push({ filePath, importName, serverName: '' });
}
/**
* Find the name of the variable used to store each invocation of express
*/
findServerName() {
for (let i = 0; i < this.expressData.length; i += 1) {
// Use the server file if an error occurs in obtaining the correct support file
const EXPRESS_FILE =
this.supportFiles.get(this.expressData[i].filePath) || this.serverFile;
const EXPRESS_NAME = this.expressData[i].importName;
// If an express call was found, store the name of the associated variable
const SERVER_NAME = findExpressServer(EXPRESS_FILE, EXPRESS_NAME);
if (SERVER_NAME) this.expressData[i].serverName = SERVER_NAME;
}
}
/**
* Identifies all router files used by the express server
*/
findRouterFiles(file: File) {
const ROUTERS = findRouters(file, this.serverPort);
ROUTERS.forEach((router) => {
// Determine the absolute file path for each router identified
router.path = findRouterPath(router, file, this.supportFiles);
this.routerData.set(router.path, router);
});
}
/**
* Finds all routes in the top-level server file and all support files
*/
findAllRoutes() {
const BASE_ROUTE = `http://localhost:${this.serverPort}`;
const PATH = this.serverFile.path.concat(this.serverFile.fileName);
// Find all routes in the top-level server file
this.routes = findRoutes(this.serverFile.contents, PATH, BASE_ROUTE);
// Find all routes in each support file
this.supportFiles.forEach((file) => {
let route = BASE_ROUTE;
// If the support file is a router file, get the base route for all routes in the file
const ROUTER_DATA = this.routerData.get(file.path + file.fileName);
if (ROUTER_DATA !== undefined) route = ROUTER_DATA.baseRoute;
this.routes = this.routes.concat(
findRoutes(file.contents, file.path + file.fileName, route),
);
});
}
/**
* Find the ending line of any route functions
*/
findRouteEndLines() {
this.routes.forEach((route) => {
const ROUTER_FILE = this.supportFiles.get(route.path) || this.serverFile;
const FILE_RANGES = getRanges(ROUTER_FILE.contents);
route.endLine = FILE_RANGES[route.startLine];
});
}
buildMasterDataObject() {
const data: MasterDataObject | undefined = ext.context.workspaceState.get(
`masterDataObject`,
);
const serverPath = this.serverFile.path.concat(this.serverFile.fileName);
const urls: Record<any, any> = {};
const paths: Record<any, any> = {};
const index: Record<any, any> = {};
this.routes.forEach((route) => {
const { origin, pathname, port, href } = new URL(route.route);
const params = this.findParams(getLocalRoute(route.route));
let presets = {};
const range =
route.startLine === route.endLine
? route.startLine
: `${route.startLine}-${route.endLine}`;
index[route.path] = {
serverPath,
port,
};
if (paths[route.path] === undefined) {
paths[route.path] = {};
}
paths[route.path][range] = {
method: route.method,
origin,
pathname,
port,
params,
range: [route.startLine, route.endLine],
};
if (data && data.domains[serverPath] && data.domains[serverPath].urls[href]) {
presets = data.domains[serverPath].urls[href].presets;
}
if (!urls[href]) {
urls[href] = {
serverPath,
filePath: route.path,
href,
port,
pathname,
methods: [route.method],
presets,
params,
};
} else if (!urls[href].methods.includes(route.method)) {
urls[href].methods.push(route.method);
}
});
const output = { paths, urls, index };
return output;
}
/**
* Identifies all parameters in the specified route
* @param {string} route The route to check
* @return {Record<string, string>} A record containing "paramID: paramValue" key-value pairs
*/
findParams(route: string): Record<string, string> {
const output: Record<string, string> = {};
const PARAMS_FOUND = route.match(ROUTE_PARAMS);
if (PARAMS_FOUND) {
for (let i = 1; i < PARAMS_FOUND.length; i++) {
// Remove the colon from the beginning of the param id
output[PARAMS_FOUND[i].slice(1)] = '';
}
}
return output;
}
}
export default ExpressParser; | the_stack |
import {Camera} from './model/camera';
import {Color} from './math/color';
import {Vec3} from './math/vec3';
import {Mat4} from './math/mat4';
import {Quaternion} from './math/quaternion';
import {AnimatedEntityProgram, AnimatedEntityRenderCall} from './render/program/animatedentityprogram';
import {DirectionalLight} from './render/directionallight';
import {getModelData, getAnimationData, ANIMATIONS} from './model/betacharactermodel';
import {ModelData} from './render/program/animatedentityprogram';
import {Animation} from './model/animation';
import {CreateRandomDancingEntity, Entity} from './model/dancingentity';
import {AnimationManager} from './model/animationmanager';
import {NaiveJSAnimationManager} from './model/naivejsanimationmanager';
import {NaiveWASMAnimationManager} from './model/naivewasmanimationmanager';
import {GUI, SystemType} from './settingsgui';
// http://stackoverflow.com/a/901144 by user jolly.exe
function getParameterByName(name: string, url?: string): string|null {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
let getCachedParameterByName = (function () {
let paramCache: Map<string, any> = new Map();
return (name: string, defaultValue: any, url?: string) => {
if (!paramCache.has(name)) {
paramCache.set(name, getParameterByName(name, url) || defaultValue);
}
return paramCache.get(name);
}
})();
class Demo {
constructor() {}
public CreateAndStart(canvas: HTMLCanvasElement) {
let animationManagerType: string = getParameterByName('system') || 'default';
if (['naivejs', 'speedyjs', 'naivewasm', 'speedywasm'].indexOf(animationManagerType) == -1) {
animationManagerType = 'naivejs';
}
let wasmAnimationManager = new NaiveWASMAnimationManager();
let jsAnimationManager = new NaiveJSAnimationManager();
Promise.all([
getModelData(),
getAnimationData(ANIMATIONS.RUN),
getAnimationData(ANIMATIONS.SAMBA),
getAnimationData(ANIMATIONS.TUT),
getAnimationData(ANIMATIONS.WAVE),
wasmAnimationManager.load(),
jsAnimationManager.load()
]).then((stuff) => {
if (!stuff[5]) {
throw new Error('Could not instantiate system!');
}
this.start(canvas, stuff[0], stuff[1], [stuff[2], stuff[3], stuff[4]], jsAnimationManager, wasmAnimationManager)
})
.catch((e) => alert(e));
}
protected start(canvas: HTMLCanvasElement, betaModelData: ModelData[], betaRun: Animation, betaDances: Animation[], jsAnimationManager: NaiveJSAnimationManager, wasmAnimationManager: NaiveWASMAnimationManager) {
// With everything loaded, start opening up the screen
document.body.className += " loaded";
let gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (!gl) {
return console.error('Could not create WebGL rendering context!');
}
var activeAnimationManager:AnimationManager = jsAnimationManager;
let gui = new GUI();
//
// Set up the model
//
let camera = new Camera(
new Vec3(0, 285, 600),
new Vec3(0, 85, 0),
new Vec3(0, 1, 0)
);
let projMatrix = new Mat4().perspective(
Math.PI * 0.6,
gl.canvas.clientWidth / gl.canvas.clientHeight,
0.1,
2000.0
);
gl.canvas.width = gl.canvas.clientWidth;
gl.canvas.height = gl.canvas.clientHeight;
const VELOCITY = 80;
const START_POS = new Vec3(0, 0, -800);
const END_POS = new Vec3(0, 0, 750);
const DISTANCE_TO_TRAVEL = END_POS.sub(START_POS).length();
const EACH_OFFSET = new Vec3(175, 0, 0);
// Register animations (must happen first)
jsAnimationManager.registerAnimation(betaRun);
wasmAnimationManager.registerAnimation(betaRun);
betaDances.forEach((dance) =>{
jsAnimationManager.registerAnimation(dance);
wasmAnimationManager.registerAnimation(dance);
});
// Register models and perform associations
betaModelData.forEach((model) => {
jsAnimationManager.registerModel(model)
wasmAnimationManager.registerModel(model);
});
betaModelData.forEach((model) => {
if (!jsAnimationManager.associateModelAndAnimation(betaRun, model) || !wasmAnimationManager.associateModelAndAnimation(betaRun, model)) {
console.error('Error - model', model, 'and animation', betaRun, 'cannot be associated!');
}
});
betaDances.forEach((dance) => betaModelData.forEach((model) => {
if (!jsAnimationManager.associateModelAndAnimation(dance, model) || !wasmAnimationManager.associateModelAndAnimation(dance, model)) {
console.error('Error - model', model, 'and animation', betaRun, 'cannot be associated!');
};
}));
let numRunners = gui.values.NumRunners;
let runners: Entity[] = [];
var setupRunners = () => {
for (let i = runners.length; i >= numRunners; i--) runners.pop();
for (let i = runners.length; i < numRunners; i++) {
runners.push(CreateRandomDancingEntity(
betaRun,
betaDances,
DISTANCE_TO_TRAVEL,
VELOCITY, {
minStartRunTime: getCachedParameterByName('minstartruntime', undefined),
minDanceCycles: getCachedParameterByName('mindancecycles', undefined),
maxDanceCycles: getCachedParameterByName('maxdancecycles', undefined)
}
));
}
};
setupRunners();
//
// GUI
//
gui.values.OnSystemChange.push((type: SystemType) => {
switch (type) {
case 'JavaScript':
activeAnimationManager = jsAnimationManager;
break;
case 'WebAssembly':
activeAnimationManager = wasmAnimationManager;
break;
}
});
gui.values.OnNumRunnersChange.push((num: number) => {
numRunners = num;
setupRunners();
});
window.addEventListener('resize', () => {
if (!gl) return;
projMatrix = new Mat4().perspective(
Math.PI * 0.6,
gl.canvas.clientWidth / gl.canvas.clientHeight,
0.1,
2000.0
);
gl.canvas.width = gl.canvas.clientWidth;
gl.canvas.height = gl.canvas.clientHeight;
program.prepare(gl);
program.setSceneData(gl, projMatrix, new DirectionalLight(
Color.WHITE,
Color.WHITE,
new Vec3(1, -3, 0.7).setNormal()
));
program.disengage(gl);
});
let stats = new Stats();
let animationTimePanel = stats.addPanel(new Stats.Panel('Anim', '#f8f', '#212'));
stats.showPanel(2);
document.body.appendChild(stats.dom);
//
// Make the GL resources
//
let program = new AnimatedEntityProgram();
let calls: AnimatedEntityRenderCall[] = betaModelData.map((model) => new AnimatedEntityRenderCall(model, new Mat4()));
program.prepare(gl);
program.setSceneData(gl, projMatrix, new DirectionalLight(
Color.WHITE,
Color.WHITE,
new Vec3(-1, -3, -0.7).setNormal()
));
program.disengage(gl);
let r = activeAnimationManager.getSingleAnimation(betaRun, calls[1].modelData, 0);
let lastFrame = performance.now();
let thisFrame: number;
let dt: number;
let frame = function () {
//
// Timing
//
thisFrame = performance.now();
dt = (thisFrame - lastFrame) / 1000;
lastFrame = thisFrame;
stats.begin();
//
// GL resources
//
if (!gl) {
console.warn('Context lost - restoring');
gl = canvas.getContext('webgl');
if (!gl) {
return console.error('Could not restore WebGL context!');
}
}
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clearColor(0xd9/255, 0xe9/255, 1, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//
// Model Updates
//
for (let i = 0; i < runners.length; i++) {
runners[i].update(dt);
if (runners[i].isFinished()) {
runners[i] = CreateRandomDancingEntity(betaRun, betaDances, DISTANCE_TO_TRAVEL, VELOCITY);
}
}
//
// Scene Rendering
//
program.prepare(gl);
program.setPerFrameData(gl, camera.getViewMatrix(), camera.getPosition());
let sum = 0;
for (let i = 0; i < runners.length; i++) {
for (let j = 0; j < calls.length; j++) {
let b4 = performance.now();
let animationData = runners[i].getAnimationData(calls[j].modelData, activeAnimationManager);
let after = performance.now();
sum = sum + (after - b4);
// TODO SESS: Handle the extra memory used here
calls[j].worldTransform.setRotationTranslationScale(
Quaternion.IDENTITY,
Vec3.lerp(START_POS, END_POS, runners[i].getTrackPos() / DISTANCE_TO_TRAVEL).setAdd(EACH_OFFSET.scale(i - runners.length / 2)),
Vec3.ONES
);
program.renderObject(gl, calls[j], animationData.boneData);
}
}
animationTimePanel.update(sum, 25 * runners.length);
program.disengage(gl);
stats.end();
requestAnimationFrame(frame);
};
requestAnimationFrame(frame);
}
};
const DemoApp: Demo = new Demo();
DemoApp.CreateAndStart(document.getElementById('demo-surface') as HTMLCanvasElement); | the_stack |
export const rules = [
{
class: 'table_row',
attributes: ['hover'],
'layer0.opacity': 0.1,
},
{
class: 'table_row',
attributes: ['selected'],
'layer0.opacity': 0.2,
},
{
class: 'table_row',
parents: [{ class: 'auto_complete', attributes: ['file_light'] }],
attributes: ['selected'],
'layer0.opacity': 0.15,
},
{
class: 'table_row',
'layer0.tint': [255, 255, 255],
'layer0.opacity': 0.0,
},
{
class: 'table_row',
parents: [{ class: 'auto_complete', attributes: ['file_light'] }],
'layer0.tint': [0, 0, 0],
'layer0.opacity': 0.0,
},
// Command History
{
class: 'command_table',
},
{
class: 'command_history_container',
'layer0.tint': 'var(accentLighter)',
},
{
class: 'command_table_container',
'layer0.tint': 'var(accentLight)',
},
// Browse page
{
class: 'console_panel',
'layer0.tint': 'var(consoleBorder)',
'layer0.opacity': 1.0,
},
{
class: 'panel_grid_control',
inside_spacing: 0,
outside_vspacing: 4,
},
{
class: 'root_tabs',
'layer0.tint': 'var(tabBarBg)',
'layer0.opacity': 1.0,
},
// Focus highlight
{
class: 'focus_highlight_control',
highlight_color: 'color(var(foreground) a(0.2))',
highlight_border_color: 'color(var(foreground) a(0.6))',
},
// Overlay
{
class: 'overlay_container_control',
'layer0.tint': 'var(overlayBg)',
'layer0.opacity': 0.4,
},
// Labels
{
class: 'label_control',
fg: 'var(labelColor)',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
},
{
class: 'title_label_control',
fg: 'var(labelColor)',
'font.face': 'var(font_face)',
'font.size': 24,
},
{
class: 'label_control',
parents: [{ class: 'button_control' }],
fg: 'var(buttonFg)',
shadow_color: 'var(buttonShadow)',
shadow_offset: [0, 0],
},
// Basic and hazard buttons
{
class: 'button_control',
'layer1.tint': 'var(buttonBg)',
'layer1.opacity': {
target: 0.6,
speed: 4.0,
interpolation: 'smoothstep',
},
// 'layer1.texture': 'Theme - Merge/button.png',
'layer1.inner_margin': 4,
'layer2.tint': 'var(hazardButtonBg)',
'layer2.opacity': 0.0,
// 'layer2.texture': 'Theme - Merge/button.png',
'layer2.inner_margin': 4,
min_size: [90, 15],
content_margin: [10, 6],
},
{
class: 'button_control left',
// 'layer1.texture': 'Theme - Merge/button_left.png',
// 'layer2.texture': 'Theme - Merge/button_left.png',
},
{
class: 'button_control right',
// 'layer1.texture': 'Theme - Merge/button_right.png',
// 'layer2.texture': 'Theme - Merge/button_right.png',
},
{
class: 'button_control',
attributes: ['hover'],
'layer1.tint': 'var(buttonBgHover)',
'layer1.opacity': 1.0,
},
{
class: 'button_control',
attributes: ['confirm'],
'layer2.opacity': {
target: 0.5,
speed: 2.0,
interpolation: 'smoothstep',
},
},
{
class: 'button_control',
attributes: ['pressed'],
'layer1.opacity': 1.0,
},
{
class: 'button_control',
attributes: ['pressed', 'confirm'],
'layer1.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'label_control',
parents: [{ class: 'button_control', attributes: ['confirm'] }],
fg: 'var(foreground)',
shadow_color: 'var(hazard_button_shadow)',
shadow_offset: [0, 0],
},
// Split buttons
{
class: 'button_control_left',
// 'layer1.texture': 'Theme - Merge/button_left.png',
min_size: [70, 15],
},
{
class: 'button_control_right',
// 'layer1.texture': 'Theme - Merge/button_right.png',
'layer1.inner_margin': [2, 2, 2, 2],
// 'layer3.texture': 'Theme - Merge/button_right_line.png',
'layer3.tint': 'var(split_button_line)',
'layer3.opacity': 0.35,
'layer3.inner_margin': 4,
content_margin: [5, 6],
min_size: [10, 15],
},
// {
// class: 'label_control',
// parents: [{ class: 'button_control_right' }],
// fg: 'var(split_button_right_fg)',
// },
// {
// class: 'label_control',
// parents: [{ class: 'button_control_right', attributes: ['hover'] }],
// fg: 'var(split_button_right_fg-hover)',
// },
// Toggle buttons
{
class: 'toggle_button',
'layer0.tint': 'var(toggleButtonBg)',
'layer0.opacity': 1.0,
'layer0.inner_margin': 4,
min_size: [60, 22],
content_margin: [8, 0, 8, 0],
},
{
class: 'toggle_button left',
// 'layer0.texture': 'Theme - Merge/button_outline_left.png',
'layer1.opacity': {
target: 0.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'toggle_button left',
attributes: ['hover'],
'layer1.tint': 'var(toggleButtonBg)',
'layer1.opacity': {
target: 0.3,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'toggle_button left',
attributes: ['selected'],
// 'layer0.texture': 'Theme - Merge/button_left.png',
'layer1.opacity': 0,
},
{
class: 'toggle_button right',
// 'layer0.texture': 'Theme - Merge/button_outline_right.png',
'layer1.opacity': {
target: 0.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'toggle_button right',
attributes: ['hover'],
'layer1.tint': 'var(toggleButtonBg)',
'layer1.opacity': {
target: 0.3,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'toggle_button right',
attributes: ['selected'],
// 'layer0.texture': 'Theme - Merge/button_right.png',
'layer1.opacity': 0,
},
{
class: 'label_control',
parents: [{ class: 'toggle_button' }],
fg: 'var(toggleButtonFg)',
},
{
class: 'label_control',
parents: [{ class: 'toggle_button', attributes: ['selected'] }],
fg: 'var(toggleButtonFgSelected)',
},
// File Tabs
{
class: 'tab',
'layer0.tint': 'var(tabBackground)',
'layer0.opacity': 0.0,
'layer0.inner_margin': 4,
'layer1.inner_margin': 'var(tabSelectedBorderSize)',
'layer1.draw_center': false,
'layer1.tint': 'var(tabSelectedBorderColor)',
'layer1.opacity': 0.0,
min_size: [90, 32],
content_margin: [8, 0, 8, 0],
},
{
class: 'tab',
parents: [{ class: 'side_bar_container with_graph' }],
'layer0.tint': 'var(sideBarContainerBgWithGraph)',
},
{
class: 'tab',
attributes: ['hover'],
'layer1.opacity': {
target: 0.5,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'tab',
attributes: ['selected'],
'layer0.opacity': 0.0,
'layer1.opacity': 1.0,
},
{
class: 'label_control',
parents: [{ class: 'tab' }],
fg: 'var(toggleButtonFg)',
},
{
class: 'label_control',
parents: [{ class: 'tab', attributes: ['selected'] }],
fg: 'var(toggleButtonFgSelected)',
},
{
class: 'tab_separator',
// 'layer0.texture': 'Theme - Merge/tab_separator.png',
'layer0.tint': 'var(tabSeparatorBg)',
'layer0.inner_margin': [0, 1],
'layer0.opacity': 1.0,
content_margin: [0, 12, 1, 12],
},
{
class: 'tab_separator_container',
},
{
class: 'details_tab_bar',
'layer0.tint': 'var(tabBarBg)',
'layer0.opacity': 1.0,
},
{
class: 'scroll_area_control',
parents: [{ class: 'details_tab_bar' }],
left_shadow: 'var(scrollShadow)',
left_shadow_size: 8,
right_shadow: 'var(scrollShadow)',
right_shadow_size: 8,
},
{
class: 'tab',
parents: [{ class: 'details_tab_bar' }],
'layer0.tint': 'var(locationBarFg)',
},
{
class: 'label_control',
parents: [{ class: 'details_tab_bar' }],
fg: 'var(foreground)',
},
{
class: 'label_control',
parents: [{ class: 'all_button' }],
fg: 'var(foreground)',
},
{
class: 'label_control',
parents: [
{ class: 'details_tab_bar' },
{ class: 'tab', attributes: ['selected'] },
],
fg: 'var(foreground)',
},
// Checkboxes
{
class: 'checkbox_box_control',
content_margin: [13, 13, 0, 0],
// 'layer0.texture': 'Theme - Merge/checkbox_back.png',
'layer0.tint': 'var(checkboxBack)',
'layer0.opacity': 1,
// 'layer1.texture': 'Theme - Merge/checkbox_border.png',
'layer1.tint': 'var(checkbox_border-unselected)',
'layer1.opacity': 1,
// 'layer2.texture': 'Theme - Merge/checkbox_check.png',
'layer2.tint': 'var(checkboxSelected)',
'layer2.opacity': 0,
},
{
class: 'checkbox_box_control',
parents: [{ class: 'checkbox_control', attributes: ['checked'] }],
'layer1.tint': 'var(checkboxBorderSelected)',
'layer2.opacity': 1,
},
{
class: 'checkbox_box_control',
parents: [{ class: 'checkbox_control', attributes: ['disabled'] }],
// 'layer2.texture': 'Theme - Merge/checkbox_disabled.png',
'layer2.tint': 'var(checkbox-disabled)',
'layer2.opacity': 1,
},
// Radio Buttons
{
class: 'radio_button_list_control',
spacing: 4,
},
{
class: 'checkbox_box_control',
parents: [
{ class: 'radio_button_list_control' },
{ class: 'checkbox_control' },
],
content_margin: [13, 13, 0, 0],
// 'layer0.texture': 'Theme - Merge/radio_button_back.png',
'layer0.tint': 'var(radioBack)',
'layer0.opacity': 1,
// 'layer1.texture': 'Theme - Merge/radio_button_border.png',
'layer1.tint': 'var(radioBorderSelected)',
'layer1.opacity': 1,
// 'layer2.texture': 'Theme - Merge/radio_button_on.png',
'layer2.tint': 'var(radioSelected)',
'layer2.opacity': 0,
},
{
class: 'checkbox_box_control',
parents: [
{ class: 'radio_button_list_control' },
{ class: 'checkbox_control', attributes: ['hover'] },
],
'layer1.tint': 'var(radioBorderSelected)',
},
{
class: 'checkbox_box_control',
parents: [
{ class: 'radio_button_list_control' },
{ class: 'checkbox_control', attributes: ['checked'] },
],
'layer1.tint': 'var(radioBorderSelected)',
'layer2.opacity': 1,
},
// Scroll Bars
{
class: 'scroll_area_control',
settings: ['overlay_scroll_bars'],
overlay: true,
},
{
class: 'scroll_area_control',
settings: ['!overlay_scroll_bars'],
overlay: false,
},
{
class: 'scroll_bar_control',
'layer0.opacity': 1.0,
content_margin: 4,
tint_index: 0,
},
{
class: 'scroll_bar_control',
settings: ['overlay_scroll_bars'],
'layer0.opacity': 0.0,
},
{
class: 'scroll_bar_control',
settings: ['!overlay_scroll_bars'],
'layer0.opacity': 1.0,
},
{
class: 'scroll_track_control',
// 'layer0.texture': 'Theme - Merge/light_scroll_bar.png',
'layer0.opacity': 1.0,
'layer0.inner_margin': 2,
content_margin: [4, 4, 3, 4],
},
{
class: 'scroll_track_control',
attributes: ['dark'],
// 'layer0.texture': 'Theme - Merge/dark_scroll_bar.png',
},
{
class: 'puck_control',
// 'layer0.texture': 'Theme - Merge/light_scroll_puck.png',
'layer0.opacity': 1.0,
'layer0.inner_margin': 2,
content_margin: [0, 12],
},
{
class: 'puck_control',
attributes: ['dark'],
// 'layer0.texture': 'Theme - Merge/dark_scroll_puck.png',
},
{
class: 'scroll_corner_control',
'layer0.opacity': 1.0,
tint_index: 0,
},
// Scroll Bars (Horizontal)
{
class: 'scroll_track_control',
attributes: ['horizontal'],
// 'layer0.texture': 'Theme - Merge/light_scroll_bar_horiz.png',
content_margin: [4, 4, 4, 3],
},
{
class: 'scroll_track_control',
attributes: ['horizontal', 'dark'],
// 'layer0.texture': 'Theme - Merge/dark_scroll_bar_horiz.png',
},
{
class: 'puck_control',
attributes: ['horizontal'],
// 'layer0.texture': 'Theme - Merge/light_scroll_puck_horiz.png',
content_margin: [12, 0],
},
{
class: 'puck_control',
attributes: ['horizontal', 'dark'],
// 'layer0.texture': 'Theme - Merge/dark_scroll_puck_horiz.png',
},
// Scroll Bars (Overlay)
{
class: 'scroll_bar_control',
parents: [{ class: 'overlay_control' }],
'layer0.opacity': 0.0,
content_margin: [4, 0, 0, 0],
},
{
class: 'scroll_track_control',
parents: [{ class: 'overlay_control' }],
// 'layer0.texture': 'Theme - Merge/light_scroll_bar.png',
},
{
class: 'puck_control',
parents: [{ class: 'overlay_control' }],
// 'layer0.texture': 'Theme - Merge/light_scroll_puck.png',
},
// Dialogs
{
class: 'dialog',
'layer0.tint': 'var(dialogBg)',
'layer0.opacity': 1.0,
},
{
class: 'progress_bar_control',
'layer0.tint': 'var(progressBg)',
'layer0.opacity': 1.0,
},
{
class: 'progress_gauge_control',
'layer0.tint': 'var(progressFg)',
'layer0.opacity': 1.0,
content_margin: [0, 6],
},
{
class: 'button_control',
parents: [{ class: 'dialog' }],
'layer1.tint': 'var(dialogButtonBg)',
},
// Quick Panel
{
class: 'overlay_control',
'layer0.tint': 'var(quickPanelBg)',
'layer0.opacity': 1.0,
content_margin: 4,
},
{
class: 'quick_panel',
row_padding: 6,
'layer0.tint': 'var(quickPanelBg)',
'layer0.opacity': 1.0,
dark_content: false,
},
{
class: 'text_line_control',
'layer0.opacity': 0.0,
'layer0.inner_margin': [20, 5, 20, 5],
'layer1.tint': 'color(var(accentLightest) a(0.5))',
'layer1.opacity': 1.0,
'layer1.inner_margin': 'var(inputBorderSize)',
'layer1.draw_center': false,
color_scheme_tint: 'color(var(accentLightest) a(0.15))',
},
{
class: 'text_line_control',
parents: [{ class: 'welcome_overlay_contents' }],
color_scheme_tint: 'var(inputBackgroundWelcome)',
},
{
class: 'mini_quick_panel_row',
'layer0.tint': 'var(quickPanelRowBg)',
'layer0.opacity': 0.0,
},
{
class: 'text_line_control',
parents: [{ class: 'overlay_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size_lg)',
},
{
class: 'text_line_control',
parents: [{ class: 'switch_project_window' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size_lg)',
},
{
class: 'mini_quick_panel_row',
attributes: ['hover'],
'layer0.opacity': 0.5,
},
{
class: 'mini_quick_panel_row',
attributes: ['selected'],
'layer0.opacity': 1.0,
},
{
class: 'quick_panel_row',
'layer0.tint': 'var(quickPanelRowBg)',
'layer0.opacity': 0.0,
},
{
class: 'quick_panel_row',
attributes: ['hover'],
'layer0.opacity': 0.5,
},
{
class: 'quick_panel_row',
attributes: ['selected'],
'layer0.opacity': 1.0,
},
{
class: 'quick_panel_label',
fg: 'var(quickPanelPathFg)',
match_fg: 'var(quickPanelPathFgMatch)',
selected_fg: 'var(quickPanelPathFgSelected)',
selected_match_fg: 'var(quickPanelPathFgSelectedMatch)',
},
{
class: 'quick_panel_label',
parents: [{ class: 'mini_quick_panel_row' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size_lg)',
},
{
class: 'quick_panel_path_label',
fg: 'var(quickPanelPathFg)',
match_fg: 'var(quickPanelPathFgMatch)',
selected_fg: 'var(quickPanelPathFgSelected)',
selected_match_fg: 'var(quickPanelPathFgSelectedMatch)',
},
{
class: 'quick_panel_label preview',
fg: 'var(previewFg)',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
},
{
class: 'quick_panel_label command',
'font.italic': true,
},
// Quick Panel
// - Right Side Labels (e.g. Build 2009)
{
class: "quick_panel_label hint",
color: "color(var(--foreground) a(- 50%))"
},
// Quick Panel
// - Right Side Command Labels (e.g. ⌘ + p)
{
class: "quick_panel_label key_binding",
color: "color(var(--foreground) a(- 50%))"
},
// Header
{
class: 'title_bar',
fg: 'var(headerFg)',
bg: 'var(headerBg)',
style: 'var(titleBarStyle)',
},
{
class: 'title_bar',
attributes: ['panel_visible'],
bg: 'var(headerBg)',
},
{
class: 'header',
'layer0.tint': 'var(headerBg)',
'layer0.opacity': 1.0,
content_margin: [0, 2, 0, 2],
},
{
class: 'search_dialog',
'layer0.tint': 'var(headerBg)',
'layer0.opacity': 1.0,
content_margin: [4, 0, 4, 4],
},
{
class: 'search_text_control',
// 'layer0.texture': 'Theme - Merge/input.png',
'layer0.opacity': 1.0,
"layer0.tint": "var(accentLighter)",
'layer0.inner_margin': 4,
content_margin: 2,
},
{
class: 'search_bar',
spacing: 4,
},
{
class: 'info_area',
// 'layer0.texture': 'Theme - Merge/button.png',
'layer0.tint': 'var(accentLighter)',
'layer0.opacity': 0.4,
'layer0.inner_margin': 4,
content_margin: [36, 0],
icon_spacing: [2, 1],
min_size: [220, 27],
},
{
class: 'info_area',
attributes: ['hover'],
'layer0.opacity': 1.0,
'layer0.tint': 'var(accentLighter)',
},
{
class: 'label_control',
parents: [{ class: 'info_area' }],
shadow_color: 'var(infoShadow)',
shadow_offset: [0, 0],
},
{
class: 'info_area_line',
spacing: 4,
},
{
class: 'failed_label',
parents: [{ class: 'info_area' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(failedLabelFg)',
background_color: 'var(failed_label_bg)',
},
{
class: 'progress_bar_control',
parents: [{ class: 'info_area' }],
// 'layer0.texture': 'Theme - Merge/progress_bar_bottom.png',
'layer0.inner_margin': [2, 0, 2, 2],
'layer0.tint': 'var(background)',
'layer0.opacity': 1.0,
},
{
class: 'progress_gauge_control',
parents: [{ class: 'info_area' }],
// 'layer0.texture': 'Theme - Merge/progress_bar_bottom.png',
'layer0.inner_margin': [2, 0, 2, 2],
'layer0.tint': 'var(foreground)',
'layer0.opacity': 1.0,
content_margin: [0, 2],
},
{
class: 'git_output_button',
// 'layer0.texture': 'Theme - Merge/icon_output_border.png',
'layer0.tint': 'var(foreground)',
'layer0.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
// 'layer1.texture': 'Theme - Merge/icon_output_prompt.png',
'layer1.tint': 'var(foreground)',
'layer1.opacity': {
target: 0.6,
speed: 4.0,
interpolation: 'smoothstep',
},
// 'layer2.texture': 'Theme - Merge/icon_output_none.png',
'layer2.tint': 'var(foreground)',
'layer2.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
content_margin: [13, 8, 12, 8],
},
{
class: 'git_output_button succeeded',
'layer2.tint': 'var(outputSucceededFg)',
// 'layer2.texture': 'Theme - Merge/icon_output_succeeded.png',
},
{
class: 'git_output_button failed',
'layer2.tint': 'var(outputFailedFg)',
// 'layer2.texture': 'Theme - Merge/icon_output_failed.png',
},
{
class: 'git_output_button running',
'layer2.tint': 'var(outputRunningFg)',
// 'layer2.texture': 'Theme - Merge/icon_output_running.png',
},
{
class: 'git_output_button cancelled',
'layer2.tint': 'var(outputCanceledFg)',
// 'layer2.texture': 'Theme - Merge/icon_output_cancelled.png',
},
{
class: 'git_output_button',
attributes: ['hover'],
'layer0.opacity': {
target: 0.6,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer2.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'toggle_diverged_banner_button',
'layer0.texture': 'Theme - Merge/icon_diverged_exclamation.png',
'layer0.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer0.tint': 'var(diverged_icon_fg)',
'layer1.texture': 'Theme - Merge/icon_diverged_filled.png',
'layer1.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.tint': 'var(diverged_icon_bg)',
content_margin: [11, 8, 10, 8],
},
{
class: 'toggle_diverged_banner_button hide',
'layer0.opacity': {
target: 0.4,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer0.tint': 'var(foreground)',
'layer1.texture': 'Theme - Merge/icon_diverged_border.png',
'layer1.opacity': {
target: 0.4,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.tint': 'var(foreground)',
},
{
class: 'toggle_diverged_banner_button',
attributes: ['hover'],
'layer0.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'toggle_diverged_banner_button hide',
attributes: ['hover'],
'layer0.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
},
// Header buttons
{
class: 'button_control',
parents: [{ class: 'header' }],
'layer1.tint': 'var(headerButtonBg)',
},
{
class: 'button_control_right',
parents: [{ class: 'header' }],
'layer3.tint': 'var(headerBg)',
'layer3.opacity': 0.35,
},
{
class: 'load_diff_icon_container',
min_size: [10, 27],
},
{
class: 'button_control icon_button',
'layer0.tint': 'var(background)',
'layer0.opacity': 1.0,
content_margin: 0,
min_size: [10, 27],
},
{
class: 'button_control icon_button search_close',
content_margin: 0,
min_size: [10, 27],
},
{
class: 'button_control icon_button search_history_dropdown',
content_margin: 0,
min_size: [10, 27],
},
{
class: 'button_control_right icon_button',
content_margin: 0,
min_size: [20, 27],
},
{
class: 'button_control_left icon_button',
content_margin: 0,
min_size: [20, 27],
},
{
class: 'button_control icon_button file_button',
content_margin: 0,
min_size: [110, 27],
},
{
class: 'icon_side_bar',
'layer0.texture': 'Theme - Merge/icon_side_bar.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_side_bar',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_table_of_contents',
'layer0.texture': 'Theme - Merge/icon_toc.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_table_of_contents',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_back',
'layer0.texture': 'Theme - Merge/icon_back.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_back',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_forward',
'layer0.texture': 'Theme - Merge/icon_forward.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_forward',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_stash',
'layer0.texture': 'Theme - Merge/icon_stash.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_stash',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_full_context',
parents: [{ class: 'file_diff_hunk_container', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacity)',
},
{
class: 'icon_full_context',
parents: [{ class: 'icon_button', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_pop_stash',
'layer0.texture': 'Theme - Merge/icon_pop_stash.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_pop_stash',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_search',
'layer0.texture': 'Theme - Merge/icon_search.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_search',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_more',
'layer0.texture': 'Theme - Merge/icon_more.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_more',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_pull',
'layer0.texture': 'Theme - Merge/icon_pull.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_pull',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_push',
'layer0.texture': 'Theme - Merge/icon_push.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [15, 13],
},
{
class: 'icon_push',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_options_dropdown',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [8, 13],
},
{
class: 'icon_options_dropdown',
parents: [{ class: 'button_control', attributes: ['hover'] }],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'recent_commit_messages icon_options_dropdown',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [8, 13],
},
{
class: 'icon_cancel',
'layer0.texture': 'Theme - Merge/icon_cancel.png',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [9, 8],
},
{
class: 'icon_cancel',
attributes: ['hover'],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_dropdown_button',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [9, 8],
},
{
class: 'icon_dropdown_button',
attributes: ['hover'],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'tab_close_button',
'layer0.opacity': 'var(iconButtonOpacity)',
'layer0.tint': 'var(foreground)',
content_margin: [9, 8],
},
{
class: 'tab_close_button',
attributes: ['hover'],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_visible',
'layer0.texture': 'Theme - Merge/icon_visible.png',
'layer0.opacity': 'var(iconButtonOpacityHidden)',
'layer0.tint': 'var(foreground)',
content_margin: [8, 5],
},
// Merge Helper
{
class: 'merge_helper_container',
'layer0.tint': 'var(quickPanelBg)',
'layer0.opacity': 1.0,
content_margin: 8,
spacing: 16,
},
{
class: 'merge_options_container',
spacing: 4,
},
{
class: 'merge_helper_buttons_container',
spacing: 4,
},
{
class: 'merge_helper_help_text_label',
fg: 'color(var(labelColor) a(0.5))',
},
{
class: 'merge_helper_highlight_label',
background_color: 'var(divergedBg)',
fg: "var(accentLightest)"
},
// Diverged banner
{
class: 'diverged_container',
'layer0.opacity': 1.0,
'layer0.tint': 'var(divergedBg)',
content_margin: [4, 4, 4, 4],
},
{
class: 'diverged_button_container',
spacing: 4,
},
{
class: 'label_control',
parents: [{ class: 'diverged_container' }],
fg: 'var(divergedButtonFg)',
shadow_color: 'var(highlightedButtonShadow)',
shadow_offset: [0, 0],
},
{
class: 'button_control',
parents: [{ class: 'diverged_container' }],
'layer1.tint': 'var(divergedButtonBg)',
},
// Highlighted buttons
{
class: 'button_control',
attributes: ['highlighted'],
'layer1.tint': 'var(highlightedButtonLightBg)',
},
{
class: 'button_control',
attributes: ['highlighted', 'dark'],
'layer1.tint': 'var(highlightedButtonDarkBg)',
},
{
class: 'button_control icon_button',
attributes: ['highlighted'],
content_margin: 0,
min_size: [10, 27],
},
{
class: 'label_control',
parents: [{ class: 'button_control', attributes: ['highlighted'] }],
fg: 'var(highlightedButtonDarkFg)',
shadow_color: 'var(highlightedButtonShadow)',
},
{
class: 'label_control',
parents: [
{ class: 'button_control', attributes: ['highlighted', 'dark'] },
],
fg: 'var(highlightedButtonDarkFg)',
},
// Side bar
{
class: 'side_bar_container',
'layer0.tint': 'var(sideBarContainerBg)',
'layer0.opacity': 1.0,
content_margin: 0,
},
{
class: 'side_bar_container with_graph',
'layer0.tint': 'var(sideBarContainerBgWithGraph)',
},
{
class: 'tab_body_container',
settings: ['overlay_scroll_bars'],
content_margin: [0, 4],
},
{
class: 'scroll_area_control',
parents: [{ class: 'side_bar_container' }],
settings: ['overlay_scroll_bars'],
top_shadow: 'var(scrollShadow)',
top_shadow_size: 8,
},
{
class: 'scroll_bar_control',
parents: [{ class: 'side_bar_container' }],
'layer0.opacity': 0.0,
},
{
class: 'scroll_track_control',
parents: [{ class: 'side_bar_container' }],
'layer0.texture': 'Theme - Merge/light_scroll_bar.png',
},
{
class: 'puck_control',
parents: [{ class: 'side_bar_container' }],
'layer0.texture': 'Theme - Merge/light_scroll_puck.png',
},
{
class: 'location_bar_label',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.bold': false,
color: 'var(locationBarFg)',
},
{
class: 'location_bar_label',
attributes: ['selected'],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.bold': true,
color: 'var(locationBarFg)',
},
{
class: 'location_bar_heading',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.bold': true,
color: 'var(locationBarFg)',
shadow_color: 'var(location_bar_heading_shadow)',
shadow_offset: [0, 0],
},
{
class: 'location_bar_tree',
row_padding: [6, 2, 2, 2],
indent: 12,
indent_offset: 13,
indent_top_level: true,
dark_content: false,
},
{
class: 'location_bar_tree',
settings: ['overlay_scroll_bars'],
row_padding: [6, 2, 8, 2],
},
{
class: 'location_bar_row',
'layer0.tint': 'var(locationBarRowBg)',
'layer0.opacity': 0.0,
},
{
class: 'location_bar_row',
attributes: ['hover'],
'layer0.tint': 'var(locationBarRowBgHover)',
'layer0.opacity': 1.0,
},
{
class: 'location_bar_row',
attributes: ['selected'],
'layer0.tint': 'var(locationBarRowBgHover)',
'layer0.opacity': 1.0,
},
{
class: 'branch_stat',
'layer0.texture': 'Theme - Merge/annotation.png',
'layer0.tint': 'var(branchStatsLabelBg)',
'layer0.opacity': 1.0,
'layer0.inner_margin': 4,
content_margin: [4, 0, 3, 0],
},
{
class: 'branch_stat left',
'layer0.texture': 'Theme - Merge/annotation_left.png',
content_margin: [4, 0, 2, 0],
},
{
class: 'branch_stat right',
'layer0.texture': 'Theme - Merge/annotation_right.png',
content_margin: [4, 0, 3, 0],
},
{
class: 'branch_stats_meta',
spacing: 1,
},
{
class: 'branch_stat_meta',
spacing: 1,
},
{
class: 'submodule_stat',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(submodule_stat_fg)',
background_color: 'var(submodule_stat_bg)',
},
{
class: 'branch_stat_label',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'color(var(fileAnnFg) a(0.8))',
},
{
class: 'icon_behind',
'layer0.texture': 'Theme - Merge/icon_behind.png',
'layer0.tint': 'var(fileAnnIconBehindFg)',
'layer0.opacity': 1.0,
content_margin: [4, 5, 5, 5],
},
{
class: 'icon_ahead',
'layer0.texture': 'Theme - Merge/icon_ahead.png',
'layer0.tint': 'var(fileAnnIconAheadFg)',
'layer0.opacity': 1.0,
content_margin: [4, 5, 5, 5],
},
{
class: 'button_control icon_button not_filtering search_refs',
'layer1.tint': 'var(background)',
},
{
class: 'button_control icon_button filtering search_refs',
'layer1.tint': 'var(background)',
},
{
class: "filter_button",
"layer1.tint": "var(tabBackground)"
},
{
class: "icon_filter",
parents: [
{
class: "button_control icon_button filter_button"
}
],
"layer1.tint": "var(foreground)"
},
{
class: "icon_filter",
parents: [
{
class: "button_control icon_button filter_button"
}
],
"layer0.tint": "var(foreground)"
},
{
class: "icon_filter",
parents: [
{
class: "button_control icon_button filter_button",
attributes: [
"hover"
]
}
],
"layer0.tint": "var(foreground)"
},
{
class: "icon_filter",
parents: [
{
class: "button_control icon_button filter_button",
attributes: [
"selected"
]
}
],
"layer0.opacity": 0.25,
"layer1.opacity": 0.75,
"layer1.tint": "var(foreground)",
},
{
class: 'location_bar_branch_row',
spacing: 4,
},
{
class: 'button_control icon_button transparent',
min_size: 0,
content_margin: [2, 2],
'layer1.opacity': 0,
'layer0.tint': 'var(transparent)',
'layer1.tint': 'var(transparent)',
'layer2.tint': 'var(transparent)',
},
{
class: 'icon_visible',
parents: [
{
class: 'side_bar_container',
attributes: ['hover'],
},
],
'layer0.opacity': 'var(iconButtonOpacity)',
},
{
class: 'icon_visible',
attributes: ['hover'],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_hidden',
'layer0.opacity': 'var(iconButtonOpacityFaded)',
'layer0.tint': 'var(foreground)',
'layer1.opacity': 'var(iconButtonOpacity)',
'layer1.tint': 'var(hiddenSlash)',
content_margin: [8, 5],
},
{
class: 'icon_hidden',
attributes: ['hover'],
'layer0.opacity': 'var(iconButtonOpacityHover)',
'layer1.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'icon_uninitialized_submodule',
'layer0.opacity': 1,
'layer0.tint': 'var(iconUninitializedSubmodule)',
content_margin: [8, 5],
},
{
class: 'icon_section_actions',
'layer0.opacity': 'var(iconButtonOpacityHidden)',
'layer0.tint': 'var(foreground)',
content_margin: [10, 7],
},
{
class: 'icon_section_actions',
parents: [
{
class: 'side_bar_container',
attributes: ['hover'],
},
],
'layer0.opacity': 'var(iconButtonOpacity)',
},
{
class: 'icon_section_actions',
attributes: ['hover'],
'layer0.opacity': 'var(iconButtonOpacityHover)',
},
{
class: 'side_bar_tabs',
'layer0.tint': 'var(tabBarBg)',
'layer0.opacity': 1.0,
},
{
class: 'table_of_contents_heading_container',
spacing: 8,
},
{
class: 'table_of_contents_view_style',
content_margin: 4,
},
{
class: 'table_of_contents_tree',
row_padding: [6, 2, 2, 2],
indent: 12,
indent_offset: 13,
indent_top_level: true,
dark_content: false,
},
{
class: 'table_of_contents_tree',
settings: ['overlay_scroll_bars'],
row_padding: [6, 2, 8, 2],
},
{
class: 'table_of_contents_label',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(tableOfContentsFg)',
},
{
class: 'table_of_contents_row_container',
'layer0.tint': 'var(tableOfContentsRowBg)',
'layer0.opacity': 0.0,
},
{
class: 'table_of_contents_row_container',
attributes: ['hover'],
'layer0.tint': 'var(tableOfContentsRowBgHover)',
'layer0.opacity': 1.0,
},
{
class: 'table_of_contents_row_container',
attributes: ['selected'],
'layer0.tint': 'var(tableOfContentsRowBgHover)',
'layer0.opacity': 1.0,
},
{
class: 'table_of_contents_heading',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.bold': true,
color: 'var(locationBarFg)',
shadow_color: 'var(location_bar_heading_shadow)',
shadow_offset: [0, 0],
},
// Commit list
{
class: 'scroll_bar_control',
parents: [{ class: 'commit_table_container' }],
'layer0.opacity': 0.0,
},
{
class: 'scroll_track_control',
parents: [{ class: 'commit_table_container' }],
},
{
class: 'puck_control',
parents: [{ class: 'commit_table_container' }],
},
{
class: 'commit_table',
row_padding: [0, 0],
dark_content: true,
},
{
class: 'commit_summary_control',
'layer0.tint': 'var(commitRowBgHover)',
'layer0.opacity': 0.0,
content_margin: [8, 8, 4, 8],
},
{
class: 'commit_summary_control',
parents: [{ class: 'commit_table_row', attributes: ['hover'] }],
'layer0.opacity': 1.0,
},
{
class: 'commit_summary_control',
parents: [{ class: 'commit_table_row', attributes: ['selected'] }],
'layer0.opacity': 1.0,
},
{
class: 'commit_edges_control',
num_colors: 6,
color0: 'var(commitEdge0)',
color1: 'var(commitEdge1)',
color2: 'var(commitEdge2)',
color3: 'var(commitEdge3)',
color4: 'var(commitEdge4)',
color5: 'var(commitEdge5)',
},
{
class: 'index_files_label',
parents: [{ class: 'commit_summary_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(commitSummaryFgPrimary)',
},
{
class: 'index_action_label',
parents: [{ class: 'commit_summary_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.italic': true,
color: 'var(commitSummaryFgSecondary)',
},
{
class: 'message_label',
parents: [{ class: 'commit_summary_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.bold': false,
color: 'var(commitSummaryFgPrimary)',
},
{
class: 'message_label',
attributes: ['highlighted'],
'font.bold': true,
},
{
class: 'author_label',
parents: [{ class: 'commit_summary_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.italic': true,
color: 'var(commitSummaryFgSecondary)',
},
{
class: 'time_label',
parents: [{ class: 'commit_summary_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.italic': true,
color: 'var(commitSummaryFgSecondary)',
},
{
class: 'commit_file_name_label',
parents: [{ class: 'commit_summary_control' }],
'font.size': 'var(font_size)',
'font.italic': true,
color: 'var(commitSummaryFgPrimary)',
indent: 16,
},
{
class: 'commit_file_path_label',
parents: [{ class: 'commit_summary_control' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.italic': true,
color: 'var(commitSummaryFgSecondary)',
indent: 16,
},
// Annotations
{
class: 'commit_annotation branch head',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(headAnnFg)',
background_color: 'var(headAnnBg)',
},
{
class: 'commit_annotation branch',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(branchAnnFg)',
background_color: 'var(branchAnnBg)',
},
{
class: 'commit_annotation remote',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(remoteAnnFg)',
background_color: 'var(remoteAnnBg)',
},
{
class: "condensed_branch_annotation_container",
background_color: "var(purple)"
},
{
class: "condensed_branch_annotation",
fg: "var(background)"
},
{
class: "condensed_branch_icon",
"layer0.tint": "var(background)"
},
{
class: 'tag_annotation_container',
background_color: 'var(tagAnnBg)',
},
{
class: 'tag_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(tagAnnFg)',
},
{
class: 'stash_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(stashAnnFg)',
background_color: 'var(stashAnnBg)',
},
{
class: 'file_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
color: 'var(fileAnnFg)',
background_color: 'var(fileAnnBg)',
},
{
class: 'submodule_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
fg: 'var(submoduleAnnFg)',
background_color: 'var(submoduleAnnBg)',
},
{
class: 'submodule_light_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
fg: 'var(submoduleLightAnnFg)',
background_color: 'var(submoduleLightAnnBg)',
},
{
class: 'inserted_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
fg: 'var(labelColor)',
background_color: 'var(insertedAnnBg)',
},
{
class: 'deleted_annotation',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
fg: 'var(labelColor)',
background_color: 'var(deletedAnnBg)',
},
// Search panel
{
class: 'search_message',
content_margin: [14, 14, 14, 14],
},
{
class: 'search_help',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
background_color: 'var(background)',
headline_color: 'color(var(foreground) l(+ 10%))',
color: 'var(foreground)',
content_margin: [14, 8, 14, 14],
},
// {
// class: 'searching',
// 'layer0.texture': {
// keyframes: [
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_12.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_02.png',
// ],
// loop: true,
// frame_time: 0.05,
// },
// 'layer0.opacity': 1.0,
// 'layer0.tint': 'var(loadingBall1)',
// 'layer1.texture': {
// keyframes: [
// 'Theme - Merge/loading_13.png',
// 'Theme - Merge/loading_12.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_02.png',
// 'Theme - Merge/loading_01.png',
// 'Theme - Merge/loading_02.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_12.png',
// ],
// loop: true,
// frame_time: 0.05,
// },
// 'layer1.opacity': 1.0,
// 'layer1.tint': 'var(loadingBall2)',
// 'layer2.texture': {
// keyframes: [
// 'Theme - Merge/loading_01.png',
// 'Theme - Merge/loading_02.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_12.png',
// 'Theme - Merge/loading_13.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// ],
// loop: true,
// frame_time: 0.05,
// },
// 'layer2.opacity': 1.0,
// 'layer2.tint': 'var(loadingBall1)',
// content_margin: [11, 5],
// },
// Blame panel
{
class: 'blame_commit_summary',
content_margin: [8, 8, 8, 8],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
background_color: 'var(accentLight)',
link_color: 'var(blue)',
color: 'var(--foreground)',
},
{
class: 'blame_text_control',
settings: ['!kelly_colors'],
num_colors: 6,
color0: 'color(var(red) s(80%))',
color1: 'color(color(var(orange) s(100%)) s(80%))',
color2: 'color(var(yellow) s(80%))',
color3: 'color(color(var(cyan) l(35%)) s(80%))',
color4: 'color(color(var(blue) l(60%)) s(80%))',
color5: 'color(color(var(purple) s(80%) l(65%)) s(80%))',
},
{
class: 'blame_text_control',
settings: ['kelly_colors'],
num_colors: 17,
color0: 'rgb(128, 62, 117)',
color1: 'rgb(166, 189, 215)',
color2: 'rgb(193, 0, 32)',
color3: 'rgb(206, 162, 98)',
color4: 'rgb(129, 112, 102)',
color5: 'rgb(0, 125, 52)',
color6: 'rgb(246, 118, 142)',
color7: 'rgb(0, 83, 138)',
color8: 'rgb(255, 122, 92)',
color9: 'rgb(255, 142, 0)',
color10: 'rgb(179, 40, 81)',
color11: 'rgb(244, 200, 0)',
color12: 'rgb(127, 24, 13)',
color13: 'rgb(147, 170, 0)',
color14: 'rgb(89, 51, 21)',
color15: 'rgb(241, 58, 19)',
color16: 'rgb(35, 44, 22)',
},
// Detail panel
{
class: 'details_panel',
'layer0.tint': 'var(detailPanelBg)',
'layer0.opacity': 1.0,
},
{
class: 'scroll_area_control',
parents: [{ class: 'side_bar_container' }],
content_margin: [0, 4, 0, 0],
},
{
class: 'scroll_area_control',
parents: [{ class: 'side_bar_container' }],
settings: ['overlay_scroll_bars'],
content_margin: 0,
},
{
class: 'scroll_area_control',
parents: [{ class: 'details_panel' }],
settings: ['overlay_scroll_bars'],
},
{
class: 'scroll_bar_control',
parents: [{ class: 'details_panel' }],
settings: ['!overlay_scroll_bars'],
content_margin: [4, 4, 4, 4],
'layer0.opacity': 1.0,
'layer0.tint': 'var(detailPanelBg)',
},
{
class: 'scroll_bar_control',
parents: [{ class: 'commit_dialog_section_container' }],
content_margin: [4, 0, 4, 4],
},
{
class: 'scroll_bar_control',
parents: [{ class: 'commit_dialog_summary_container' }],
content_margin: [4, 0, 4, 4],
},
{
class: 'commit_dialog_section_container',
content_margin: [0, 4, 0, 0],
},
{
class: 'commit_dialog_summary_container',
content_margin: [0, 4, 0, 0],
},
{
class: 'scroll_corner_control',
parents: [{ class: 'details_panel' }],
settings: ['!overlay_scroll_bars'],
'layer0.opacity': 1.0,
'layer0.tint': 'var(detailPanelBg)',
},
{
class: 'diff scroll_area_control',
overlay: true,
},
{
class: 'diff scroll_area_control',
settings: ['!overlay_scroll_bars'],
hover_reveal: true,
},
{
class: 'scroll_bar_control',
parents: [{ class: 'details_panel' }, { class: 'diff' }],
'layer0.opacity': 0.0,
},
{
class: 'commit_dialog_header',
content_margin: [0, 2, 0, 0],
},
{
class: 'scroll_bar_control',
parents: [{ class: 'commit_dialog_header' }],
settings: ['!overlay_scroll_bars'],
content_margin: [4, 0, 0, 0],
},
{
class: 'scroll_bar_control',
parents: [{ class: 'commit_dialog_header' }],
settings: ['overlay_scroll_bars'],
content_margin: [4, 0, 4, 0],
},
{
class: 'scroll_area_control',
parents: [{ class: 'commit_dialog_header' }],
},
{
class: 'commit_message_container',
'layer0.tint': '#f00',
'layer0.opacity': 1.0,
content_margin: [4, 4, 4, 8],
spacing: 6,
},
{
class: 'recent_commit_messages_dropdown_container',
content_margin: [2, 0],
},
{
class: 'commit_metadata_container',
content_margin: [6, 6, 4, 6],
message_content_margin: [0, 4, 0, 4],
'layer0.tint': '#f0f',
'layer0.opacity': 1.0,
spacing: 6,
},
{
class: 'sidebar_commit_metadata_container',
min_size: [0, 180],
},
{
class: 'commit_metadata_standin',
'layer0.tint': 'var(background)',
'layer0.opacity': 0.0,
content_margin: [0, 4, 0, 0],
},
{
class: 'show_contents_container',
content_margin: 8,
},
{
class: 'edit_button_container',
spacing: 4,
},
{
class: 'field_name_label',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
'font.italic': true,
'font.bold': true,
color: 'var(foreground)',
},
{
class: 'separator_container',
content_margin: [12, 12, 12, 12],
},
{
class: 'terminator',
// 'layer0.texture': 'Theme - Merge/terminator.png',
'layer0.tint': 'color(var(terminatorFg) a(0.25))',
'layer0.opacity': 1.0,
content_margin: [16, 4, 16, 4],
},
{
class: "terminator",
attributes: ["hover"],
"layer0.tint": "color(var(terminatorFg) a(0.50))",
"layer0.opacity": 1,
},
{
class: 'terminator_container',
content_margin: [12, 12, 12, 12],
},
{
class: 'label_control good_signature',
color: 'var(green)',
},
{
class: 'label_control bad_signature',
color: 'var(red)',
},
// {
// class: 'loading',
// 'layer0.texture': {
// keyframes: [
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_12.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_02.png',
// ],
// loop: true,
// frame_time: 0.05,
// },
// 'layer0.opacity': 1.0,
// 'layer0.tint': 'var(loadingBall1)',
// 'layer1.texture': {
// keyframes: [
// 'Theme - Merge/loading_13.png',
// 'Theme - Merge/loading_12.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_02.png',
// 'Theme - Merge/loading_01.png',
// 'Theme - Merge/loading_02.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_12.png',
// ],
// loop: true,
// frame_time: 0.05,
// },
// 'layer1.opacity': 1.0,
// 'layer1.tint': 'var(loadingBall2)',
// 'layer2.texture': {
// keyframes: [
// 'Theme - Merge/loading_01.png',
// 'Theme - Merge/loading_02.png',
// 'Theme - Merge/loading_03.png',
// 'Theme - Merge/loading_04.png',
// 'Theme - Merge/loading_05.png',
// 'Theme - Merge/loading_06.png',
// 'Theme - Merge/loading_07.png',
// 'Theme - Merge/loading_08.png',
// 'Theme - Merge/loading_09.png',
// 'Theme - Merge/loading_10.png',
// 'Theme - Merge/loading_11.png',
// 'Theme - Merge/loading_12.png',
// 'Theme - Merge/loading_13.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// 'Theme - Merge/loading_00.png',
// ],
// loop: true,
// frame_time: 0.05,
// },
// 'layer2.opacity': 1.0,
// 'layer2.tint': 'var(loadingBall1)',
// content_margin: [11, 5],
// },
// File diffs
{
class: 'single_file',
content_margin: [6, 6, 6, 6],
},
{
class: 'file_diff_control',
spacing: 0,
content_margin: [0, 0, 0, 1],
},
{
class: 'file_diff_control',
attributes: ['expanded'],
content_margin: [0, 0, 0, 6],
},
{
class: 'expand_all_diff_control untracked',
content_margin: [0, 0, 0, 1],
},
{
class: 'file_diff_header',
'layer0.tint': 'var(fileHeaderBg)',
'layer0.opacity': 1.0,
content_margin: 4,
},
{
class: 'file_diff_header collapsible',
attributes: ['hover'],
'layer0.tint': 'var(fileHeaderBgHover)',
},
{
class: 'file_diff_header',
parents: [{ class: 'expand_all_diff_control' }],
spacing: 4,
content_margin: [4, 4, 4, 4],
},
{
class: 'file_diff_header',
parents: [{ class: 'expand_all_diff_control detail' }],
'layer0.tint': 'var(detailPanelBg)',
},
{
class: 'file_diff_header',
parents: [{ class: 'expand_all_diff_control working' }],
'layer0.tint': 'var(detailPanelBg)',
},
{
class: 'onion_skin_slider',
puck_border_color: 'var(accentLighter)',
puck_color: 'var(foreground)',
track_color: 'var(accentLight)',
},
{
class: "image_metadata_label",
background_color: "var(accentLightest)",
fg: "var(foreground)"
},
{
class: 'button_control all_button',
// 'layer0.texture': 'Theme - Merge/button_outline.png',
'layer0.draw_center': false,
'layer0.tint': 'var(buttonBg)',
'layer0.inner_margin': 4,
'layer0.opacity': {
target: 0.4,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.opacity': {
target: 0.2,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'button_control all_button',
attributes: ['hover'],
'layer0.opacity': {
target: 0.0,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer1.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'file_diff_header',
parents: [{ class: 'expand_all_diff_control staged' }],
'layer0.tint': 'var(detailPanelBg)',
},
{
class: 'file_diff_header',
parents: [{ class: 'expand_all_diff_control untracked' }],
'layer0.tint': 'var(untrackedHeaderBg)',
},
{
class: 'file_diff_header collapsible',
parents: [{ class: 'expand_all_diff_control untracked' }],
attributes: ['hover'],
'layer0.tint': 'var(untrackedHeaderBgHover)',
},
{
class: 'file_diff_header',
parents: [{ class: 'file_diff_control unmerged' }],
'layer0.tint': 'var(unmergedHeaderBg)',
},
{
class: 'file_diff_header collapsible',
parents: [{ class: 'file_diff_control unmerged' }],
attributes: ['hover'],
'layer0.tint': 'var(unmergedHeaderBgHover)',
},
{
class: 'file_diff_header',
parents: [{ class: 'file_diff_control untracked' }],
'layer0.tint': 'var(untrackedHeaderBg)',
content_margin: [20, 4, 4, 4],
},
{
class: 'file_diff_header collapsible',
parents: [{ class: 'file_diff_control untracked' }],
attributes: ['hover'],
'layer0.tint': 'var(untrackedHeaderBgHover)',
},
{
class: 'file_meta',
spacing: 5,
},
{
class: 'icon_deleted',
// 'layer0.texture': 'Theme - Merge/icon_deleted.png',
'layer0.tint': 'var(deletedIconFg)',
'layer0.opacity': 1.0,
content_margin: [10, 9, 10, 9],
},
{
class: 'icon_created',
// 'layer0.texture': 'Theme - Merge/icon_staged.png',
'layer0.tint': 'var(createdIconFg)',
'layer0.opacity': 1.0,
content_margin: [10, 9, 10, 9],
},
{
class: 'icon_unmerged',
// 'layer0.texture': 'Theme - Merge/icon_unmerged.png',
'layer0.tint': 'var(unmergedIconFg)',
'layer0.opacity': 1.0,
content_margin: [10, 9, 10, 9],
},
{
class: 'icon_recent',
'layer0.texture': 'Theme - Merge/icon_recent_bg.png',
'layer0.tint': 'var(recentIconBg)',
'layer0.opacity': 1.0,
'layer1.texture': 'Theme - Merge/icon_recent.png',
'layer1.tint': 'var(recentIconFg)',
'layer1.opacity': 1.0,
content_margin: [10, 9, 10, 9],
},
{
class: 'table_of_contents_icon',
content_margin: [10, 9, 10, 9],
},
{
class: 'icon_staged',
// 'layer0.texture': 'Theme - Merge/icon_staged.png',
'layer0.tint': 'var(stagedIconFg)',
'layer0.opacity': 1.0,
content_margin: [10, 9, 10, 9],
},
{
class: 'icon_text',
color: 'var(foreground)',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
},
{
class: 'total_untracked',
content_margin: [4, 0, 4, 0],
},
{
class: 'recently_modified',
content_margin: [5, 0, 0, 0],
},
{
class: 'file_icons',
spacing: 1,
},
{
class: 'file_icon',
// 'layer0.texture': 'Theme - Merge/button.png',
'layer0.tint': 'var(fileIconBg)',
'layer0.opacity': 1.0,
'layer0.inner_margin': [4, 4, 4, 4],
min_size: [0, 18],
},
{
class: 'file_icon_left',
// 'layer0.texture': 'Theme - Merge/button_left.png',
},
{
class: 'file_icon_right',
// 'layer0.texture': 'Theme - Merge/button_right.png',
},
{
class: 'table_of_contents_icon_wrapper',
content_margin: [8, 0],
},
{
class: 'label_control',
parents: [{ class: 'file_diff_header' }],
"font.bold": true,
shadow_color: 'var(file_diff_shadow)',
shadow_offset: [0, 0],
},
{
class: "eliding_label_control",
color: "var(foreground)"
},
{
class: 'eliding_label_control',
parents: [{ class: 'file_diff_header' }],
shadow_color: 'var(file_diff_shadow)',
shadow_offset: [0, 0],
},
{
class: 'label_control',
parents: [{ class: 'file_diff_header' }, { class: 'button_control' }],
shadow_color: 'var(buttonShadow)',
},
{
class: 'label_control',
parents: [
{ class: 'file_diff_header' },
{ class: 'button_control', attributes: ['confirm'] },
],
shadow_color: 'var(hazard_button_shadow)',
},
{
class: 'label_control',
parents: [{ class: 'expand_all_diff_control' }, { class: 'file_meta' }],
fg: 'var(foreground)',
},
{
class: 'renamed_file_container',
spacing: 0,
},
{
class: 'label_control inserted',
fg: 'var(renamed_file_inserted)',
},
{
class: 'label_control deleted',
fg: 'var(renamed_file_deleted)',
},
{
class: 'disclosure_button_control',
// 'layer0.texture': 'Theme - Merge/disclosure_unexpanded.png',
'layer0.opacity': {
target: 0.3,
speed: 4.0,
interpolation: 'smoothstep',
},
'layer0.tint': 'var(disclosureFg)',
content_margin: [8, 8],
},
{
class: 'disclosure_button_control',
attributes: ['expanded'],
// 'layer0.texture': 'Theme - Merge/disclosure_expanded.png',
},
{
class: 'disclosure_button_control',
attributes: ['hover'],
'layer0.opacity': {
target: 0.5,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'disclosure_button_control',
parents: [{ class: 'file_diff_header', attributes: ['hover'] }],
'layer0.opacity': {
target: 0.5,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'disclosure_button_control',
parents: [{ class: 'close' }],
// 'layer0.texture': 'Theme - Merge/icon_cancel.png',
content_margin: [9, 8],
},
{
class: 'file_diff_hunk_header',
'layer0.tint': 'var(hunkHeaderBg)',
'layer0.opacity': 1.0,
content_margin: 4,
},
{
class: 'hunk_label_container',
content_margin: [4, 0],
},
{
class: 'file_diff_hunk_container',
'layer0.tint': 'var(--background)',
'layer0.opacity': 1.0,
},
{
class: 'hunk_description_container',
content_margin: [0, 8, 0, 8],
},
// Commit dialog
{
class: 'commit_author',
color: 'var(foreground)',
},
{
class: 'commit_author_container',
content_margin: [2, 0, 0, 0],
},
{
class: 'commit_buttons',
spacing: 4,
},
{
class: 'commit_button',
min_size: [204, 15],
},
{
class: 'split_commit_button',
// The min_size is wider than commit_button because button_control
// adds the margin to the min_size, where split_commit_button
// does not have it's own margin
min_size: [224, 15],
},
// Hunk buttons
{
class: 'icon_more_hunk',
'layer0.tint': 'var(foreground)'
},
{
class: 'hunk_button',
min_size: [90, 15],
content_margin: [10, 3],
},
{
class: 'hunk_button',
parents: [
{ class: 'file_diff_hunk_container', attributes: ['!hover'] },
],
attributes: ['!confirm'],
'layer1.opacity': 0.0,
'layer2.opacity': 0.0,
},
{
class: 'hunk_button',
parents: [{ class: 'file_diff_hunk_container', attributes: ['hover'] }],
'layer1.opacity': 0.6,
},
{
class: 'hunk_button',
parents: [{ class: 'file_diff_hunk_header', attributes: ['selected'] }],
'layer1.opacity': 0.6,
},
{
class: 'hunk_button',
parents: [{ class: 'file_diff_hunk_container', attributes: ['hover'] }],
attributes: ['hover'],
'layer1.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'hunk_button',
parents: [{ class: 'file_diff_hunk_container', attributes: ['hover'] }],
attributes: ['pressed'],
'layer1.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'label_control',
parents: [
{ class: 'file_diff_hunk_container' },
{ class: 'hunk_button', attributes: ['!confirm'] },
],
fg: 'color(var(hunkButtonFg) a(0))',
shadow_offset: [0, 0],
},
{
class: 'label_control',
parents: [
{ class: 'file_diff_hunk_container', attributes: ['hover'] },
{ class: 'hunk_button', attributes: ['!confirm'] },
],
fg: 'var(hunkButtonFg)',
shadow_color: 'var(hunkButtonShadow)',
shadow_offset: [0, 0],
},
{
class: 'label_control',
parents: [
{ class: 'file_diff_hunk_header', attributes: ['selected'] },
{ class: 'hunk_button', attributes: ['!confirm'] },
],
fg: 'var(hunkButtonFg)',
shadow_color: 'var(hunkButtonShadow)',
shadow_offset: [0, 0],
},
// File Badges
{
class: 'file_badge',
// 'layer0.texture': 'Theme - Merge/button.png',
'layer0.inner_margin': [4, 4, 4, 4],
'layer0.opacity': 1.0,
min_size: [18, 18],
},
{
class: 'file_badge_split_container',
spacing: 1,
},
{
class: 'left_badge',
// 'layer0.texture': 'Theme - Merge/button_left.png',
},
{
class: 'right_badge',
// 'layer0.texture': 'Theme - Merge/button_right.png',
},
{
class: 'modified_badge',
'layer0.tint': 'var(fileBadgeModifiedBg)',
},
{
class: 'modified_badge',
parents: [{ class: 'file_diff_header', attributes: ['hover'] }],
'layer0.tint': 'var(fileBadgeModifiedHover)',
},
{
class: 'unmerged_badge',
'layer0.tint': 'var(fileBadgeUnmergedBg)',
},
{
class: 'unmerged_badge',
parents: [{ class: 'file_diff_header', attributes: ['hover'] }],
'layer0.tint': 'var(fileBadgeUnmergedHover)',
},
{
class: 'untracked_badge',
'layer0.tint': 'var(fileBadgeUntrackedBg)',
},
{
class: 'staged_badge',
'layer0.tint': 'var(fileBadgeStagedBg)',
},
{
class: 'staged_badge',
parents: [{ class: 'file_diff_header' }],
'layer0.tint': 'var(fileBadgeStagedBg)',
},
{
class: 'staged_badge',
parents: [{ class: 'file_diff_header', attributes: ['hover'] }],
'layer0.tint': 'var(fileBadgeStagedBgHover)',
},
{
class: 'label_control',
parents: [{ class: 'file_badge' }],
'font.bold': false,
},
{
class: 'label_control',
parents: [{ class: 'modified_badge' }],
fg: 'var(fileBadgeModifiedLeftFg)',
},
{
class: 'label_control',
parents: [{ class: 'unmerged_badge' }],
fg: 'var(file_badge_unmerged_fg)',
},
{
class: 'label_control',
parents: [{ class: 'untracked_badge' }],
fg: 'var(fileBadgeUntrackedFg)',
},
{
class: 'label_control',
parents: [{ class: 'staged_badge' }],
fg: 'var(fileBadgeStagedFg)',
},
{
class: 'icon_deleted',
parents: [{ class: 'modified_badge' }],
'layer0.tint': 'var(fileBadgeModifiedRightFg)',
},
{
class: 'icon_deleted',
parents: [{ class: 'staged_badge' }],
'layer0.tint': 'var(fileBadgeModifiedRightFg)',
},
// Welcome overlay
{
class: 'welcome_overlay',
'layer0.tint': 'var(overlayBg)',
'layer0.opacity': 0.9,
},
{
class: 'dialog',
parents: [{ class: 'welcome_overlay' }],
'layer0.opacity': 0.5,
},
{
class: 'welcome_overlay_contents',
'layer0.tint': 'var(welcomeBg)',
'layer0.opacity': 1.0,
// 'layer0.texture': 'Theme - Merge/button.png',
'layer0.inner_margin': 4,
spacing: 32,
content_margin: [50, 25, 50, 25],
},
{
class: 'button_control',
parents: [{ class: 'welcome_overlay_contents' }],
'layer1.tint': 'var(buttonBgWelcome)',
// 'layer1.texture': 'Theme - Merge/button.png',
'layer1.inner_margin': 4,
'layer2.opacity': 0.0,
// 'layer2.texture': 'Theme - Merge/button.png',
'layer2.inner_margin': 4,
min_size: [120, 15],
content_margin: [10, 6],
},
{
class: 'purchase_license_cta_link',
fg: 'color(var(link_label_color))',
'font.face': 'var(font_face)',
'font.bold': true,
},
{
class: 'open_new_repository_buttons_container',
content_margin: [0, 8, 0, 8],
spacing: 8,
},
{
class: 'subtitle_label_control',
fg: 'var(labelColor)',
'font.face': 'var(font_face)',
'font.size': 17,
},
{
class: 'recent_repository_row',
spacing: 4,
content_margin: [0, 4],
},
{
class: 'recent_repository_button',
'layer0.tint': 'var(recentRepositoriesRowBg)',
'layer0.opacity': 1.0,
content_margin: 4,
},
{
class: 'recent_repository_button',
attributes: ['hover'],
'layer0.tint': 'var(recentRepositoriesRowBgHover)',
'layer0.opacity': 1.0,
},
// Command History overlay
{
class: 'commit_metadata_container',
content_margin: [8, 5, 5, 5],
'layer0.tint': 'var(commitRowBgHover)',
'layer0.opacity': 0.0,
},
{
class: 'commit_table_container command_history',
'layer0.tint': 'var(commitListBg)',
'layer0.opacity': 1.0,
content_margin: 0,
},
{
class: 'commit_metadata_container',
'layer0.opacity': 1.0,
parents: [{ class: 'commit_table_row', attributes: ['selected'] }],
},
{
class: 'commit_metadata_container',
'layer0.opacity': 0.2,
parents: [{ class: 'commit_table_row', attributes: ['!selected'] }],
attributes: ['hover'],
},
{
class: 'git_output_data_container',
'layer0.tint': 'var(gitOutputPanelBg)',
'layer0.opacity': 1.0,
content_margin: [6, 6, 4, 6],
},
// Command History overlay labels
{
class: 'command_history_label',
fg: 'var(helpLabelColor)',
'font.face': 'var(font_face)',
'font.size': 15,
'font.italic': true,
},
// Preferences Page
{
class: 'preferences_overlay_left',
'layer0.tint': 'var(preferencesOverlayLeft)',
'layer0.opacity': 1.0,
content_margin: [0, 16, 0, 0],
},
{
class: 'preferences_overlay_right',
content_margin: [16, 16, 4, 16],
'layer0.tint': 'var(preferencesOverlayBg)',
'layer0.opacity': 1.0,
},
{
class: 'preferences_section_table',
row_padding: [24, 6, 12, 6],
dark_content: false,
'layer0.tint': 'var(preferencesSectionTableBg)',
'layer0.opacity': 1.0,
},
{
class: 'preferences_section_table_row',
attributes: ['hover'],
'layer0.tint': 'var(preferencesSectionTableRowBg)',
'layer0.opacity': 1.0,
content_margin: [0, 16, 0, 0],
},
{
class: 'preferences_section_table_row',
attributes: ['selected'],
'layer0.tint': 'var(preferencesSectionTableRowBg)',
'layer0.opacity': 1.0,
content_margin: [0, 16, 0, 0],
},
{
class: 'preferences_buttons_container',
content_margin: 8,
'layer0.tint': 'var(preferencesOverlayBg)',
'layer0.opacity': 1.0,
},
{
class: 'preference_wrapper',
content_margin: [4, 4, 4, 24],
spacing: 4,
},
{
class: 'preference_text_input_container',
spacing: 8,
},
// Preference Labels
{
class: 'preferences_section_label',
fg: 'var(labelColor)',
'font.face': 'var(font_face)',
'font.size': 14,
'font.bold': true,
case: 'title',
},
{
class: 'preference_help_text_label',
fg: 'var(helpLabelColor)',
'font.face': 'var(font_face)',
'font.size': 'var(font_size_sm)',
},
// Switch Repository Window
{
class: 'panel_control',
parents: [{ class: 'switch_project_window' }],
'layer0.opacity': 1.0,
'layer0.tint': 'var(switchRepoBg)',
content_margin: 2,
},
{
class: 'scroll_bar_control',
parents: [{ class: 'switch_project_window' }],
'layer0.tint': 'var(switchRepoBg)',
tint_index: -1,
},
// Tool Tips
{
class: 'tool_tip_control',
'layer0.tint': 'var(foreground)',
'layer0.opacity': 1.0,
content_margin: [8, 3, 8, 3],
},
{
class: 'tool_tip_label_control',
'font.face': 'var(font_face)',
'font.size': 'var(font_size_sm)',
fg: 'color(black)',
},
// Hints
{
class: 'hint_stem',
'layer0.opacity': 1.0,
'layer0.tint': 'var(hint_bg)',
},
{
class: 'hint_stem bottom',
// 'layer0.texture': 'Theme - Merge/hint_bottom_arrow.png',
content_margin: [6, 3, 6, 3],
},
{
class: 'hint_stem left',
// 'layer0.texture': 'Theme - Merge/hint_left_arrow.png',
content_margin: [3, 6, 3, 6],
},
{
class: 'hint_stem top',
// 'layer0.texture': 'Theme - Merge/hint_top_arrow.png',
content_margin: [6, 3, 6, 3],
},
{
class: 'hint_stem right',
// 'layer0.texture': 'Theme - Merge/hint_right_arrow.png',
content_margin: [3, 6, 3, 6],
},
{
class: 'hint_control',
'layer0.tint': 'var(hint_bg)',
'layer0.opacity': 1.0,
},
{
class: 'hint_control bottom',
'layer0.texture': 'Theme - Merge/hint_bottom_box.png',
'layer0.inner_margin': [4, 9, 4, 4],
content_margin: [8, 9, 8, 4],
},
{
class: 'hint_control left',
'layer0.texture': 'Theme - Merge/hint_left_box.png',
'layer0.inner_margin': [4, 4, 9, 4],
content_margin: [8, 4, 13, 4],
},
{
class: 'hint_control right',
'layer0.texture': 'Theme - Merge/hint_right_box.png',
'layer0.inner_margin': [9, 4, 4, 4],
content_margin: [13, 4, 8, 4],
},
{
class: 'hint_control top',
'layer0.texture': 'Theme - Merge/hint_top_box.png',
'layer0.inner_margin': [4, 4, 4, 9],
content_margin: [8, 4, 8, 9],
},
{
class: 'hint_label',
'font.face': 'var(font_face)',
'font.size': 'var(font_size_sm)',
fg: 'var(hint_fg)',
},
{
class: 'hint_control',
parents: [{ class: 'error_output' }],
'layer0.tint': 'var(error_hint_bg)',
},
{
class: 'hint_control bottom',
parents: [{ class: 'error_output' }],
// 'layer1.texture': 'Theme - Merge/hint_bottom_stripe.png',
'layer1.inner_margin': [4, 9, 4, 4],
'layer1.draw_center': false,
'layer1.tint': 'var(error_hint_accent)',
'layer1.opacity': 1.0,
content_margin: [10, 12, 10, 6],
},
{
class: 'hint_stem',
parents: [{ class: 'error_output' }],
'layer0.tint': 'var(error_hint_accent)',
},
{
class: 'hint_label',
parents: [{ class: 'error_output' }],
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
fg: 'var(error_hint_fg)',
},
// Tree View
{
class: 'scroll_bar_control',
parents: [{ class: 'tree_details' }],
content_margin: [4, 4, 4, 4],
},
{
class: 'scroll_bar_control',
parents: [{ class: 'tree_list' }],
'layer0.tint': 'color(var(commitListBg) a(0.5))',
'layer0.opacity': 1.0,
},
{
class: 'tree',
'layer0.tint': 'color(var(commitListBg) a(0.5))',
'layer0.opacity': 1.0,
row_padding: [6, 3, 6, 3],
indent: 12,
indent_offset: 13,
indent_top_level: false,
dark_content: false,
},
{
class: 'tree_row',
'layer0.tint': 'var(hunkHeaderBg)',
'layer0.opacity': 0.0,
},
{
class: 'tree_row',
attributes: ['selected'],
'layer0.opacity': 1.0,
},
// Merge Tool
{
class: 'diff_text_control',
line_selection_color: [64, 64, 177, 10],
line_selection_border_color: [64, 64, 117, 50],
line_selection_border_width: 2.0,
line_selection_border_radius: 2.0,
},
{
class: 'use_hunk_button',
'layer0.tint': 'var(hunkButtonFg)',
'layer0.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
content_margin: [10, 8],
},
{
class: 'use_hunk_button left',
// 'layer0.texture': 'Theme - Merge/icon_left_hunk.png',
},
{
class: 'use_hunk_button right',
// 'layer0.texture': 'Theme - Merge/icon_right_hunk.png',
},
{
class: 'use_hunk_button',
attributes: ['hover'],
'layer0.opacity': {
target: 1.0,
speed: 4.0,
interpolation: 'smoothstep',
},
},
// Auto Complete
{
class: 'popup_control',
'layer0.tint': [255, 255, 255],
'layer0.opacity': 1.0,
},
{
class: 'auto_complete',
row_padding: [4, 1, 4, 1],
tint_index: 0,
'layer0.opacity': 1.0,
tint_modifier: [255, 255, 255, 0.05],
},
{
class: 'auto_complete',
attributes: ['file_light'],
tint_modifier: [0, 0, 0, 0.05],
},
{
class: 'scroll_bar_control',
parents: [{ class: 'popup_control auto_complete_popup' }],
tint_modifier: [0, 0, 0, 0.05],
},
{
class: 'scroll_bar_control',
attributes: ['dark'],
parents: [{ class: 'popup_control auto_complete_popup' }],
tint_modifier: [255, 255, 255, 0.05],
},
{
class: 'auto_complete_label',
fg: [0, 0, 0, 0.0],
match_fg: [255, 255, 255, 0.18],
selected_fg: [0, 0, 0, 0.0],
selected_match_fg: [255, 255, 255, 0.18],
fg_blend: true,
},
{
class: 'auto_complete_label',
parents: [{ class: 'auto_complete', attributes: ['file_light'] }],
fg: [0, 0, 0, 0.0],
match_fg: [0, 0, 0, 0.18],
selected_fg: [0, 0, 0, 0.0],
selected_match_fg: [0, 0, 0, 0.18],
fg_blend: true,
},
{
class: 'progress_gauge_control',
parents: [{ class: 'clone_area' }],
content_margin: [0, 12],
},
{
class: 'clone_progress_container',
spacing: 4,
},
{
class: 'table_of_contents_style_container',
content_margin: [0, 8, 0, 8],
},
{
class: 'table_of_contents_style_selector',
min_size: [80, 20],
},
// Repository Tabs (Tab Bar Settings)
{
class: 'tabset_control',
'layer0.opacity': 1.0,
content_margin: [0, 0, 0, 0],
tint_index: 0,
tint_modifier: [255, 255, 255, 0.32],
tab_height: 32,
tab_width: 32,
},
{
class: 'tabset_control',
settings: ['mouse_wheel_switches_tabs', '!enable_tab_scrolling'],
mouse_wheel_switch: true,
},
{
class: 'tab_control',
content_margin: [10, 6],
'layer1.tint': 'var(repositoryTabBarBg)',
'layer1.opacity': 1.0,
'layer3.tint': 'var(repositoryTabBarBorderBg)',
// 'layer3.texture': 'Theme - Merge/tab_border.png',
'layer3.inner_margin': [16, 0, 16, 0],
'layer3.opacity': {
target: 0.2,
speed: 2.0,
interpolation: 'smoothstep',
},
},
{
class: 'tab_control',
attributes: ['selected'],
'layer1.tint': 'var(headerBg)',
tint_modifier: [255, 255, 255, 0.0],
'layer3.opacity': 0.0,
},
{
class: 'tab_control',
attributes: ['right'],
// 'layer3.texture': 'Theme - Merge/tab_border_end.png',
},
{
class: 'repository_tab_label_container',
spacing: 4,
},
{
class: 'icon_folder',
// 'layer0.texture': 'Theme - Merge/folder_closed.png',
'layer0.opacity': 0.4,
'layer0.tint': 'var(foreground)',
content_margin: [9, 8],
},
{
class: 'tab_label',
fg: 'color(var(labelColor) a(0.9))',
'font.face': 'var(font_face)',
'font.size': 'var(font_size)',
},
{
class: "tab_label",
fg: "var(tabLabelColor)",
"font.face": "var(font_face)",
"font.size": "var(font_size)"
},
{
class: "tab_label",
parents: [
{
class: "tab_control",
attributes: [
"hover"
]
}],
fg: "var(tabLabelColorHover)"
},
{
class: "close_button_control",
"layer0.tint": "var(foreground)",
},
{
class: "tab_label",
parents: [
{
class: "tab_control",
attributes: [
"selected"
]
}],
fg: "var(tabLabelColorSelected)"
},
{
class: 'tab_close_button',
settings: ['show_tab_close_buttons'],
// 'layer0.texture': 'Theme - Default/common/tab_close.png',
content_margin: [10, 9],
},
{
class: 'tab_close_button',
parents: [{ class: 'tab_control', attributes: ['!selected'] }],
'layer0.opacity': {
target: 0.3,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'tab_close_button',
parents: [{ class: 'tab_control', attributes: ['selected'] }],
'layer0.opacity': {
target: 0.5,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'tab_close_button',
attributes: ['hover'],
parents: [{ class: 'tab_control', attributes: ['!selected'] }],
'layer0.opacity': {
target: 0.6,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'tab_close_button',
attributes: ['hover'],
parents: [{ class: 'tab_control', attributes: ['selected'] }],
'layer0.opacity': {
target: 0.8,
speed: 4.0,
interpolation: 'smoothstep',
},
},
{
class: 'new_tab_button',
content_margin: 0,
min_size: [32, 32],
'layer1.tint': 'var(repositoryTabBarBg)',
'layer1.opacity': 1.0,
'layer3.tint': 'var(repositoryTabBarBorderBg)',
// 'layer3.texture': 'Theme - Merge/tab_border_end.png',
'layer3.inner_margin': [16, 0, 16, 0],
'layer3.opacity': 0.2,
},
{
class: 'new_tab_icon',
parents: [{ class: 'new_tab_button' }],
"layer0.tint": "var(foreground)",
"layer0.opacity": "var(iconButtonOpacity)",
},
{
class: 'new_tab_icon',
parents: [{ class: 'new_tab_button', attributes: ['hover'] }],
"layer0.tint": "var(foreground)",
"layer0.opacity": "var(iconButtonOpacityHover)",
},
{
class: 'tab_dropdown_button',
content_margin: 0,
min_size: [32, 32],
'layer1.tint': 'var(repositoryTabBarBg)',
'layer1.opacity': 1.0,
'layer3.tint': 'var(repositoryTabBarBorderBg)',
// 'layer3.texture': 'Theme - Merge/tab_border_end.png',
'layer3.inner_margin': [16, 0, 16, 0],
'layer3.opacity': 0.2,
},
{
class: 'tab_select_dropdown_icon',
parents: [{ class: 'tab_dropdown_button' }],
"layer0.tint": "var(foreground)",
"layer0.opacity": "var(iconButtonOpacity)",
},
{
class: 'tab_select_dropdown_icon',
parents: [{ class: 'tab_dropdown_button', attributes: ['hover'] }],
"layer0.tint": "var(foreground)",
"layer0.opacity": "var(iconButtonOpacityHover)",
},
] | the_stack |
import {Host, InvalidConfigField, InvalidUri, LEGACY_BASE64_URI, makeConfig, Method, parseOnlineConfigUrl, Password, Port, SHADOWSOCKS_URI, SIP002_URI, Tag,} from './shadowsocks_config';
describe('shadowsocks_config', () => {
describe('Config API', () => {
it('has expected shape', () => {
const config = makeConfig({
host: '192.168.100.1',
port: 8888,
method: 'chacha20',
password: 'P@$$W0RD!',
});
const host: string = config.host.data;
const port: number = config.port.data;
const method: string = config.method.data;
const password: string = config.password.data;
expect(host).toEqual('192.168.100.1');
expect(port).toEqual(8888);
expect(method).toEqual('chacha20');
expect(password).toEqual('P@$$W0RD!');
});
});
describe('field validation', () => {
it('accepts IPv4 address hosts', () => {
for (const valid of ['127.0.0.1', '8.8.8.8', '192.168.0.1']) {
const host = new Host(valid);
expect(host.data).toEqual(valid);
expect(host.isIPv4).toBeTruthy();
expect(host.isIPv6).toBeFalsy();
expect(host.isHostname).toBeFalsy();
}
});
it('preserves normalized IPv6 address hosts', () => {
for (const valid of ['0:0:0:0:0:0:0:1', '2001:0:ce49:7601:e866:efff:62c3:fffe']) {
const host = new Host(valid);
expect(host.data).toEqual(valid);
expect(host.isIPv4).toBeFalsy();
expect(host.isIPv6).toBeTruthy();
expect(host.isHostname).toBeFalsy();
}
});
it('normalizes IPv6 address hosts', () => {
const testCases = [
// Canonical form
['::1', '0:0:0:0:0:0:0:1'], ['2001:db8::', '2001:db8:0:0:0:0:0:0'],
// Expanded form
['1:02:003:0004:005:06:7:08', '1:2:3:4:5:6:7:8'],
// IPv4-mapped form
['::ffff:192.0.2.128', '0:0:0:0:0:ffff:c000:280']
];
for (const [input, expanded] of testCases) {
const host = new Host(input);
expect(host.data).toEqual(expanded);
expect(host.isIPv4).toBeFalsy();
expect(host.isIPv6).toBeTruthy();
expect(host.isHostname).toBeFalsy();
}
});
it('accepts valid hostname hosts', () => {
for (const valid of ['localhost', 'example.com']) {
const host = new Host(valid);
expect(host.data).toEqual(valid);
expect(host.isIPv4).toBeFalsy();
expect(host.isIPv6).toBeFalsy();
expect(host.isHostname).toBeTruthy();
}
});
it('accepts valid unicode hostnames and converts them to punycode', () => {
const testCases = [['mañana.com', 'xn--maana-pta.com'], ['☃-⌘.com', 'xn----dqo34k.com']];
for (const [input, converted] of testCases) {
const host = new Host(input);
expect(host.data).toEqual(converted);
expect(host.isIPv6).toBeFalsy();
expect(host.isIPv4).toBeFalsy();
expect(host.isHostname).toBeTruthy();
}
});
it('rejects invalid host values', () => {
for (const invalid of ['-', '-pwned', ';echo pwned', '.', '....']) {
expect(() => new Host(invalid)).toThrowError(InvalidConfigField);
}
});
it('throws on empty host', () => {
expect(() => new Host('')).toThrowError(InvalidConfigField);
});
it('accepts valid ports', () => {
expect(new Port('8388').data).toEqual(8388);
expect(new Port('443').data).toEqual(443);
expect(new Port(8388).data).toEqual(8388);
expect(new Port(443).data).toEqual(443);
});
it('throws on empty port', () => {
expect(() => new Port('')).toThrowError(InvalidConfigField);
});
it('throws on invalid port', () => {
expect(() => new Port('foo')).toThrowError(InvalidConfigField);
expect(() => new Port('-123')).toThrowError(InvalidConfigField);
expect(() => new Port('123.4')).toThrowError(InvalidConfigField);
expect(() => new Port('123.4')).toThrowError(InvalidConfigField);
expect(() => new Port(-123)).toThrowError(InvalidConfigField);
expect(() => new Port(123.4)).toThrowError(InvalidConfigField);
// Maximum port number possible is 65535.
expect(() => new Port(65536)).toThrowError(InvalidConfigField);
});
it('normalizes non-normalized but valid port', () => {
expect(new Port('01234').data).toEqual(1234);
});
it('throws on empty method', () => {
expect(() => new Method('')).toThrowError(InvalidConfigField);
});
it('throws on invalid method', () => {
expect(() => new Method('foo')).toThrowError(InvalidConfigField);
});
it('accepts valid methods', () => {
for (const method
of ['rc4-md5',
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'aes-128-cfb',
'aes-192-cfb',
'aes-256-cfb',
'aes-128-ctr',
'aes-192-ctr',
'aes-256-ctr',
'camellia-128-cfb',
'camellia-192-cfb',
'camellia-256-cfb',
'bf-cfb',
'chacha20-ietf-poly1305',
'salsa20',
'chacha20',
'chacha20-ietf',
'xchacha20-ietf-poly1305',
]) {
expect(new Method(method).data).toEqual(method);
}
});
it('accepts empty password', () => {
expect(new Password('').data).toEqual('');
});
it('accepts empty or undefined tag', () => {
expect(new Tag('').data).toEqual('');
expect(new Tag().data).toEqual('');
});
it('throws on Config with missing or invalid fields', () => {
expect(() => makeConfig({
host: '192.168.100.1',
port: '8989',
})).toThrowError(InvalidConfigField);
expect(() => makeConfig({
method: 'aes-128-gcm',
password: 'test',
})).toThrowError(InvalidConfigField);
});
it('throw on invalid configs', () => {
expect(() => makeConfig({
port: 'foo',
method: 'aes-128-gcm',
})).toThrowError(InvalidConfigField);
expect(() => makeConfig({
port: '1337',
method: 'foo',
})).toThrowError(InvalidConfigField);
});
});
describe('URI serializer', () => {
it('can serialize a SIP002 URI', () => {
const config = makeConfig({
host: '192.168.100.1',
port: '8888',
method: 'aes-128-gcm',
password: 'test',
tag: 'Foo Bar',
});
expect(SIP002_URI.stringify(config))
.toEqual('ss://YWVzLTEyOC1nY206dGVzdA@192.168.100.1:8888/#Foo%20Bar');
});
it('can serialize a SIP002 URI with a non-latin password', () => {
const config = makeConfig({
host: '192.168.100.1',
port: '8888',
method: 'aes-128-gcm',
password: '小洞不补大洞吃苦',
tag: 'Foo Bar',
});
expect(SIP002_URI.stringify(config))
.toEqual(
'ss://YWVzLTEyOC1nY2065bCP5rSe5LiN6KGl5aSn5rSe5ZCD6Ium@192.168.100.1:8888/#Foo%20Bar');
});
it('can serialize a SIP002 URI with IPv6 host', () => {
const config = makeConfig({
host: '2001:0:ce49:7601:e866:efff:62c3:fffe',
port: '8888',
method: 'aes-128-gcm',
password: 'test',
tag: 'Foo Bar',
});
expect(SIP002_URI.stringify(config))
.toEqual(
'ss://YWVzLTEyOC1nY206dGVzdA@[2001:0:ce49:7601:e866:efff:62c3:fffe]:8888/#Foo%20Bar');
});
it('can serialize a legacy base64 URI', () => {
const config = makeConfig({
host: '192.168.100.1',
port: '8888',
method: 'bf-cfb',
password: 'test',
tag: 'Foo Bar',
});
expect(LEGACY_BASE64_URI.stringify(config)).toEqual(
'ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4#Foo%20Bar');
});
it('can serialize a legacy base64 URI with a non-latin password', () => {
const config = makeConfig({
host: '192.168.100.1',
port: '8888',
method: 'bf-cfb',
password: '小洞不补大洞吃苦',
tag: 'Foo Bar',
});
expect(LEGACY_BASE64_URI.stringify(config))
.toEqual(
'ss://YmYtY2ZiOuWwj+a0nuS4jeihpeWkp+a0nuWQg+iLpkAxOTIuMTY4LjEwMC4xOjg4ODg#Foo%20Bar');
});
});
describe('URI parser', () => {
it('exposes a PROTOCOL property with value "ss:"', () => {
expect(SHADOWSOCKS_URI.PROTOCOL).toEqual('ss:');
});
it('can parse a valid SIP002 URI with IPv4 host', () => {
const input = 'ss://YWVzLTEyOC1nY206dGVzdA@192.168.100.1:8888#Foo%20Bar';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('aes-128-gcm');
expect(config.password.data).toEqual('test');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(8888);
expect(config.tag.data).toEqual('Foo Bar');
});
it('can parse a SIP002 URI with non-uri-safe base64 padding', () => {
const input = 'ss://YWVzLTEyOC1nY206dGVzdA==@192.168.100.1:8888#Foo%20Bar';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('aes-128-gcm');
expect(config.password.data).toEqual('test');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(8888);
expect(config.tag.data).toEqual('Foo Bar');
});
it('can parse a valid SIP002 URI with IPv6 host', () => {
const input = 'ss://YWVzLTEyOC1nY206dGVzdA@[2001:0:ce49:7601:e866:efff:62c3:fffe]:8888';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('aes-128-gcm');
expect(config.password.data).toEqual('test');
expect(config.host.data).toEqual('2001:0:ce49:7601:e866:efff:62c3:fffe');
expect(config.port.data).toEqual(8888);
});
it('can parse a valid SIP002 URI with a compressed IPv6 host', () => {
const input = 'ss://YWVzLTEyOC1nY206dGVzdA@[2001::fffe]:8888';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('aes-128-gcm');
expect(config.password.data).toEqual('test');
expect(config.host.data).toEqual('2001:0:0:0:0:0:0:fffe');
expect(config.port.data).toEqual(8888);
});
it('can parse a valid SIP002 URI with a non-latin password', () => {
const input = 'ss://YWVzLTEyOC1nY2065bCP5rSe5LiN6KGl5aSn5rSe5ZCD6Ium@192.168.100.1:8888';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('aes-128-gcm');
expect(config.password.data).toEqual('小洞不补大洞吃苦');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(8888);
});
it('can parse a valid SIP002 URI with an arbitrary query param', () => {
const input = 'ss://cmM0LW1kNTpwYXNzd2Q@192.168.100.1:8888/?foo=1';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.extra.foo!).toEqual('1');
});
it('can parse a valid SIP002 URI with the at symbol and other symbols in the password', () => {
const input =
'ss://YmYtY2ZiOnRlc3QvIUAjOi5fLV4nIiRAJUAxOTIuMTY4LjEwMC4xOjg4ODg#server_by_tim@shadowsocks.org';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.password.data).toEqual('test/!@#:._-^\'"$@%');
});
it('can parse a valid SIP002 URI with a plugin param', () => {
const input = 'ss://cmM0LW1kNTpwYXNzd2Q@192.168.100.1:8888/?plugin=obfs-local%3Bobfs%3Dhttp';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('rc4-md5');
expect(config.password.data).toEqual('passwd');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(8888);
expect(config.extra.plugin!).toEqual('obfs-local;obfs=http');
});
it('can parse a valid SIP002 URI with the default HTTP port and no plugin parameters', () => {
const input = 'ss://cmM0LW1kNTpwYXNzd2Q@192.168.100.1:80';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('rc4-md5');
expect(config.password.data).toEqual('passwd');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(80);
});
it('can parse a valid SIP002 URI with the default HTTP port and parameters', () => {
const input = 'ss://cmM0LW1kNTpwYXNzd2Q@192.168.100.1:80/?foo=1&bar=';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('rc4-md5');
expect(config.password.data).toEqual('passwd');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(80);
});
it('can parse a valid legacy base64 URI with IPv4 host', () => {
const input = 'ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4#Foo%20Bar';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('bf-cfb');
expect(config.password.data).toEqual('test');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(8888);
expect(config.tag.data).toEqual('Foo Bar');
});
it('can parse a valid legacy base64 URI with IPv6 host', () => {
const input = 'ss://YmYtY2ZiOnRlc3RAWzIwMDE6MDpjZTQ5Ojc2MDE6ZTg2NjplZmZmOjYyYzM6ZmZmZV06ODg4OA';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.host.data).toEqual('2001:0:ce49:7601:e866:efff:62c3:fffe');
expect(config.port.data).toEqual(8888);
expect(config.method.data).toEqual('bf-cfb');
expect(config.password.data).toEqual('test');
expect(config.tag.data).toEqual('');
});
it('can parse a valid legacy base64 URI default HTTP port', () => {
const input = 'ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpwYXNzdzByZEAxOTIuMTY4LjEwMC4xOjgw';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(80);
expect(config.method.data).toEqual('chacha20-ietf-poly1305');
expect(config.password.data).toEqual('passw0rd');
});
it('can parse a valid legacy base64 URI with a non-latin password', () => {
const input =
'ss://YmYtY2ZiOuWwj+a0nuS4jeihpeWkp+a0nuWQg+iLpkAxOTIuMTY4LjEwMC4xOjg4ODg#Foo%20Bar';
const config = SHADOWSOCKS_URI.parse(input);
expect(config.method.data).toEqual('bf-cfb');
expect(config.password.data).toEqual('小洞不补大洞吃苦');
expect(config.host.data).toEqual('192.168.100.1');
expect(config.port.data).toEqual(8888);
expect(config.tag.data).toEqual('Foo Bar');
});
it('throws when parsing empty input', () => {
expect(() => SHADOWSOCKS_URI.parse('')).toThrowError(InvalidUri);
});
it('throws when parsing invalid input', () => {
expect(() => SHADOWSOCKS_URI.parse('not a URI')).toThrowError(InvalidUri);
expect(() => SHADOWSOCKS_URI.parse('ss://not-base64')).toThrowError(InvalidUri);
});
});
describe('SIP008', () => {
it('can parse a valid ssconf URI with domain name and extras', () => {
const input = encodeURI(
'ssconf://my.domain.com/secret/long/path#certFp=AA:BB:CC:DD:EE:FF&httpMethod=POST');
const onlineConfig = parseOnlineConfigUrl(input);
expect(new URL(onlineConfig.location))
.toEqual(new URL('https://my.domain.com/secret/long/path'));
expect(onlineConfig.certFingerprint).toEqual('AA:BB:CC:DD:EE:FF');
expect(onlineConfig.httpMethod).toEqual('POST');
});
it('can parse a valid ssconf URI with domain name and custom port', () => {
const input =
encodeURI('ssconf://my.domain.com:9090/secret/long/path#certFp=AA:BB:CC:DD:EE:FF');
const onlineConfig = parseOnlineConfigUrl(input);
expect(new URL(onlineConfig.location))
.toEqual(new URL('https://my.domain.com:9090/secret/long/path'));
expect(onlineConfig.certFingerprint).toEqual('AA:BB:CC:DD:EE:FF');
});
it('can parse a valid ssconf URI with hostname and no path', () => {
const input = encodeURI('ssconf://my.domain.com');
const onlineConfig = parseOnlineConfigUrl(input);
expect(new URL(onlineConfig.location)).toEqual(new URL('https://my.domain.com'));
expect(onlineConfig.certFingerprint).toBeUndefined();
});
it('can parse a valid ssconf URI with IPv4 address', () => {
const input =
encodeURI('ssconf://1.2.3.4/secret/long/path#certFp=AA:BB:CC:DD:EE:FF&other=param');
const onlineConfig = parseOnlineConfigUrl(input);
expect(new URL(onlineConfig.location)).toEqual(new URL('https://1.2.3.4/secret/long/path'));
expect(onlineConfig.certFingerprint).toEqual('AA:BB:CC:DD:EE:FF');
});
it('can parse a valid ssconf URI with IPv6 address and custom port', () => {
// encodeURI encodes the IPv6 address brackets.
const input = `ssconf://[2001:0:ce49:7601:e866:efff:62c3:fffe]:8081/secret/long/path#certFp=${
encodeURIComponent('AA:BB:CC:DD:EE:FF')}`;
const onlineConfig = parseOnlineConfigUrl(input);
expect(new URL(onlineConfig.location))
.toEqual(new URL('https://[2001:0:ce49:7601:e866:efff:62c3:fffe]:8081/secret/long/path'));
expect(onlineConfig.certFingerprint).toEqual('AA:BB:CC:DD:EE:FF');
});
it('can parse a valid ssconf URI with URI-encoded tag', () => {
const certFp = '&=?:%';
const input = `ssconf://1.2.3.4/secret#certFp=${encodeURIComponent(certFp)}&httpMethod=GET`;
const onlineConfig = parseOnlineConfigUrl(input);
expect(new URL(onlineConfig.location)).toEqual(new URL('https://1.2.3.4/secret'));
expect(onlineConfig.certFingerprint).toEqual(certFp);
expect(onlineConfig.httpMethod).toEqual('GET');
});
});
}); | the_stack |
import {
AbiItem,
BurnAndReleaseTransaction,
LockAndMintTransaction,
Logger,
NullLogger,
RenVMAssetFees,
RenVMFees,
} from "@renproject/interfaces";
import {
assert,
fixSignature,
fromBase64,
Ox,
signatureToBuffer,
toBase64,
} from "@renproject/utils";
import BigNumber from "bignumber.js";
import {
ResponseQueryBurnTx,
ResponseQueryFees,
ResponseQueryMintTx,
} from "./methods";
import { Fees, RenVMArg, RenVMType } from "./value";
const decodeString = (input: string) => fromBase64(input).toString();
const decodeBytes = (input: string) => fromBase64(input);
const decodeNumber = (input: string) => new BigNumber(input);
/**
* Validate an argument returned from RenVM.
*
* @param name The expected name.
* @param type The expected type.
* @param arg The actual argument returned.
*/
const assertArgumentType = <ArgType>(
name: ArgType extends RenVMArg<infer Name, infer _Type> ? Name : never,
type: ArgType extends RenVMArg<infer _Name, infer Type> ? Type : never,
arg: ArgType extends RenVMArg<infer Name, infer Type, infer Value>
? RenVMArg<Name, Type, Value>
: never,
): ArgType extends RenVMArg<infer _Name, infer _Type, infer Value>
? Value
: never => {
assert(
arg.type === type,
`Expected argument ${name} of type ${type} but got ${arg.name} of type ${arg.type}`,
);
return arg.value;
};
const assertAndDecodeBytes = <ArgType extends RenVMArg<string, RenVMType>>(
name: ArgType extends RenVMArg<infer Name, infer _Type> ? Name : never,
type: ArgType extends RenVMArg<infer _Name, infer Type> ? Type : never,
arg: ArgType extends RenVMArg<infer Name, infer Type, infer Value>
? Value extends string
? RenVMArg<Name, Type, Value>
: never
: never,
): Buffer => {
try {
return decodeBytes(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertArgumentType<ArgType>(name as any, type as any, arg as any),
);
} catch (error) {
error.message = `Unable to decode parameter ${name} with value ${String(
arg.value,
)} (type ${typeof arg.value}): ${String(error.message)}`;
throw error;
}
};
const assertAndDecodeNumber = <ArgType>(
name: ArgType extends RenVMArg<infer Name, infer _Type> ? Name : never,
type: ArgType extends RenVMArg<infer _Name, infer Type> ? Type : never,
arg: ArgType extends RenVMArg<infer Name, infer Type, infer Value>
? Value extends string
? RenVMArg<Name, Type, Value>
: never
: never,
): BigNumber => {
try {
return decodeNumber(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertArgumentType<ArgType>(name as any, type as any, arg as any),
);
} catch (error) {
error.message = `Unable to decode parameter ${name} with value ${String(
arg.value,
)} (type ${typeof arg.value}): ${String(error.message)}`;
throw error;
}
};
const assertAndDecodeAddress = <ArgType extends RenVMArg<string, RenVMType>>(
name: ArgType extends RenVMArg<infer Name, infer _Type> ? Name : never,
type: ArgType extends RenVMArg<infer _Name, infer Type> ? Type : never,
arg: ArgType extends RenVMArg<infer Name, infer Type, infer Value>
? Value extends string
? RenVMArg<Name, Type, Value>
: never
: never,
): string => {
try {
return Ox(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertArgumentType<ArgType>(name as any, type as any, arg as any),
);
} catch (error) {
error.message = `Unable to decode parameter ${name} with value ${String(
arg.value,
)} (type ${typeof arg.value}): ${String(error.message)}`;
throw error;
}
};
const defaultPayload: ResponseQueryMintTx["tx"]["in"]["0"] = {
name: "p",
type: RenVMType.ExtEthCompatPayload,
value: {
abi: "W10=",
value: "",
fn: "",
},
};
const findField = <ArgType extends RenVMArg<string, RenVMType>>(
field: ArgType extends RenVMArg<infer Name, infer _Type> ? Name : never,
response: ResponseQueryMintTx,
): ArgType => {
for (const outField of response.tx.out || []) {
if (outField.name === field) {
return outField as ArgType;
}
}
for (const outField of response.tx.autogen) {
if (outField.name === field) {
return outField as ArgType;
}
}
for (const outField of response.tx.in) {
if (outField.name === field) {
return outField as ArgType;
}
}
throw new Error(`Unable to find field ${field} in response from RenVM.`);
};
const onError = <P>(getP: () => P, defaultP: P) => {
try {
return getP();
} catch (error) {
return defaultP;
}
};
export const unmarshalMintTx = (
response: ResponseQueryMintTx,
logger: Logger = NullLogger,
): LockAndMintTransaction => {
// Note: Numbers are decoded and re-encoded to ensure they are in the correct format.
// TODO: Check that response is mint response.
// assert(
// parseV1Selector(response.tx.to).to === "Eth",
// `Expected mint details but got back burn details (${response.tx.hash} - ${response.tx.to})`
// );
type In = ResponseQueryMintTx["tx"]["in"];
const pRaw = assertArgumentType<In[0]>(
"p",
RenVMType.ExtEthCompatPayload,
onError(() => findField<In[0]>("p", response), defaultPayload),
);
const token = assertAndDecodeAddress<In[1]>(
"token",
RenVMType.ExtTypeEthCompatAddress,
findField<In[1]>("token", response),
);
const to = assertAndDecodeAddress<In[2]>(
"to",
RenVMType.ExtTypeEthCompatAddress,
findField<In[2]>("to", response),
);
const n = assertAndDecodeBytes<In[3]>(
"n",
RenVMType.B32,
findField<In[3]>("n", response),
);
const p = {
abi: JSON.parse(decodeString(pRaw.abi)) as AbiItem[],
value: decodeBytes(pRaw.value),
fn: decodeString(pRaw.fn),
};
type Autogen = ResponseQueryMintTx["tx"]["autogen"];
const phash = assertAndDecodeBytes<Autogen[0]>(
"phash",
RenVMType.B32,
findField<Autogen[0]>("phash", response),
);
const ghash = assertAndDecodeBytes<Autogen[1]>(
"ghash",
RenVMType.B32,
findField<Autogen[1]>("ghash", response),
);
const nhash = assertAndDecodeBytes<Autogen[2]>(
"nhash",
RenVMType.B32,
findField<Autogen[2]>("nhash", response),
);
const amount = assertAndDecodeNumber<Autogen[3]>(
"amount",
RenVMType.U256,
findField<Autogen[3]>("amount", response),
).toFixed();
const utxoRaw = assertArgumentType<Autogen[4]>(
"utxo",
RenVMType.ExtTypeBtcCompatUTXO,
findField<Autogen[4]>("utxo", response),
);
const sighash = assertAndDecodeBytes<Autogen[5]>(
"sighash",
RenVMType.B32,
findField<Autogen[5]>("sighash", response),
);
const utxo = {
txHash: Ox(decodeBytes(utxoRaw.txHash), { prefix: "" }),
vOut: parseInt(utxoRaw.vOut, 10),
scriptPubKey: utxoRaw.scriptPubKey
? Ox(decodeBytes(utxoRaw.scriptPubKey), { prefix: "" })
: "",
amount: decodeNumber(utxoRaw.amount).toFixed(),
};
type Out = ResponseQueryMintTx["tx"]["out"] & {};
const out: LockAndMintTransaction["out"] = {
sighash,
ghash,
nhash,
phash,
amount,
};
if (response.tx.out) {
const [rArg, sArg, vArg] = [
findField<Out[0]>("r", response),
findField<Out[1]>("s", response),
findField<Out[2]>("v", response),
];
const r: Buffer =
rArg.type === RenVMType.B
? assertAndDecodeBytes<Out["0"]>("r", RenVMType.B, rArg)
: assertAndDecodeBytes<Out["0"]>("r", RenVMType.B32, rArg);
const s: Buffer =
sArg.type === RenVMType.B
? assertAndDecodeBytes<Out["1"]>("s", RenVMType.B, sArg)
: assertAndDecodeBytes<Out["1"]>("s", RenVMType.B32, sArg);
const v: number =
vArg.type === RenVMType.B
? assertAndDecodeBytes<Out["2"]>("v", RenVMType.B, vArg)[0]
: assertAndDecodeNumber<Out["2"]>(
"v",
RenVMType.U8,
vArg,
).toNumber();
const signature = signatureToBuffer(
fixSignature(
r,
s,
v,
sighash,
phash,
amount,
to,
token,
nhash,
false,
logger,
),
);
out.signature = signature; // r, s, v
}
return {
hash: toBase64(decodeBytes(response.tx.hash)),
txStatus: response.txStatus,
to: response.tx.to,
in: { p, token, to, n, utxo },
out,
};
};
export const unmarshalBurnTx = (
response: ResponseQueryBurnTx,
): BurnAndReleaseTransaction => {
// TODO: Check that result is burn response.
// assert(
// parseV1Selector(response.tx.to).from === Chain.Ethereum,
// `Expected burn details but got back mint details (${response.tx.hash} - ${response.tx.to})`
// );
const [refArg, toArg, amountArg] = response.tx.in;
const ref = assertAndDecodeNumber<typeof refArg>(
"ref",
RenVMType.U64,
refArg,
).toFixed();
const toRaw = assertArgumentType<typeof toArg>("to", RenVMType.B, toArg);
let amount;
try {
amount = assertAndDecodeNumber<typeof amountArg>(
"amount",
RenVMType.U256,
amountArg,
).toFixed();
} catch (error) {
amount = assertAndDecodeNumber<typeof amountArg>(
"amount",
RenVMType.U64,
amountArg,
).toFixed();
}
const to = toRaw;
// response.tx.to === Tokens.ZEC.Eth2Zec ?
// utils.zec.addressFrom(toRaw) :
// response.tx.to === Tokens.BCH.Eth2Bch ?
// utils.bch.addressFrom(toRaw) :
// utils.btc.addressFrom(toRaw);
return {
hash: toBase64(decodeBytes(response.tx.hash)),
to: response.tx.to,
in: { ref, to, amount },
txStatus: response.txStatus,
};
};
const unmarshalAssetFees = (fees: Fees): RenVMAssetFees => {
const { lock, release, ...tokens } = fees;
// TODO: Fix type errors.
return {
lock: decodeNumber(lock),
release: decodeNumber(release),
...Object.keys(tokens).reduce(
(acc, token) => ({
...acc,
[token]: {
mint: decodeNumber(fees[token].mint).toNumber(),
burn: decodeNumber(fees[token].burn).toNumber(),
},
}),
{},
),
} as unknown as RenVMAssetFees;
};
export const unmarshalFees = (response: ResponseQueryFees): RenVMFees => {
const fees = {};
for (const key of Object.keys(response)) {
fees[key] = unmarshalAssetFees(response[key]);
}
return fees;
}; | the_stack |
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ZosmfTools } from '../tool/zosmfTools';
import { TsoService } from '../service/tso.service';
import { LogService } from '../service/log.service';
import { PersistService } from '../service/persist.service';
@Component({
selector: 'app-var-viewer',
templateUrl: './var-viewer.component.html',
styleUrls: ['./var-viewer.component.css']
})
/**
* Component uses TsoService, LogService, PersistService to communicate with z/OSMF.
* From this component, users could start a long-run REXX in a TSO/E address space and retrieve
* system variable via the long-run REXX.
*/
export class VarViewerComponent implements OnInit {
/**
* variables control which part should be displayed based on the progress of user action
*/
progress = {
introduct: {
show: true,
},
createTSO: {
show: false,
try: false,
done: false,
bad: false
},
startApp: {
show: false,
try: false,
done: false,
bad: false,
second: false
},
getVar: {
show: false,
try: false,
done: false,
ready: false
},
cleanup: {
show: false,
try: false,
done: false
}
}
/**
* properties for persist used
*/
proc = "IZUFPROC";
rexx = "VAREXX";
mvsvar = "SYSNAME";
path = "persist";
preProc: string;
preRexx: string;
preMvsvar: string;
/**
* save current retrieval's result
*/
result: string;
/**
* default var values for selected
*/
MVSVARS = [
// "SYSAPPCLU",
"SYSDFP",
"SYSMVS",
"SYSNAME",
"SYSOPSYS",
"SYSSECLAB",
"SYSSMFID",
"SYSSMS",
"SYSCLONE",
"SYSPLEX",
"SYMDEF"
];
/**
* inject services to component.
* @param _tsoService responsible for creating TSO/E address space, starting application, etc
* @param _logService logs your messages to server, by default, in IZUGX.log files
* @param _persistService persist json data to server end, in .zdf files
*/
constructor(
private _tsoService: TsoService,
private _logService: LogService,
private _persistService: PersistService) { }
ngOnInit() {
// pass a ZosmfTools instance to window, it will be used by z/OSMF desktop when doing cleanup.
window["zosmfTools"] = new ZosmfTools(this._tsoService);
// get proc, rexx, var from server via PersistService
this._persistService.getJson(this.path).subscribe(data => {
// parse data
let param = data["value"];
this._logService.logInfo("init", "persist value: " + JSON.stringify(param));
// if properties persisted before, then use it
if (param["proc"]) this.preProc = param["proc"];
if (param["rexx"]) this.preRexx = param["rexx"];
if (param["mvsvar"]) this.preMvsvar = param["mvsvar"];
this.proc = this.preProc;
this.rexx = this.preRexx;
this.mvsvar = this.preMvsvar;
});
}
/**
* Make UI jump to next View after user click start or next button
*/
next() {
if (this.progress.introduct.show) {
this.progress.introduct.show = false;
this.progress.createTSO.show = true;
} else if (this.progress.getVar.show) {
this.progress.getVar.show = false;
this.progress.cleanup.show = true;
} else if (this.progress.cleanup.show) {
this.progress.cleanup.show = false;
this.progress.introduct.show = true;
this.progress.createTSO.try = false;
this.progress.createTSO.done = false;
this.progress.startApp.try = false;
this.progress.startApp.done = false;
this.progress.startApp.second = false;
this.progress.getVar.try = false;
this.progress.getVar.done = false;
this.progress.cleanup.try = false;
this.progress.cleanup.done = false;
}
}
/**
* Clear error notification once input get focused
*/
clearBad() {
if (this.progress.createTSO.bad) this.progress.createTSO.bad = false;
if (this.progress.startApp.bad) this.progress.startApp.bad = false;
}
/**
* Start a TSO/E address space with proc which specified by user.
*/
startTSO() {
let mname = "startTSO";
this._logService.logEnter(mname);
// set progress bar status
this.progress.createTSO.try = true;
// (async () => {
// await this.delay(5000);
// this.progress.createTSO.done = true;
// (async () => {
// await this.delay(3000);
// this.progress.createTSO.show = false;
// this.progress.startApp.show = true;
// })();
// })();
// start a TSO/E address space via TsoService
this._tsoService.startTSO(this.proc).subscribe(data => {
// parse response of z/OSMF TSO REST API
let key = data["servletKey"];
let qid = data["queueID"];
this._logService.logInfo(mname, "key: " + key + ", qid: " + qid);
if (data["msgData"]) { // error happened, suppose this is because the wrong PROC user input
this.progress.createTSO.bad = true;
this.progress.createTSO.try = false;
} else { // suppose TSO/E address space is successfully created
// set servletKey and queueId to service for next use
this._tsoService.setServletKey(key);
this._tsoService.setQueueId(qid);
// change progress bar status
this.progress.createTSO.done = true;
(async () => {
await this.delay(5000);
this.progress.createTSO.show = false;
this.progress.startApp.show = true;
})();
// persist proc if user specified one is different with old one
if (this.proc != this.preProc) {
let json = { "proc": this.proc };
this._persistService.putJson(this.path, json).subscribe(data => {
// update previous proc to current one for next time's comparation
this.preProc = this.proc;
});
}
}
});
this._logService.logExit(mname);
}
/**
* Start a long-run REXX with user specified rexx name
*/
startApp() {
let mname = "startApp";
this._logService.logEnter(mname);
// set progress bar status
this.progress.startApp.try = true;
// (async () => {
// await this.delay(5000);
// this.progress.startApp.done = true;
// (async () => {
// await this.delay(3000);
// this.progress.startApp.show = false;
// this.progress.getVar.show = true;
// })();
// })();
// start an app via TsoService
if (!this.progress.startApp.second) { // first time try to start REXX
this._tsoService.startApp(this.rexx).subscribe(data => {
this._logService.logInfo("startApp", "res of start app:\n" + JSON.stringify(data));
if (!this.checkREXXStatusFromRes(data)) this.checkREXXStatus();
});
} else { // normal start progress failed, need to start REXX again
this._tsoService.putTSO(this.rexx).subscribe(data => {
this._logService.logInfo("startApp", "res of put TSO:\n" + JSON.stringify(data));
if (!this.checkREXXStatusFromRes(data)) this.checkREXXStatus();
})
}
this._logService.logExit(mname);
}
/**
* Check the response of POST start App or PUT TSO cmd to determin if REXX is successfully started,
* if it's still no result at the point, then return false.
* @param res
*/
checkREXXStatusFromRes(res): boolean {
let tsoData = res["tsoData"];
let str = JSON.stringify(tsoData);
if (str.indexOf("IKJ565") >= 0) { // member not exist
this.progress.startApp.bad = true;
this.progress.startApp.try = false;
this.progress.startApp.second = true;
return true;
} else if (str.indexOf("processing has started") >= 0) { // REXX is started
// change progress bar status
this.progress.startApp.done = true;
// below is only for debug
(async () => {
await this.delay(5000);
this.progress.startApp.show = false;
this.progress.getVar.show = true;
})();
// persist rexx if user specified one is different with old one
if (this.rexx != this.preRexx) {
let json = { "rexx": this.rexx };
this._persistService.putJson(this.path, json).subscribe(data => {
// update previous rexx name for next time use
this.preRexx = this.rexx;
});
}
return true;
} else { // can't determine whether REXX is started or failed
return false;
}
}
/**
* recusive method to read TSO messages to determine whether REXX is started.
*/
checkREXXStatus() {
this._tsoService.readApp().subscribe(data => {
let jsonData = JSON.parse(data);
if (jsonData["timeout"]) { // timeout occurred, suppose REXX is failed to start
this.progress.startApp.bad = true;
this.progress.startApp.try = false;
this.progress.startApp.second = true;
} else {
let tsoData = jsonData["tsoData"];
let res = JSON.stringify(tsoData);
if (this.checkREXXStatusFromRes(jsonData)) {
return;
} else this.checkREXXStatus();
}
});
}
/**
* Pass the mvsvar to backend long-run rexx and retrievel the value of mvsvar
*/
getVar() {
// clear result status and set progress bar status
this.result = null;
this.progress.getVar.try = true;
this.progress.getVar.done = false;
// (async () => {
// await this.delay(5000);
// this.progress.getVar.done = true;
// this.progress.getVar.try = false;
// if (!this.progress.getVar.ready) this.progress.getVar.ready = true;
// this.result = "test";
// })();
// put mvsvar name which users want to retrieve, to backend long-run rexx
this._tsoService.putApp(this.mvsvar).subscribe(putRes => {
// after backend rexx receive the mvsvar, call rReadApp() to read the result
this.rReadApp();
// persist mvsvar name if user specified one is different
if (this.mvsvar != this.preMvsvar) {
let json = { "mvsvar": this.mvsvar };
this._persistService.putJson(this.path, json).subscribe(data => {
this.preMvsvar = this.mvsvar;
});
}
});
}
/**
* recusive method to read data writen by backend REXX via TsoService
*/
rReadApp() {
if (this._tsoService.servletKey) {
this._tsoService.readApp().subscribe(readRes => {
// since response of reading app is not a real json, we need to parse it as string.
let start = readRes.indexOf("appData");
if (start >= 0) { // "appData" contains in response
// get the string behind '"appData":'
let rawValue = readRes.substring(start + 9);
// cut the data off until the first ','
let len = rawValue.indexOf(',');
this._logService.logInfo("readApp", "res: " + readRes + "\nstart: " + start + ", len: " + len);
this.result = rawValue.substring(0, len);
this.progress.getVar.done = true;
this.progress.getVar.try = false;
this.progress.getVar.ready = true;
} else this.rReadApp(); // if no "appData" contains in response, then recusivly call itself
})
} else {
this.progress.getVar.try = false;
this._logService.logInfo("readApp", "tso as is not exist");
}
}
/**
* delete a TSO/E address space via TsoService
*/
deleteAS() {
this.progress.cleanup.try = true;
// (async () => {
// await this.delay(5000);
// this.progress.cleanup.done = true;
// })();
this._tsoService.deleteTSO().subscribe(data => {
this._tsoService.servletKey = null;
this._tsoService.queueId = null;
this.progress.cleanup.done = true;
});
}
/**
* debug used
* @param ms
*/
delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
} | the_stack |
import PropTypes from "prop-types";
import * as React from "react";
import { routerShape } from "react-router";
import { Trans } from "@lingui/macro";
import { InfoBoxInline } from "@dcos/ui-kit";
import ConfigurationMap from "#SRC/js/components/ConfigurationMap";
import ConfigurationMapHeading from "#SRC/js/components/ConfigurationMapHeading";
import ConfigurationMapLabel from "#SRC/js/components/ConfigurationMapLabel";
import ConfigurationMapRow from "#SRC/js/components/ConfigurationMapRow";
import ConfigurationMapSection from "#SRC/js/components/ConfigurationMapSection";
import ConfigurationMapValue from "#SRC/js/components/ConfigurationMapValue";
import DateUtil from "#SRC/js/utils/DateUtil";
import TimeAgo from "#SRC/js/components/TimeAgo";
import MetadataStore from "#SRC/js/stores/MetadataStore";
import DeclinedOffersHelpText from "../../constants/DeclinedOffersHelpText";
import DeclinedOffersTable from "../../components/DeclinedOffersTable";
import MarathonStore from "../../stores/MarathonStore";
import RecentOffersSummary from "../../components/RecentOffersSummary";
import Service from "../../structs/Service";
import Framework from "../../structs/Framework";
import TaskStatsTable from "./TaskStatsTable";
class ServiceDebugContainer extends React.Component {
static propTypes = {
service: PropTypes.instanceOf(Service),
};
UNSAFE_componentWillMount() {
MarathonStore.setShouldEmbedLastUnusedOffers(true);
}
componentWillUnmount() {
MarathonStore.setShouldEmbedLastUnusedOffers(false);
}
getDeclinedOffersTable() {
const { service } = this.props;
if (!this.shouldShowDeclinedOfferTable()) {
return null;
}
const queue = service.getQueue();
return (
<div>
<Trans render={<ConfigurationMapHeading level={2} />}>Details</Trans>
<DeclinedOffersTable
offers={queue.declinedOffers.offers}
service={service}
summary={queue.declinedOffers.summary}
/>
</div>
);
}
getLastTaskFailureInfo() {
const lastTaskFailure = this.props.service.getLastTaskFailure();
if (lastTaskFailure == null) {
return <Trans render="p">This app does not have failed tasks</Trans>;
}
const {
version,
timestamp,
taskId,
state,
message,
host,
} = lastTaskFailure;
return (
<ConfigurationMapSection>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Task ID</Trans>
<ConfigurationMapValue>
{this.getValueText(taskId)}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>State</Trans>
<ConfigurationMapValue>
{this.getValueText(state)}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Message</Trans>
<ConfigurationMapValue>
{this.getValueText(message)}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Host</Trans>
<ConfigurationMapValue>
{this.getValueText(host)}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Timestamp</Trans>
<ConfigurationMapValue>
{/* L10NTODO: Relative time */}
{timestamp} (<TimeAgo time={new Date(timestamp)} />)
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Version</Trans>
<ConfigurationMapValue>
{/* L10NTODO: Relative time */}
{version} (<TimeAgo time={new Date(version)} />)
</ConfigurationMapValue>
</ConfigurationMapRow>
</ConfigurationMapSection>
);
}
getLastVersionChange() {
const versionInfo = this.props.service.getVersionInfo();
if (versionInfo == null) {
return (
<Trans render="p">
This app does not have version change information
</Trans>
);
}
const { lastScalingAt, lastConfigChangeAt } = versionInfo;
let lastScaling = "No operation since last config change";
if (lastScalingAt !== lastConfigChangeAt) {
// L10NTODO: Relative time
lastScaling = (
<span>
{lastScalingAt} (<TimeAgo time={new Date(lastScalingAt)} />)
</span>
);
}
return (
<ConfigurationMapSection>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Scale or Restart</Trans>
<ConfigurationMapValue>{lastScaling}</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<Trans render={<ConfigurationMapLabel />}>Configuration</Trans>
<ConfigurationMapValue>
{`${lastConfigChangeAt} `}
{/* L10NTODO: Relative time */}
(<TimeAgo time={new Date(lastConfigChangeAt)} />)
</ConfigurationMapValue>
</ConfigurationMapRow>
</ConfigurationMapSection>
);
}
getRecentOfferSummaryContent() {
const { service } = this.props;
if (!this.shouldShowDeclinedOfferSummary()) {
return null;
}
return (
<div>
<Trans render={<ConfigurationMapHeading level={2} />}>Summary</Trans>
<RecentOffersSummary data={service.getQueue().declinedOffers.summary} />
</div>
);
}
getRecentOfferSummaryCount() {
const { service } = this.props;
if (!this.shouldShowDeclinedOfferSummary()) {
return null;
}
const queue = service.getQueue();
const {
declinedOffers: { summary },
} = queue;
const {
roles: { offers = 0 },
} = summary;
return ` (${offers})`;
}
getRecentOfferSummaryDisabledText(frameworkName) {
if (frameworkName != null) {
return (
<Trans render="span">
Rejected offer analysis is not currently supported for {frameworkName}
.
</Trans>
);
}
return (
<Trans render="span">
Rejected offer analysis is not currently supported.
</Trans>
);
}
getRecentOfferSummaryIntroText() {
const { service } = this.props;
if (service instanceof Framework) {
const frameworkName = service.getPackageName();
return this.getRecentOfferSummaryDisabledText(frameworkName);
}
if (this.shouldShowDeclinedOfferSummary()) {
return DeclinedOffersHelpText.summaryIntro;
}
return (
<Trans render="span">
Offers will appear here when your service is deploying or waiting for
resources.
</Trans>
);
}
getRecentOfferSummary() {
const introText = this.getRecentOfferSummaryIntroText();
const mainContent = this.getRecentOfferSummaryContent();
const offerCount = this.getRecentOfferSummaryCount();
return (
<div
ref={(ref) => {
this.offerSummaryRef = ref;
}}
>
<Trans render={<ConfigurationMapHeading />}>
Recent Resource Offers{offerCount}
</Trans>
<p>{introText}</p>
{mainContent}
</div>
);
}
getTaskStats() {
const taskStats = this.props.service.getTaskStats();
if (taskStats.getList().getItems().length === 0) {
return <Trans render="p">This app does not have task statistics</Trans>;
}
return <TaskStatsTable taskStats={taskStats} />;
}
getValueText(value) {
if (value == null || value === "") {
return <Trans render="p">Unspecified</Trans>;
}
return <span>{value}</span>;
}
getUnableToStartNotice() {
const { service } = this.props;
if (service instanceof Framework) {
return null;
}
const queue = service.getQueue();
if (queue == null || queue.since == null) {
return null;
}
const waitingSince = DateUtil.strToMs(queue.since);
const timeWaiting = Date.now() - waitingSince;
let message,
primaryAction,
secondaryAction = null;
if (service.isDelayed()) {
message = (
<Trans render="span">
DC/OS has delayed the launching of this service due to failures.
</Trans>
);
secondaryAction = (
<Trans render="span">
<a
className="clickable"
target="_blank"
onClick={() => MarathonStore.resetDelayedService(service)}
>
Retry now
</a>
</Trans>
);
primaryAction = (
<Trans render="span">
<a
href={MetadataStore.buildDocsURI("/gui/services#service-status")}
target="_blank"
>
More information
</a>{" "}
</Trans>
);
// If the service has been waiting for less than five minutes, we don't
// display the warning.
} else if (timeWaiting >= 1000 * 60 * 5) {
/* L10NTODO: Relative time */
message = (
<Trans render="span">
DC/OS has been waiting for resources and is unable to complete this
deployment for {DateUtil.getDuration(timeWaiting)}.
</Trans>
);
primaryAction = (
<Trans
render={
<div
className="clickable button-link button-primary"
onClick={this.handleJumpToRecentOffersClick}
tabIndex={0}
role="button"
/>
}
>
See recent resource offers
</Trans>
);
}
if (!message) {
return null;
}
return (
<div className="infoBoxWrapper">
<InfoBoxInline
appearance="warning"
message={message}
primaryAction={primaryAction}
secondaryAction={secondaryAction}
/>
</div>
);
}
handleJumpToRecentOffersClick = () => {
if (this.offerSummaryRef) {
this.offerSummaryRef.scrollIntoView();
}
};
shouldShowDeclinedOfferSummary() {
const { service } = this.props;
return (
!this.shouldSuppressDeclinedOfferDetails() &&
service.getQueue().declinedOffers.summary != null
);
}
shouldShowDeclinedOfferTable() {
const { service } = this.props;
return (
!this.shouldSuppressDeclinedOfferDetails() &&
service.getQueue().declinedOffers.offers != null
);
}
shouldSuppressDeclinedOfferDetails() {
const { service } = this.props;
const queue = service.getQueue();
return queue == null || service instanceof Framework;
}
render() {
return (
<div className="container">
{this.getUnableToStartNotice()}
<ConfigurationMap>
<ConfigurationMapSection>
<Trans render={<ConfigurationMapHeading />}>Last Changes</Trans>
{this.getLastVersionChange()}
</ConfigurationMapSection>
<ConfigurationMapSection>
<Trans render={<ConfigurationMapHeading />}>
Last Task Failure
</Trans>
{this.getLastTaskFailureInfo()}
</ConfigurationMapSection>
<ConfigurationMapSection>
<Trans render={<ConfigurationMapHeading />}>Task Statistics</Trans>
{this.getTaskStats()}
</ConfigurationMapSection>
{this.getRecentOfferSummary()}
{this.getDeclinedOffersTable()}
</ConfigurationMap>
</div>
);
}
}
ServiceDebugContainer.contextTypes = {
router: routerShape,
};
export default ServiceDebugContainer; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* An OS Config resource representing a guest configuration policy. These policies represent
* the desired state for VM instance guest environments including packages to install or remove,
* package repository configurations, and software to install.
*
* To get more information about GuestPolicies, see:
*
* * [API documentation](https://cloud.google.com/compute/docs/osconfig/rest)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/compute/docs/os-config-management)
*
* ## Example Usage
* ### Os Config Guest Policies Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const myImage = gcp.compute.getImage({
* family: "debian-9",
* project: "debian-cloud",
* });
* const foobar = new gcp.compute.Instance("foobar", {
* machineType: "e2-medium",
* zone: "us-central1-a",
* canIpForward: false,
* tags: [
* "foo",
* "bar",
* ],
* bootDisk: {
* initializeParams: {
* image: myImage.then(myImage => myImage.selfLink),
* },
* },
* networkInterfaces: [{
* network: "default",
* }],
* metadata: {
* foo: "bar",
* },
* }, {
* provider: google_beta,
* });
* const guestPolicies = new gcp.osconfig.GuestPolicies("guestPolicies", {
* guestPolicyId: "guest-policy",
* assignment: {
* instances: [foobar.id],
* },
* packages: [{
* name: "my-package",
* desiredState: "UPDATED",
* }],
* }, {
* provider: google_beta,
* });
* ```
* ### Os Config Guest Policies Packages
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const guestPolicies = new gcp.osconfig.GuestPolicies("guestPolicies", {
* guestPolicyId: "guest-policy",
* assignment: {
* groupLabels: [
* {
* labels: {
* color: "red",
* env: "test",
* },
* },
* {
* labels: {
* color: "blue",
* env: "test",
* },
* },
* ],
* },
* packages: [
* {
* name: "my-package",
* desiredState: "INSTALLED",
* },
* {
* name: "bad-package-1",
* desiredState: "REMOVED",
* },
* {
* name: "bad-package-2",
* desiredState: "REMOVED",
* manager: "APT",
* },
* ],
* packageRepositories: [
* {
* apt: {
* uri: "https://packages.cloud.google.com/apt",
* archiveType: "DEB",
* distribution: "cloud-sdk-stretch",
* components: ["main"],
* },
* },
* {
* yum: {
* id: "google-cloud-sdk",
* displayName: "Google Cloud SDK",
* baseUrl: "https://packages.cloud.google.com/yum/repos/cloud-sdk-el7-x86_64",
* gpgKeys: [
* "https://packages.cloud.google.com/yum/doc/yum-key.gpg",
* "https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg",
* ],
* },
* },
* ],
* }, {
* provider: google_beta,
* });
* ```
* ### Os Config Guest Policies Recipes
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const guestPolicies = new gcp.osconfig.GuestPolicies("guestPolicies", {
* guestPolicyId: "guest-policy",
* assignment: {
* zones: [
* "us-east1-b",
* "us-east1-d",
* ],
* },
* recipes: [{
* name: "guest-policy-recipe",
* desiredState: "INSTALLED",
* artifacts: [{
* id: "guest-policy-artifact-id",
* gcs: {
* bucket: "my-bucket",
* object: "executable.msi",
* generation: 1546030865175603,
* },
* }],
* installSteps: [{
* msiInstallation: {
* artifactId: "guest-policy-artifact-id",
* },
* }],
* }],
* }, {
* provider: google_beta,
* });
* ```
*
* ## Import
*
* GuestPolicies can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:osconfig/guestPolicies:GuestPolicies default projects/{{project}}/guestPolicies/{{guest_policy_id}}
* ```
*
* ```sh
* $ pulumi import gcp:osconfig/guestPolicies:GuestPolicies default {{project}}/{{guest_policy_id}}
* ```
*
* ```sh
* $ pulumi import gcp:osconfig/guestPolicies:GuestPolicies default {{guest_policy_id}}
* ```
*/
export class GuestPolicies extends pulumi.CustomResource {
/**
* Get an existing GuestPolicies 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?: GuestPoliciesState, opts?: pulumi.CustomResourceOptions): GuestPolicies {
return new GuestPolicies(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:osconfig/guestPolicies:GuestPolicies';
/**
* Returns true if the given object is an instance of GuestPolicies. 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 GuestPolicies {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === GuestPolicies.__pulumiType;
}
/**
* Specifies the VM instances that are assigned to this policy. This allows you to target sets
* or groups of VM instances by different parameters such as labels, names, OS, or zones.
* If left empty, all VM instances underneath this policy are targeted.
* At the same level in the resource hierarchy (that is within a project), the service prevents
* the creation of multiple policies that conflict with each other.
* For more information, see how the service
* [handles assignment conflicts](https://cloud.google.com/compute/docs/os-config-management/create-guest-policy#handle-conflicts).
* Structure is documented below.
*/
public readonly assignment!: pulumi.Output<outputs.osconfig.GuestPoliciesAssignment>;
/**
* Time this guest policy was created. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example:
* "2014-10-02T15:01:23.045123456Z".
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* Description of the guest policy. Length of the description is limited to 1024 characters.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The etag for this guest policy. If this is provided on update, it must match the server's etag.
*/
public readonly etag!: pulumi.Output<string>;
/**
* The logical name of the guest policy in the project with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the project.
*/
public readonly guestPolicyId!: pulumi.Output<string>;
/**
* Unique identifier for the recipe. Only one recipe with a given name is installed on an instance.
* Names are also used to identify resources which helps to determine whether guest policies have conflicts.
* This means that requests to create multiple recipes with the same name and version are rejected since they
* could potentially have conflicting assignments.
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* A list of package repositories to configure on the VM instance.
* This is done before any other configs are applied so they can use these repos.
* Package repositories are only configured if the corresponding package manager(s) are available.
* Structure is documented below.
*/
public readonly packageRepositories!: pulumi.Output<outputs.osconfig.GuestPoliciesPackageRepository[] | undefined>;
/**
* The software packages to be managed by this policy.
* Structure is documented below.
*/
public readonly packages!: pulumi.Output<outputs.osconfig.GuestPoliciesPackage[] | undefined>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* A list of Recipes to install on the VM instance.
* Structure is documented below.
*/
public readonly recipes!: pulumi.Output<outputs.osconfig.GuestPoliciesRecipe[] | undefined>;
/**
* Last time this guest policy was updated. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example:
* "2014-10-02T15:01:23.045123456Z".
*/
public /*out*/ readonly updateTime!: pulumi.Output<string>;
/**
* Create a GuestPolicies 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: GuestPoliciesArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: GuestPoliciesArgs | GuestPoliciesState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as GuestPoliciesState | undefined;
inputs["assignment"] = state ? state.assignment : undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["etag"] = state ? state.etag : undefined;
inputs["guestPolicyId"] = state ? state.guestPolicyId : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["packageRepositories"] = state ? state.packageRepositories : undefined;
inputs["packages"] = state ? state.packages : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["recipes"] = state ? state.recipes : undefined;
inputs["updateTime"] = state ? state.updateTime : undefined;
} else {
const args = argsOrState as GuestPoliciesArgs | undefined;
if ((!args || args.assignment === undefined) && !opts.urn) {
throw new Error("Missing required property 'assignment'");
}
if ((!args || args.guestPolicyId === undefined) && !opts.urn) {
throw new Error("Missing required property 'guestPolicyId'");
}
inputs["assignment"] = args ? args.assignment : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["etag"] = args ? args.etag : undefined;
inputs["guestPolicyId"] = args ? args.guestPolicyId : undefined;
inputs["packageRepositories"] = args ? args.packageRepositories : undefined;
inputs["packages"] = args ? args.packages : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["recipes"] = args ? args.recipes : undefined;
inputs["createTime"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
inputs["updateTime"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(GuestPolicies.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering GuestPolicies resources.
*/
export interface GuestPoliciesState {
/**
* Specifies the VM instances that are assigned to this policy. This allows you to target sets
* or groups of VM instances by different parameters such as labels, names, OS, or zones.
* If left empty, all VM instances underneath this policy are targeted.
* At the same level in the resource hierarchy (that is within a project), the service prevents
* the creation of multiple policies that conflict with each other.
* For more information, see how the service
* [handles assignment conflicts](https://cloud.google.com/compute/docs/os-config-management/create-guest-policy#handle-conflicts).
* Structure is documented below.
*/
assignment?: pulumi.Input<inputs.osconfig.GuestPoliciesAssignment>;
/**
* Time this guest policy was created. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example:
* "2014-10-02T15:01:23.045123456Z".
*/
createTime?: pulumi.Input<string>;
/**
* Description of the guest policy. Length of the description is limited to 1024 characters.
*/
description?: pulumi.Input<string>;
/**
* The etag for this guest policy. If this is provided on update, it must match the server's etag.
*/
etag?: pulumi.Input<string>;
/**
* The logical name of the guest policy in the project with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the project.
*/
guestPolicyId?: pulumi.Input<string>;
/**
* Unique identifier for the recipe. Only one recipe with a given name is installed on an instance.
* Names are also used to identify resources which helps to determine whether guest policies have conflicts.
* This means that requests to create multiple recipes with the same name and version are rejected since they
* could potentially have conflicting assignments.
*/
name?: pulumi.Input<string>;
/**
* A list of package repositories to configure on the VM instance.
* This is done before any other configs are applied so they can use these repos.
* Package repositories are only configured if the corresponding package manager(s) are available.
* Structure is documented below.
*/
packageRepositories?: pulumi.Input<pulumi.Input<inputs.osconfig.GuestPoliciesPackageRepository>[]>;
/**
* The software packages to be managed by this policy.
* Structure is documented below.
*/
packages?: pulumi.Input<pulumi.Input<inputs.osconfig.GuestPoliciesPackage>[]>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* A list of Recipes to install on the VM instance.
* Structure is documented below.
*/
recipes?: pulumi.Input<pulumi.Input<inputs.osconfig.GuestPoliciesRecipe>[]>;
/**
* Last time this guest policy was updated. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example:
* "2014-10-02T15:01:23.045123456Z".
*/
updateTime?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a GuestPolicies resource.
*/
export interface GuestPoliciesArgs {
/**
* Specifies the VM instances that are assigned to this policy. This allows you to target sets
* or groups of VM instances by different parameters such as labels, names, OS, or zones.
* If left empty, all VM instances underneath this policy are targeted.
* At the same level in the resource hierarchy (that is within a project), the service prevents
* the creation of multiple policies that conflict with each other.
* For more information, see how the service
* [handles assignment conflicts](https://cloud.google.com/compute/docs/os-config-management/create-guest-policy#handle-conflicts).
* Structure is documented below.
*/
assignment: pulumi.Input<inputs.osconfig.GuestPoliciesAssignment>;
/**
* Description of the guest policy. Length of the description is limited to 1024 characters.
*/
description?: pulumi.Input<string>;
/**
* The etag for this guest policy. If this is provided on update, it must match the server's etag.
*/
etag?: pulumi.Input<string>;
/**
* The logical name of the guest policy in the project with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the project.
*/
guestPolicyId: pulumi.Input<string>;
/**
* A list of package repositories to configure on the VM instance.
* This is done before any other configs are applied so they can use these repos.
* Package repositories are only configured if the corresponding package manager(s) are available.
* Structure is documented below.
*/
packageRepositories?: pulumi.Input<pulumi.Input<inputs.osconfig.GuestPoliciesPackageRepository>[]>;
/**
* The software packages to be managed by this policy.
* Structure is documented below.
*/
packages?: pulumi.Input<pulumi.Input<inputs.osconfig.GuestPoliciesPackage>[]>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* A list of Recipes to install on the VM instance.
* Structure is documented below.
*/
recipes?: pulumi.Input<pulumi.Input<inputs.osconfig.GuestPoliciesRecipe>[]>;
} | the_stack |
import Vue from 'vue';
import { ExtendedVue } from 'vue/types/vue';
export interface FeatherIconProps {
size: string;
}
export type FeatherIconComponent = ExtendedVue<
Vue,
{},
{},
{},
FeatherIconProps
>;
export const ActivityIcon: FeatherIconComponent;
export const AirplayIcon: FeatherIconComponent;
export const AlertCircleIcon: FeatherIconComponent;
export const AlertOctagonIcon: FeatherIconComponent;
export const AlertTriangleIcon: FeatherIconComponent;
export const AlignCenterIcon: FeatherIconComponent;
export const AlignJustifyIcon: FeatherIconComponent;
export const AlignLeftIcon: FeatherIconComponent;
export const AlignRightIcon: FeatherIconComponent;
export const AnchorIcon: FeatherIconComponent;
export const ApertureIcon: FeatherIconComponent;
export const ArchiveIcon: FeatherIconComponent;
export const ArrowDownCircleIcon: FeatherIconComponent;
export const ArrowDownLeftIcon: FeatherIconComponent;
export const ArrowDownRightIcon: FeatherIconComponent;
export const ArrowDownIcon: FeatherIconComponent;
export const ArrowLeftCircleIcon: FeatherIconComponent;
export const ArrowLeftIcon: FeatherIconComponent;
export const ArrowRightCircleIcon: FeatherIconComponent;
export const ArrowRightIcon: FeatherIconComponent;
export const ArrowUpCircleIcon: FeatherIconComponent;
export const ArrowUpLeftIcon: FeatherIconComponent;
export const ArrowUpRightIcon: FeatherIconComponent;
export const ArrowUpIcon: FeatherIconComponent;
export const AtSignIcon: FeatherIconComponent;
export const AwardIcon: FeatherIconComponent;
export const BarChart2Icon: FeatherIconComponent;
export const BarChartIcon: FeatherIconComponent;
export const BatteryChargingIcon: FeatherIconComponent;
export const BatteryIcon: FeatherIconComponent;
export const BellOffIcon: FeatherIconComponent;
export const BellIcon: FeatherIconComponent;
export const BluetoothIcon: FeatherIconComponent;
export const BoldIcon: FeatherIconComponent;
export const BookOpenIcon: FeatherIconComponent;
export const BookIcon: FeatherIconComponent;
export const BookmarkIcon: FeatherIconComponent;
export const BoxIcon: FeatherIconComponent;
export const BriefcaseIcon: FeatherIconComponent;
export const CalendarIcon: FeatherIconComponent;
export const CameraOffIcon: FeatherIconComponent;
export const CameraIcon: FeatherIconComponent;
export const CastIcon: FeatherIconComponent;
export const CheckCircleIcon: FeatherIconComponent;
export const CheckSquareIcon: FeatherIconComponent;
export const CheckIcon: FeatherIconComponent;
export const ChevronDownIcon: FeatherIconComponent;
export const ChevronLeftIcon: FeatherIconComponent;
export const ChevronRightIcon: FeatherIconComponent;
export const ChevronUpIcon: FeatherIconComponent;
export const ChevronsDownIcon: FeatherIconComponent;
export const ChevronsLeftIcon: FeatherIconComponent;
export const ChevronsRightIcon: FeatherIconComponent;
export const ChevronsUpIcon: FeatherIconComponent;
export const ChromeIcon: FeatherIconComponent;
export const CircleIcon: FeatherIconComponent;
export const ClipboardIcon: FeatherIconComponent;
export const ClockIcon: FeatherIconComponent;
export const CloudDrizzleIcon: FeatherIconComponent;
export const CloudLightningIcon: FeatherIconComponent;
export const CloudOffIcon: FeatherIconComponent;
export const CloudRainIcon: FeatherIconComponent;
export const CloudSnowIcon: FeatherIconComponent;
export const CloudIcon: FeatherIconComponent;
export const CodeIcon: FeatherIconComponent;
export const CodepenIcon: FeatherIconComponent;
export const CodesandboxIcon: FeatherIconComponent;
export const CoffeeIcon: FeatherIconComponent;
export const ColumnsIcon: FeatherIconComponent;
export const CommandIcon: FeatherIconComponent;
export const CompassIcon: FeatherIconComponent;
export const CopyIcon: FeatherIconComponent;
export const CornerDownLeftIcon: FeatherIconComponent;
export const CornerDownRightIcon: FeatherIconComponent;
export const CornerLeftDownIcon: FeatherIconComponent;
export const CornerLeftUpIcon: FeatherIconComponent;
export const CornerRightDownIcon: FeatherIconComponent;
export const CornerRightUpIcon: FeatherIconComponent;
export const CornerUpLeftIcon: FeatherIconComponent;
export const CornerUpRightIcon: FeatherIconComponent;
export const CpuIcon: FeatherIconComponent;
export const CreditCardIcon: FeatherIconComponent;
export const CropIcon: FeatherIconComponent;
export const CrosshairIcon: FeatherIconComponent;
export const DatabaseIcon: FeatherIconComponent;
export const DeleteIcon: FeatherIconComponent;
export const DiscIcon: FeatherIconComponent;
export const DollarSignIcon: FeatherIconComponent;
export const DownloadCloudIcon: FeatherIconComponent;
export const DownloadIcon: FeatherIconComponent;
export const DropletIcon: FeatherIconComponent;
export const Edit2Icon: FeatherIconComponent;
export const Edit3Icon: FeatherIconComponent;
export const EditIcon: FeatherIconComponent;
export const ExternalLinkIcon: FeatherIconComponent;
export const EyeOffIcon: FeatherIconComponent;
export const EyeIcon: FeatherIconComponent;
export const FacebookIcon: FeatherIconComponent;
export const FastForwardIcon: FeatherIconComponent;
export const FeatherIcon: FeatherIconComponent;
export const FigmaIcon: FeatherIconComponent;
export const FileMinusIcon: FeatherIconComponent;
export const FilePlusIcon: FeatherIconComponent;
export const FileTextIcon: FeatherIconComponent;
export const FileIcon: FeatherIconComponent;
export const FilmIcon: FeatherIconComponent;
export const FilterIcon: FeatherIconComponent;
export const FlagIcon: FeatherIconComponent;
export const FolderMinusIcon: FeatherIconComponent;
export const FolderPlusIcon: FeatherIconComponent;
export const FolderIcon: FeatherIconComponent;
export const FramerIcon: FeatherIconComponent;
export const FrownIcon: FeatherIconComponent;
export const GiftIcon: FeatherIconComponent;
export const GitBranchIcon: FeatherIconComponent;
export const GitCommitIcon: FeatherIconComponent;
export const GitMergeIcon: FeatherIconComponent;
export const GitPullRequestIcon: FeatherIconComponent;
export const GithubIcon: FeatherIconComponent;
export const GitlabIcon: FeatherIconComponent;
export const GlobeIcon: FeatherIconComponent;
export const GridIcon: FeatherIconComponent;
export const HardDriveIcon: FeatherIconComponent;
export const HashIcon: FeatherIconComponent;
export const HeadphonesIcon: FeatherIconComponent;
export const HeartIcon: FeatherIconComponent;
export const HelpCircleIcon: FeatherIconComponent;
export const HexagonIcon: FeatherIconComponent;
export const HomeIcon: FeatherIconComponent;
export const ImageIcon: FeatherIconComponent;
export const InboxIcon: FeatherIconComponent;
export const InfoIcon: FeatherIconComponent;
export const InstagramIcon: FeatherIconComponent;
export const ItalicIcon: FeatherIconComponent;
export const KeyIcon: FeatherIconComponent;
export const LayersIcon: FeatherIconComponent;
export const LayoutIcon: FeatherIconComponent;
export const LifeBuoyIcon: FeatherIconComponent;
export const Link2Icon: FeatherIconComponent;
export const LinkIcon: FeatherIconComponent;
export const LinkedinIcon: FeatherIconComponent;
export const ListIcon: FeatherIconComponent;
export const LoaderIcon: FeatherIconComponent;
export const LockIcon: FeatherIconComponent;
export const LogInIcon: FeatherIconComponent;
export const LogOutIcon: FeatherIconComponent;
export const MailIcon: FeatherIconComponent;
export const MapPinIcon: FeatherIconComponent;
export const MapIcon: FeatherIconComponent;
export const Maximize2Icon: FeatherIconComponent;
export const MaximizeIcon: FeatherIconComponent;
export const MehIcon: FeatherIconComponent;
export const MenuIcon: FeatherIconComponent;
export const MessageCircleIcon: FeatherIconComponent;
export const MessageSquareIcon: FeatherIconComponent;
export const MicOffIcon: FeatherIconComponent;
export const MicIcon: FeatherIconComponent;
export const Minimize2Icon: FeatherIconComponent;
export const MinimizeIcon: FeatherIconComponent;
export const MinusCircleIcon: FeatherIconComponent;
export const MinusSquareIcon: FeatherIconComponent;
export const MinusIcon: FeatherIconComponent;
export const MonitorIcon: FeatherIconComponent;
export const MoonIcon: FeatherIconComponent;
export const MoreHorizontalIcon: FeatherIconComponent;
export const MoreVerticalIcon: FeatherIconComponent;
export const MousePointerIcon: FeatherIconComponent;
export const MoveIcon: FeatherIconComponent;
export const MusicIcon: FeatherIconComponent;
export const Navigation2Icon: FeatherIconComponent;
export const NavigationIcon: FeatherIconComponent;
export const OctagonIcon: FeatherIconComponent;
export const PackageIcon: FeatherIconComponent;
export const PaperclipIcon: FeatherIconComponent;
export const PauseCircleIcon: FeatherIconComponent;
export const PauseIcon: FeatherIconComponent;
export const PenToolIcon: FeatherIconComponent;
export const PercentIcon: FeatherIconComponent;
export const PhoneCallIcon: FeatherIconComponent;
export const PhoneForwardedIcon: FeatherIconComponent;
export const PhoneIncomingIcon: FeatherIconComponent;
export const PhoneMissedIcon: FeatherIconComponent;
export const PhoneOffIcon: FeatherIconComponent;
export const PhoneOutgoingIcon: FeatherIconComponent;
export const PhoneIcon: FeatherIconComponent;
export const PieChartIcon: FeatherIconComponent;
export const PlayCircleIcon: FeatherIconComponent;
export const PlayIcon: FeatherIconComponent;
export const PlusCircleIcon: FeatherIconComponent;
export const PlusSquareIcon: FeatherIconComponent;
export const PlusIcon: FeatherIconComponent;
export const PocketIcon: FeatherIconComponent;
export const PowerIcon: FeatherIconComponent;
export const PrinterIcon: FeatherIconComponent;
export const RadioIcon: FeatherIconComponent;
export const RefreshCcwIcon: FeatherIconComponent;
export const RefreshCwIcon: FeatherIconComponent;
export const RepeatIcon: FeatherIconComponent;
export const RewindIcon: FeatherIconComponent;
export const RotateCcwIcon: FeatherIconComponent;
export const RotateCwIcon: FeatherIconComponent;
export const RssIcon: FeatherIconComponent;
export const SaveIcon: FeatherIconComponent;
export const ScissorsIcon: FeatherIconComponent;
export const SearchIcon: FeatherIconComponent;
export const SendIcon: FeatherIconComponent;
export const ServerIcon: FeatherIconComponent;
export const SettingsIcon: FeatherIconComponent;
export const Share2Icon: FeatherIconComponent;
export const ShareIcon: FeatherIconComponent;
export const ShieldOffIcon: FeatherIconComponent;
export const ShieldIcon: FeatherIconComponent;
export const ShoppingBagIcon: FeatherIconComponent;
export const ShoppingCartIcon: FeatherIconComponent;
export const ShuffleIcon: FeatherIconComponent;
export const SidebarIcon: FeatherIconComponent;
export const SkipBackIcon: FeatherIconComponent;
export const SkipForwardIcon: FeatherIconComponent;
export const SlackIcon: FeatherIconComponent;
export const SlashIcon: FeatherIconComponent;
export const SlidersIcon: FeatherIconComponent;
export const SmartphoneIcon: FeatherIconComponent;
export const SmileIcon: FeatherIconComponent;
export const SpeakerIcon: FeatherIconComponent;
export const SquareIcon: FeatherIconComponent;
export const StarIcon: FeatherIconComponent;
export const StopCircleIcon: FeatherIconComponent;
export const SunIcon: FeatherIconComponent;
export const SunriseIcon: FeatherIconComponent;
export const SunsetIcon: FeatherIconComponent;
export const TabletIcon: FeatherIconComponent;
export const TagIcon: FeatherIconComponent;
export const TargetIcon: FeatherIconComponent;
export const TerminalIcon: FeatherIconComponent;
export const ThermometerIcon: FeatherIconComponent;
export const ThumbsDownIcon: FeatherIconComponent;
export const ThumbsUpIcon: FeatherIconComponent;
export const ToggleLeftIcon: FeatherIconComponent;
export const ToggleRightIcon: FeatherIconComponent;
export const ToolIcon: FeatherIconComponent;
export const Trash2Icon: FeatherIconComponent;
export const TrashIcon: FeatherIconComponent;
export const TrelloIcon: FeatherIconComponent;
export const TrendingDownIcon: FeatherIconComponent;
export const TrendingUpIcon: FeatherIconComponent;
export const TriangleIcon: FeatherIconComponent;
export const TruckIcon: FeatherIconComponent;
export const TvIcon: FeatherIconComponent;
export const TwitchIcon: FeatherIconComponent;
export const TwitterIcon: FeatherIconComponent;
export const TypeIcon: FeatherIconComponent;
export const UmbrellaIcon: FeatherIconComponent;
export const UnderlineIcon: FeatherIconComponent;
export const UnlockIcon: FeatherIconComponent;
export const UploadCloudIcon: FeatherIconComponent;
export const UploadIcon: FeatherIconComponent;
export const UserCheckIcon: FeatherIconComponent;
export const UserMinusIcon: FeatherIconComponent;
export const UserPlusIcon: FeatherIconComponent;
export const UserXIcon: FeatherIconComponent;
export const UserIcon: FeatherIconComponent;
export const UsersIcon: FeatherIconComponent;
export const VideoOffIcon: FeatherIconComponent;
export const VideoIcon: FeatherIconComponent;
export const VoicemailIcon: FeatherIconComponent;
export const Volume1Icon: FeatherIconComponent;
export const Volume2Icon: FeatherIconComponent;
export const VolumeXIcon: FeatherIconComponent;
export const VolumeIcon: FeatherIconComponent;
export const WatchIcon: FeatherIconComponent;
export const WifiOffIcon: FeatherIconComponent;
export const WifiIcon: FeatherIconComponent;
export const WindIcon: FeatherIconComponent;
export const XCircleIcon: FeatherIconComponent;
export const XOctagonIcon: FeatherIconComponent;
export const XSquareIcon: FeatherIconComponent;
export const XIcon: FeatherIconComponent;
export const YoutubeIcon: FeatherIconComponent;
export const ZapOffIcon: FeatherIconComponent;
export const ZapIcon: FeatherIconComponent;
export const ZoomInIcon: FeatherIconComponent;
export const ZoomOutIcon: FeatherIconComponent; | the_stack |
import { d3, initChart } from './c3-helper'
describe('c3 chart legend', function() {
'use strict'
var chart, args
beforeEach(function(done) {
chart = initChart(chart, args, done)
})
describe('legend when multiple charts rendered', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30],
['data2', 50],
['data3', 100]
]
}
}
})
describe('long data names', function() {
beforeAll(function() {
args = {
data: {
columns: [
['long data name 1', 30],
['long data name 2', 50],
['long data name 3', 50]
]
}
}
})
it('should have properly computed legend width', function() {
var expectedLeft = [148, 226, 384],
expectedWidth = [118, 118, 108]
d3.selectAll('.c3-legend-item').each(function(d, i) {
var rect = (d3.select(this).node() as any).getBoundingClientRect()
expect(rect.left).toBeCloseTo(expectedLeft[i], -2)
expect(rect.width).toBeCloseTo(expectedWidth[i], -2)
})
})
})
})
describe('legend position', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
}
}
})
it('should be located on the center of chart', function() {
var box = chart.internal.legend.node().getBoundingClientRect()
expect(box.left + box.right).toBe(638)
})
})
describe('legend as inset', function() {
describe('should change the legend to "inset" successfully', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
},
legend: {
position: 'inset',
inset: {
step: null
}
}
}
})
it('should be positioned properly', function() {
var box = (d3
.select('.c3-legend-background')
.node() as any).getBoundingClientRect()
expect(box.top).toBe(5.5)
expect(box.left).toBeGreaterThan(30)
})
it('should have automatically calculated height', function() {
var box = (d3
.select('.c3-legend-background')
.node() as any).getBoundingClientRect()
expect(box.height).toBe(48)
})
})
describe('should change the legend step to 1 successfully', function() {
beforeAll(function() {
args.legend.inset.step = 1
})
it('should have automatically calculated height', function() {
var box = (d3
.select('.c3-legend-background')
.node() as any).getBoundingClientRect()
expect(box.height).toBe(28)
})
})
describe('should change the legend step to 2 successfully', function() {
beforeAll(function() {
args.legend.inset.step = 2
})
it('should have automatically calculated height', function() {
var box = (d3
.select('.c3-legend-background')
.node() as any).getBoundingClientRect()
expect(box.height).toBe(48)
})
})
describe('with only one series', function() {
beforeAll(function() {
args = {
data: {
columns: [['data1', 30, 200, 100, 400, 150, 250]]
},
legend: {
position: 'inset'
}
}
})
it('should locate legend properly', function() {
var box = (d3
.select('.c3-legend-background')
.node() as any).getBoundingClientRect()
expect(box.height).toBe(28)
expect(box.width).toBeGreaterThan(64)
})
})
})
describe('legend.hide', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
hide: true
}
}
})
it('should not show legends', function() {
d3.selectAll('.c3-legend-item').each(function() {
expect(d3.select(this).style('visibility')).toBe('hidden')
})
})
describe('hidden legend', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
hide: 'data2'
}
}
})
it('should not show legends', function() {
expect(d3.select('.c3-legend-item-data1').style('visibility')).toBe(
'visible'
)
expect(d3.select('.c3-legend-item-data2').style('visibility')).toBe(
'hidden'
)
})
})
})
describe('legend.show', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
show: false
}
}
})
it('should not initially have rendered any legend items', function() {
expect(d3.selectAll('.c3-legend-item').empty()).toBe(true)
})
it('allows us to show the legend on showLegend call', function() {
chart.legend.show()
d3.selectAll('.c3-legend-item').each(function() {
expect(d3.select(this).style('visibility')).toBe('visible')
// This selects all the children, but we expect it to be empty
expect((d3.select(this).selectAll('*') as any).length).not.toEqual(0)
})
})
})
describe('with legend.show is true', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
show: true
}
}
})
it('should initially have rendered some legend items', function() {
expect(d3.selectAll('.c3-legend-item').empty()).toBe(false)
})
it('should remove rendered every legend items', function() {
chart.legend.hide()
d3.selectAll('.c3-legend-item').each(function() {
expect(d3.select(this).style('visibility')).toBe('hidden')
// This selects all the children, but we expect it to be empty
expect((d3.select(this).selectAll('*') as any).length).toEqual(
undefined
)
})
})
})
describe('custom legend size', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
item: {
tile: {
width: 15,
height: 2
}
}
}
}
})
it('renders the legend item with the correct width and height', function() {
d3.selectAll('.c3-legend-item-tile').each(function() {
expect(d3.select(this).style('stroke-width')).toBe(
args.legend.item.tile.height + 'px'
)
var tileWidth =
Number(d3.select(this).attr('x2')) -
Number(d3.select(this).attr('x1'))
expect(tileWidth).toBe(args.legend.item.tile.width)
})
})
})
describe('custom legend padding', function() {
beforeAll(function() {
args = {
data: {
columns: [
['padded1', 30, 200, 100, 400, 150, 250],
['padded2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
padding: 10
}
}
})
it('renders the correct amount of padding on the legend element', function() {
d3.selectAll(
'.c3-legend-item-padded1 .c3-legend-item-tile, .c3-legend-item-padded2 .c3-legend-item-tile'
).each(function(el, index) {
var itemWidth = (d3.select(this).node() as any).parentNode.getBBox()
.width,
textBoxWidth = (d3
.select((d3.select(this).node() as any).parentNode)
.select('text')
.node() as any).getBBox().width,
tileWidth = 17, // default value is 10, plus 7 more for padding @TODO verify this, seems PhantomJS@^2 adds another 1px to each side
expectedWidth =
textBoxWidth + tileWidth + (index ? 0 : 10) + args.legend.padding
expect(itemWidth).toBe(expectedWidth)
})
})
})
describe('legend item tile coloring with color_treshold', function() {
beforeAll(function() {
args = {
data: {
columns: [
['padded1', 100],
['padded2', 90],
['padded3', 50],
['padded4', 20]
]
},
type: 'gauge',
color: {
pattern: ['#FF0000', '#F97600', '#F6C600', '#60B044'],
threshold: {
values: [30, 80, 95]
}
}
}
})
// espacially for gauges with multiple arcs to have the same coloring between legend tiles, tooltip tiles and arc
it('selects the color from color_pattern if color_treshold is given', function() {
var tileColor = []
d3.selectAll('.c3-legend-item-tile').each(function() {
tileColor.push(d3.select(this).style('stroke'))
})
expect(tileColor[0]).toBe('rgb(96, 176, 68)')
expect(tileColor[1]).toBe('rgb(246, 198, 0)')
expect(tileColor[2]).toBe('rgb(249, 118, 0)')
expect(tileColor[3]).toBe('rgb(255, 0, 0)')
})
})
describe('legend item tile coloring with color_treshold (more than one data value)', function() {
beforeAll(function() {
args = {
data: {
columns: [
['padded1', 40, 60],
['padded2', 100, -10],
['padded3', 0, 50],
['padded4', 20, 0]
]
},
type: 'gauge',
color: {
pattern: ['#FF0000', '#F97600', '#F6C600', '#60B044'],
threshold: {
values: [30, 80, 95]
}
}
}
})
// espacially for gauges with multiple arcs to have the same coloring between legend tiles, tooltip tiles and arc
it('selects the color from color_pattern if color_treshold is given', function() {
var tileColor = []
d3.selectAll('.c3-legend-item-tile').each(function() {
tileColor.push(d3.select(this).style('stroke'))
})
expect(tileColor[0]).toBe('rgb(96, 176, 68)')
expect(tileColor[1]).toBe('rgb(246, 198, 0)')
expect(tileColor[2]).toBe('rgb(249, 118, 0)')
expect(tileColor[3]).toBe('rgb(255, 0, 0)')
})
})
describe('legend item tile coloring without color_treshold', function() {
beforeAll(function() {
args = {
data: {
columns: [
['padded1', 100],
['padded2', 90],
['padded3', 50],
['padded4', 20]
],
colors: {
padded1: '#60b044',
padded4: '#8b008b'
}
},
type: 'gauge'
}
})
it('selects the color from data_colors, data_color or default', function() {
var tileColor = []
d3.selectAll('.c3-legend-item-tile').each(function() {
tileColor.push(d3.select(this).style('stroke'))
})
expect(tileColor[0]).toBe('rgb(96, 176, 68)')
expect(tileColor[1]).toBe('rgb(31, 119, 180)')
expect(tileColor[2]).toBe('rgb(255, 127, 14)')
expect(tileColor[3]).toBe('rgb(139, 0, 139)')
})
})
}) | the_stack |
import browserEnv from '@ikscodes/browser-env';
import { MagicIncomingWindowMessage, MagicOutgoingWindowMessage, JsonRpcRequestPayload } from '@magic-sdk/types';
import _ from 'lodash';
import { createViewController } from '../../../factories';
import { JsonRpcResponse } from '../../../../src/core/json-rpc';
import * as storage from '../../../../src/util/storage';
import * as webCryptoUtils from '../../../../src/util/web-crypto';
import { SDKEnvironment } from '../../../../src/core/sdk-environment';
/**
* Create a dummy request payload.
*/
function requestPayload(id = 1): JsonRpcRequestPayload {
return {
id,
jsonrpc: '2.0',
method: 'eth_accounts',
params: [],
};
}
/**
* Create a dummy response payload.
*/
function responseEvent(values: { result?: any; error?: any; id?: number } = {}) {
return {
data: {
response: {
result: values.result ?? null,
error: values.error ?? null,
jsonrpc: '2.0',
id: values.id ?? 1,
},
},
};
}
/**
* Stub the `ViewController.on` method (hide implementation, only test
* `ViewController.post` logic).
*/
function stubViewController(viewController: any, events: [MagicIncomingWindowMessage, any][]) {
const timeouts = [];
const handlerSpy = jest.fn(() => timeouts.forEach((t) => t && clearTimeout(t)));
const onSpy = jest.fn((msgType, handler) => {
events.forEach((event, i) => {
if (msgType === event[0]) {
timeouts.push(setTimeout(() => handler(event[1]), 100 * (i + 1)));
}
});
return handlerSpy;
});
const postSpy = jest.fn();
viewController.on = onSpy;
viewController.ready = Promise.resolve();
viewController._post = postSpy;
return { handlerSpy, onSpy, postSpy };
}
let createJwtStub;
const FAKE_JWT_TOKEN = 'hot tokens';
const FAKE_RT = 'will freshen';
let FAKE_STORE: any = {};
beforeEach(() => {
jest.restoreAllMocks();
createJwtStub = jest.spyOn(webCryptoUtils, 'createJwt');
jest.spyOn(global.console, 'info').mockImplementation(() => {});
browserEnv();
browserEnv.stub('addEventListener', jest.fn());
jest.spyOn(storage, 'getItem').mockImplementation((key: string) => FAKE_STORE[key]);
jest.spyOn(storage, 'setItem').mockImplementation(async (key: string, value: any) => {
FAKE_STORE[key] = value;
});
SDKEnvironment.platform = 'web';
});
afterEach(() => {
FAKE_STORE = {};
});
test('Sends payload; recieves MAGIC_HANDLE_REQUEST event; resolves response', async () => {
createJwtStub.mockImplementationOnce(() => Promise.resolve(FAKE_JWT_TOKEN));
const viewController = createViewController('asdf');
const { handlerSpy, onSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent()],
]);
const payload = requestPayload();
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(onSpy.mock.calls[0][0]).toBe(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toBeCalledTimes(1);
expect(response).toEqual(new JsonRpcResponse(responseEvent().data.response));
});
test('Sends payload with jwt when web crypto is supported', async () => {
createJwtStub.mockImplementationOnce(() => Promise.resolve(FAKE_JWT_TOKEN));
const viewController = createViewController('asdf');
const { handlerSpy, onSpy, postSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent()],
]);
const payload = requestPayload();
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(onSpy.mock.calls[0][0]).toBe(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toHaveBeenCalledTimes(1);
expect(response).toEqual(new JsonRpcResponse(responseEvent().data.response));
expect(createJwtStub).toHaveBeenCalledWith();
expect(postSpy).toBeCalledWith(expect.objectContaining({ jwt: FAKE_JWT_TOKEN }));
});
test('Sends payload with rt and jwt when rt is saved', async () => {
createJwtStub.mockImplementationOnce(() => Promise.resolve(FAKE_JWT_TOKEN));
FAKE_STORE.rt = FAKE_RT;
const viewController = createViewController('asdf');
const { postSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent()],
]);
const payload = requestPayload();
await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(createJwtStub).toHaveBeenCalledWith();
expect(postSpy).toHaveBeenCalledWith(expect.objectContaining({ jwt: FAKE_JWT_TOKEN, rt: FAKE_RT }));
});
test('Sends payload without rt if no jwt can be made', async () => {
createJwtStub.mockImplementation(() => Promise.resolve(undefined));
FAKE_STORE.rt = FAKE_RT;
const viewController = createViewController('asdf');
const { postSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent()],
]);
const payload = requestPayload();
await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(postSpy).not.toBeCalledWith(expect.objectContaining({ rt: FAKE_RT }));
});
test('Sends payload when web crypto jwt fails', async () => {
const consoleErrorStub = jest.spyOn(global.console, 'error').mockImplementationOnce(() => {});
createJwtStub.mockRejectedValueOnce('danger');
FAKE_STORE.rt = FAKE_RT;
const viewController = createViewController('asdf');
const { handlerSpy, onSpy, postSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent()],
]);
const payload = requestPayload();
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(onSpy.mock.calls[0][0]).toEqual(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toHaveBeenCalledTimes(1);
expect(response).toEqual(new JsonRpcResponse(responseEvent().data.response));
expect(createJwtStub).toHaveBeenCalledWith();
expect(consoleErrorStub).toHaveBeenCalled();
expect(postSpy).not.toHaveBeenCalledWith(expect.objectContaining({ jwt: FAKE_JWT_TOKEN }));
});
test('Sends payload and stores rt if response event contains rt', async () => {
const eventWithRt = { data: { ...responseEvent().data, rt: FAKE_RT } };
const viewController = createViewController('asdf');
const { handlerSpy, onSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, eventWithRt],
]);
const payload = requestPayload();
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(onSpy.mock.calls[0][0]).toEqual(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toHaveBeenCalled();
expect(response).toEqual(new JsonRpcResponse(responseEvent().data.response));
expect(FAKE_STORE.rt).toEqual(FAKE_RT);
});
test('does not call web crypto api if platform is not web', async () => {
SDKEnvironment.platform = 'react-native';
const eventWithRt = { data: { ...responseEvent().data } };
const viewController = createViewController('asdf');
const { handlerSpy, onSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, eventWithRt],
]);
const payload = requestPayload();
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(createJwtStub).not.toHaveBeenCalledWith();
expect(onSpy.mock.calls[0][0]).toEqual(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toHaveBeenCalled();
expect(response).toEqual(new JsonRpcResponse(responseEvent().data.response));
});
test('Sends payload recieves MAGIC_HANDLE_REQUEST event; skips payloads with non-matching ID; resolves response', async () => {
const viewController = createViewController('asdf');
const { handlerSpy, onSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent({ id: 1234 })], // Should be skipped
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, responseEvent()],
]);
const payload = requestPayload();
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(onSpy.mock.calls[0][0]).toEqual(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toHaveBeenCalledTimes(1);
expect(response).toEqual(new JsonRpcResponse(responseEvent().data.response));
});
test('Sends payload and standardizes malformed response', async () => {
const viewController = createViewController('asdf');
const payload = requestPayload();
stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, { data: { response: undefined } }],
]);
viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, payload);
expect(true).toBe(true);
});
test('Sends a batch payload and resolves with multiple responses', async () => {
const response1 = responseEvent({ result: 'one', id: 1 });
const response2 = responseEvent({ result: 'two', id: 2 });
const response3 = responseEvent({ result: 'three', id: 3 });
const viewController = createViewController('asdf');
const { handlerSpy, onSpy } = stubViewController(viewController, [
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, response1],
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, response2],
[MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE, response3],
]);
const payload1 = requestPayload(1);
const payload2 = requestPayload(2);
const payload3 = requestPayload(3);
const response = await viewController.post(MagicOutgoingWindowMessage.MAGIC_HANDLE_REQUEST, [
payload1,
payload2,
payload3,
]);
expect(onSpy.mock.calls[0][0]).toBe(MagicIncomingWindowMessage.MAGIC_HANDLE_RESPONSE);
expect(handlerSpy).toBeCalledTimes(1);
expect(response).toEqual([
new JsonRpcResponse(response1.data.response),
new JsonRpcResponse(response2.data.response),
new JsonRpcResponse(response3.data.response),
]);
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages an Express Route Connection.
*
* > **NOTE:** The provider status of the Express Route Circuit must be set as provisioned while creating the Express Route Connection. See more details [here](https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-circuit-portal-resource-manager#send-the-service-key-to-your-connectivity-provider-for-provisioning).
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleVirtualWan = new azure.network.VirtualWan("exampleVirtualWan", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* });
* const exampleVirtualHub = new azure.network.VirtualHub("exampleVirtualHub", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* virtualWanId: exampleVirtualWan.id,
* addressPrefix: "10.0.1.0/24",
* });
* const exampleExpressRouteGateway = new azure.network.ExpressRouteGateway("exampleExpressRouteGateway", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* virtualHubId: exampleVirtualHub.id,
* scaleUnits: 1,
* });
* const exampleExpressRoutePort = new azure.network.ExpressRoutePort("exampleExpressRoutePort", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* peeringLocation: "Equinix-Seattle-SE2",
* bandwidthInGbps: 10,
* encapsulation: "Dot1Q",
* });
* const exampleExpressRouteCircuit = new azure.network.ExpressRouteCircuit("exampleExpressRouteCircuit", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* expressRoutePortId: exampleExpressRoutePort.id,
* bandwidthInGbps: 5,
* sku: {
* tier: "Standard",
* family: "MeteredData",
* },
* });
* const exampleExpressRouteCircuitPeering = new azure.network.ExpressRouteCircuitPeering("exampleExpressRouteCircuitPeering", {
* peeringType: "AzurePrivatePeering",
* expressRouteCircuitName: exampleExpressRouteCircuit.name,
* resourceGroupName: exampleResourceGroup.name,
* sharedKey: "ItsASecret",
* peerAsn: 100,
* primaryPeerAddressPrefix: "192.168.1.0/30",
* secondaryPeerAddressPrefix: "192.168.2.0/30",
* vlanId: 100,
* });
* const exampleExpressRouteConnection = new azure.network.ExpressRouteConnection("exampleExpressRouteConnection", {
* expressRouteGatewayId: exampleExpressRouteGateway.id,
* expressRouteCircuitPeeringId: exampleExpressRouteCircuitPeering.id,
* });
* ```
*
* ## Import
*
* Express Route Connections can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:network/expressRouteConnection:ExpressRouteConnection example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Network/expressRouteGateways/expressRouteGateway1/expressRouteConnections/connection1
* ```
*/
export class ExpressRouteConnection extends pulumi.CustomResource {
/**
* Get an existing ExpressRouteConnection 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?: ExpressRouteConnectionState, opts?: pulumi.CustomResourceOptions): ExpressRouteConnection {
return new ExpressRouteConnection(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:network/expressRouteConnection:ExpressRouteConnection';
/**
* Returns true if the given object is an instance of ExpressRouteConnection. 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 ExpressRouteConnection {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === ExpressRouteConnection.__pulumiType;
}
/**
* The authorization key to establish the Express Route Connection.
*/
public readonly authorizationKey!: pulumi.Output<string | undefined>;
/**
* Is Internet security enabled for this Express Route Connection?
*/
public readonly enableInternetSecurity!: pulumi.Output<boolean | undefined>;
/**
* The ID of the Express Route Circuit Peering that this Express Route Connection connects with. Changing this forces a new resource to be created.
*/
public readonly expressRouteCircuitPeeringId!: pulumi.Output<string>;
/**
* The ID of the Express Route Gateway that this Express Route Connection connects with. Changing this forces a new resource to be created.
*/
public readonly expressRouteGatewayId!: pulumi.Output<string>;
/**
* The name which should be used for this Express Route Connection. Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* A `routing` block as defined below.
*/
public readonly routing!: pulumi.Output<outputs.network.ExpressRouteConnectionRouting>;
/**
* The routing weight associated to the Express Route Connection. Possible value is between `0` and `32000`. Defaults to `0`.
*/
public readonly routingWeight!: pulumi.Output<number | undefined>;
/**
* Create a ExpressRouteConnection 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: ExpressRouteConnectionArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ExpressRouteConnectionArgs | ExpressRouteConnectionState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ExpressRouteConnectionState | undefined;
inputs["authorizationKey"] = state ? state.authorizationKey : undefined;
inputs["enableInternetSecurity"] = state ? state.enableInternetSecurity : undefined;
inputs["expressRouteCircuitPeeringId"] = state ? state.expressRouteCircuitPeeringId : undefined;
inputs["expressRouteGatewayId"] = state ? state.expressRouteGatewayId : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["routing"] = state ? state.routing : undefined;
inputs["routingWeight"] = state ? state.routingWeight : undefined;
} else {
const args = argsOrState as ExpressRouteConnectionArgs | undefined;
if ((!args || args.expressRouteCircuitPeeringId === undefined) && !opts.urn) {
throw new Error("Missing required property 'expressRouteCircuitPeeringId'");
}
if ((!args || args.expressRouteGatewayId === undefined) && !opts.urn) {
throw new Error("Missing required property 'expressRouteGatewayId'");
}
inputs["authorizationKey"] = args ? args.authorizationKey : undefined;
inputs["enableInternetSecurity"] = args ? args.enableInternetSecurity : undefined;
inputs["expressRouteCircuitPeeringId"] = args ? args.expressRouteCircuitPeeringId : undefined;
inputs["expressRouteGatewayId"] = args ? args.expressRouteGatewayId : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["routing"] = args ? args.routing : undefined;
inputs["routingWeight"] = args ? args.routingWeight : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(ExpressRouteConnection.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering ExpressRouteConnection resources.
*/
export interface ExpressRouteConnectionState {
/**
* The authorization key to establish the Express Route Connection.
*/
authorizationKey?: pulumi.Input<string>;
/**
* Is Internet security enabled for this Express Route Connection?
*/
enableInternetSecurity?: pulumi.Input<boolean>;
/**
* The ID of the Express Route Circuit Peering that this Express Route Connection connects with. Changing this forces a new resource to be created.
*/
expressRouteCircuitPeeringId?: pulumi.Input<string>;
/**
* The ID of the Express Route Gateway that this Express Route Connection connects with. Changing this forces a new resource to be created.
*/
expressRouteGatewayId?: pulumi.Input<string>;
/**
* The name which should be used for this Express Route Connection. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A `routing` block as defined below.
*/
routing?: pulumi.Input<inputs.network.ExpressRouteConnectionRouting>;
/**
* The routing weight associated to the Express Route Connection. Possible value is between `0` and `32000`. Defaults to `0`.
*/
routingWeight?: pulumi.Input<number>;
}
/**
* The set of arguments for constructing a ExpressRouteConnection resource.
*/
export interface ExpressRouteConnectionArgs {
/**
* The authorization key to establish the Express Route Connection.
*/
authorizationKey?: pulumi.Input<string>;
/**
* Is Internet security enabled for this Express Route Connection?
*/
enableInternetSecurity?: pulumi.Input<boolean>;
/**
* The ID of the Express Route Circuit Peering that this Express Route Connection connects with. Changing this forces a new resource to be created.
*/
expressRouteCircuitPeeringId: pulumi.Input<string>;
/**
* The ID of the Express Route Gateway that this Express Route Connection connects with. Changing this forces a new resource to be created.
*/
expressRouteGatewayId: pulumi.Input<string>;
/**
* The name which should be used for this Express Route Connection. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A `routing` block as defined below.
*/
routing?: pulumi.Input<inputs.network.ExpressRouteConnectionRouting>;
/**
* The routing weight associated to the Express Route Connection. Possible value is between `0` and `32000`. Defaults to `0`.
*/
routingWeight?: pulumi.Input<number>;
} | the_stack |
import { Dao } from '../dao/dao';
import { GeoPackage } from '../geoPackage';
import { UserMappingTable } from '../extension/relatedTables/userMappingTable';
import { MediaTable } from '../extension/relatedTables/mediaTable';
import { SimpleAttributesTable } from '../extension/relatedTables/simpleAttributesTable';
import { UserRow } from './userRow';
import { RelationType } from '../extension/relatedTables/relationType';
import { UserTable } from './userTable';
import { MediaRow } from '../extension/relatedTables/mediaRow';
import { SimpleAttributesRow } from '../extension/relatedTables/simpleAttributesRow';
import { FeatureRow } from '../features/user/featureRow';
import { ExtendedRelation } from '../extension/relatedTables/extendedRelation';
import { DBValue } from '../db/dbAdapter';
import { GeoPackageDataType } from '../db/geoPackageDataType';
import { UserColumn } from './userColumn';
import { AlterTable } from '../db/alterTable';
import { CoreSQLUtils } from '../db/coreSQLUtils';
/**
* Abstract User DAO for reading user tables
* @class UserDao
* @extends Dao
* @param {module:db/geoPackageConnection~GeoPackageConnection} geoPackage connection
* @param {string} table table name
*/
export class UserDao<T extends UserRow> extends Dao<UserRow> {
table_name: string;
columns: string[];
protected _table: UserTable<UserColumn>;
protected constructor(geoPackage: GeoPackage, table: UserTable<UserColumn>) {
super(geoPackage);
this._table = table;
this.table_name = table.getTableName();
this.gpkgTableName = table.getTableName();
if (table.getPkColumn()) {
this.idColumns = [table.getPkColumn().getName()];
} else {
this.idColumns = [];
}
this.columns = table.getUserColumns().getColumnNames();
}
/**
* Creates a UserRow
* @param {Object} [results] results to create the row from if not specified, an empty row is created
* @return {module:user/userRow~UserRow}
*/
createObject(results: Record<string, DBValue>): UserRow {
if (results) {
return this.getRow(results);
}
return this.newRow();
}
/**
* Sets the value in the row
* @param {module:user/userRow~UserRow} object user row
* @param {Number} columnIndex index
* @param {Object} value value
*/
setValueInObject(object: T, columnIndex: number, value: any): void {
object.setValueNoValidationWithIndex(columnIndex, value);
}
/**
* Get a user row from the current results
* @param {Object} results result to create the row from
* @return {module:user/userRow~UserRow} the user row
*/
getRow(results: Record<string, DBValue>): UserRow {
if (results instanceof UserRow) {
return results;
}
if (!this.table) return undefined;
const columns = this.table.getColumnCount();
const columnTypes: { [key: string]: GeoPackageDataType } = {};
for (let i = 0; i < columns; i++) {
const column = this.table.getColumnWithIndex(i);
columnTypes[column.name] = column.dataType;
}
return this.newRow(columnTypes, results);
}
/**
* Get the table for this dao
* @return {module:user/userTable~UserTable}
*/
get table(): UserTable<UserColumn> {
return this._table;
}
/**
* Create a user row
* @param {module:db/geoPackageDataType[]} columnTypes column types
* @param {module:dao/columnValues~ColumnValues[]} values values
* @return {module:user/userRow~UserRow} user row
*/
newRow(columnTypes?: { [key: string]: GeoPackageDataType }, values?: Record<string, DBValue>): UserRow {
return new UserRow(this.table, columnTypes, values);
}
/**
* Links related rows together
* @param {module:user/userRow~UserRow} userRow user row
* @param {module:user/userRow~UserRow} relatedRow related row
* @param {string} relationType relation type
* @param {string|UserMappingTable} [mappingTable] mapping table
* @param {module:dao/columnValues~ColumnValues} [mappingColumnValues] column values
* @return {number}
*/
linkRelatedRow(
userRow: UserRow,
relatedRow: UserRow,
relationType: RelationType,
mappingTable?: string | UserMappingTable,
mappingColumnValues?: Record<string, any>,
): number {
const rte = this.geoPackage.relatedTablesExtension;
const baseTableName = userRow.table.getTableName();
const relatedTableName = relatedRow.table.getTableName();
const relationship = rte
.getRelationshipBuilder()
.setBaseTableName(baseTableName)
.setRelatedTableName(relatedTableName)
.setRelationType(relationType);
let mappingTableName: string;
if (!mappingTable || typeof mappingTable === 'string') {
mappingTable = mappingTable || baseTableName + '_' + relatedTableName;
relationship.setMappingTableName(mappingTable);
mappingTableName = mappingTable as string;
} else {
relationship.setUserMappingTable(mappingTable);
mappingTableName = mappingTable.getTableName();
}
rte.addRelationship(relationship);
const userMappingDao = rte.getMappingDao(mappingTableName);
const userMappingRow = userMappingDao.newRow();
userMappingRow.baseId = userRow.id;
userMappingRow.relatedId = relatedRow.id;
for (const column in mappingColumnValues) {
userMappingRow.setValueWithColumnName(column, mappingColumnValues[column]);
}
return userMappingDao.create(userMappingRow);
}
/**
* Links a user row to a feature row
* @param {module:user/userRow~UserRow} userRow user row
* @param {module:features/user/featureRow~FeatureRow} featureRow feature row
* @param {string|UserMappingTable} [mappingTable] mapping table
* @param {module:dao/columnValues~ColumnValues} [mappingColumnValues] column values
* @return {number}
*/
linkFeatureRow(
userRow: UserRow,
featureRow: FeatureRow,
mappingTable?: string | UserMappingTable,
mappingColumnValues?: Record<string, any>,
): number {
return this.linkRelatedRow(userRow, featureRow, RelationType.FEATURES, mappingTable, mappingColumnValues);
}
/**
* Links a user row to a media row
* @param {module:user/userRow~UserRow} userRow user row
* @param {module:extension/relatedTables~MediaRow} mediaRow media row
* @param {string|UserMappingTable} [mappingTable] mapping table
* @param {module:dao/columnValues~ColumnValues} [mappingColumnValues] column values
* @return {number}
*/
linkMediaRow(
userRow: UserRow,
mediaRow: MediaRow,
mappingTable?: string | UserMappingTable,
mappingColumnValues?: Record<string, any>,
): number {
return this.linkRelatedRow(userRow, mediaRow, RelationType.MEDIA, mappingTable, mappingColumnValues);
}
/**
* Links a user row to a simpleAttributes row
* @param {module:user/userRow~UserRow} userRow user row
* @param {module:extension/relatedTables~SimpleAttributesRow} simpleAttributesRow simple attributes row
* @param {string|UserMappingTable} [mappingTable] mapping table
* @param {module:dao/columnValues~ColumnValues} [mappingColumnValues] column values
* @return {number}
*/
linkSimpleAttributesRow(
userRow: UserRow,
simpleAttributesRow: SimpleAttributesRow,
mappingTable?: string | UserMappingTable,
mappingColumnValues?: Record<string, any>,
): number {
return this.linkRelatedRow(
userRow,
simpleAttributesRow,
RelationType.SIMPLE_ATTRIBUTES,
mappingTable,
mappingColumnValues,
);
}
/**
* Get all media rows that are linked to this user row
* @param {module:user/userRow~UserRow} userRow user row
* @return {module:extension/relatedTables~MediaRow[]}
*/
getLinkedMedia(userRow: UserRow): MediaRow[] {
const mediaRelations = this.mediaRelations;
const rte = this.geoPackage.relatedTablesExtension;
const linkedMedia: MediaRow[] = [];
for (let i = 0; i < mediaRelations.length; i++) {
const mediaRelation = mediaRelations[i];
const mediaDao = rte.getMediaDao(mediaRelation);
const userMappingDao = rte.getMappingDao(mediaRelation.mapping_table_name);
const mappings = userMappingDao.queryByBaseId(userRow.id);
for (let m = 0; m < mappings.length; m++) {
const relatedId = mappings[m].related_id;
linkedMedia.push(mediaDao.queryForId(relatedId) as MediaRow);
}
}
return linkedMedia;
}
/**
* Get all simple attribute rows that are linked to this user row
* @param {module:user/userRow~UserRow} userRow user row
* @return {module:extension/relatedTables~SimpleAttributeRow[]}
*/
getLinkedSimpleAttributes(userRow: UserRow): SimpleAttributesRow[] {
const simpleRelations = this.simpleAttributesRelations;
const rte = this.geoPackage.relatedTablesExtension;
const linkedSimpleAttributes: SimpleAttributesRow[] = [];
for (let i = 0; i < simpleRelations.length; i++) {
const simpleRelation = simpleRelations[i];
const simpleDao = rte.getSimpleAttributesDao(simpleRelation);
const userMappingDao = rte.getMappingDao(simpleRelation.mapping_table_name);
const mappings = userMappingDao.queryByBaseId(userRow.id);
for (let m = 0; m < mappings.length; m++) {
const relatedId = mappings[m].related_id;
linkedSimpleAttributes.push(simpleDao.queryForId(relatedId) as SimpleAttributesRow);
}
}
return linkedSimpleAttributes;
}
/**
* Get all feature rows that are linked to this user row
* @param {module:user/userRow~UserRow} userRow user row
* @return {module:features/user/featureRow~FeatureRow[]}
*/
getLinkedFeatures(userRow: UserRow): FeatureRow[] {
const featureRelations = this.featureRelations;
const rte = this.geoPackage.relatedTablesExtension;
const linkedFeatures: FeatureRow[] = [];
for (let i = 0; i < featureRelations.length; i++) {
const featureRelation = featureRelations[i];
const featureDao = this.geoPackage.getFeatureDao(featureRelation.base_table_name);
const userMappingDao = rte.getMappingDao(featureRelation.mapping_table_name);
const mappings = userMappingDao.queryByBaseId(userRow.id);
for (let m = 0; m < mappings.length; m++) {
const relatedId = mappings[m].related_id;
linkedFeatures.push(featureDao.queryForId(relatedId) as FeatureRow);
}
}
return linkedFeatures;
}
/**
* Get all simple attribute relations to this table
* @return {Object[]}
*/
get simpleAttributesRelations(): ExtendedRelation[] {
return this.getRelationsWithName(SimpleAttributesTable.RELATION_TYPE.name);
}
/**
* Get all feature relations to this table
* @return {Object[]}
*/
get featureRelations(): ExtendedRelation[] {
return this.getRelationsWithName(RelationType.FEATURES.name);
}
/**
* Get all media relations to this table
* @return {Object[]}
*/
get mediaRelations(): ExtendedRelation[] {
return this.getRelationsWithName(MediaTable.RELATION_TYPE.name);
}
/**
* Get all relations to this table with the specified name
* @param {string} name
* @return {Object[]}
*/
getRelationsWithName(name: string): ExtendedRelation[] {
return this.geoPackage.extendedRelationDao.getBaseTableRelationsWithName(this.table_name, name);
}
/**
* Get all relations to this table
* @return {Object[]}
*/
get relations(): ExtendedRelation[] {
return this.geoPackage.extendedRelationDao.getBaseTableRelations(this.table_name);
}
/**
* Gets the rows in this table by id
* @param {Number[]} ids ids to query for
* @return {Object[]}
*/
getRows(ids: number[]): T[] {
const rows: T[] = [];
for (let i = 0; i < ids.length; i++) {
const row = this.queryForId(ids[i]);
if (row) {
rows.push(row as T);
}
}
return rows;
}
/**
* Get count of all rows in this table
* @return {Number}
*/
getCount(): number {
return this.connection.count(this.table_name);
}
getTableName(): string {
return this.table_name;
}
/**
* Rename column
* @param columnName column name
* @param newColumnName new column name
*/
renameColumn(columnName: string, newColumnName: string) {
AlterTable.renameColumn(this.connection, this.table_name, columnName, newColumnName);
this._table.renameColumnWithName(columnName, newColumnName);
}
/**
* Add a new column
* @param column new column
*/
addColumn(column: UserColumn) {
AlterTable.addColumn(this.connection, this.table_name, column.getName(), CoreSQLUtils.columnDefinition(column));
this._table.addColumn(column);
}
/**
* Drop a colum
* @param index column index
*/
dropColumnWithIndex(index: number) {
this.dropColumn(this._table.getColumnNameWithIndex(index));
}
/**
* Drop a column
* @param columnName column name
*/
dropColumn(columnName: string) {
AlterTable.dropColumnForUserTable(this.connection, this.table, columnName);
}
/**
* Drop columns
* @param columns columns
*/
dropColumns(columns: UserColumn[]) {
let columnNames = [];
columns.forEach(column => {
columnNames.push(column.getName());
});
this.dropColumnNames(columnNames);
}
/**
* Drop columns
* @param indices column indexes
*/
dropColumnIndexes(indices: number[]) {
let columnNames = [];
indices.forEach(idx => {
columnNames.push(this._table.getColumnNameWithIndex(idx));
});
this.dropColumnNames(columnNames);
}
/**
* Drop columns
* @param columnNames column names
*/
dropColumnNames(columnNames: string[]) {
AlterTable.dropColumnsForUserTable(this.connection, this.table, columnNames);
}
/**
* Alter a column
* @param column column
*/
alterColumn(column: UserColumn) {
AlterTable.alterColumnForTable(this.connection, this.table, column);
}
/**
* Alter columns
* @param columns columns
*/
alterColumns(columns: UserColumn[]) {
AlterTable.alterColumnsForTable(this.connection, this.table, columns);
}
} | the_stack |
import * as Enums from "./enums";
import * as Utils from "./utils";
import { GlobalSettings } from "./shared";
import { ChannelAdapter } from "./channel-adapter";
import {
ActivityResponse,
IActivityRequest,
ActivityRequestTrigger,
SuccessResponse,
ErrorResponse,
LoginRequestResponse
} from "./activity-request";
import { Strings } from "./strings";
import {
SubmitAction,
ExecuteAction,
SerializationContext,
AdaptiveCard,
Action,
Input,
TokenExchangeResource,
AuthCardButton
} from "./card-elements";
import { Versions } from "./serialization";
import { HostConfig } from "./host-config";
function logEvent(level: Enums.LogLevel, message?: any, ...optionalParams: any[]) {
if (GlobalSettings.applets.logEnabled) {
if (GlobalSettings.applets.onLogEvent) {
GlobalSettings.applets.onLogEvent(level, message, optionalParams);
} else {
/* eslint-disable no-console */
switch (level) {
case Enums.LogLevel.Warning:
console.warn(message, optionalParams);
break;
case Enums.LogLevel.Error:
console.error(message, optionalParams);
break;
default:
console.log(message, optionalParams);
break;
}
/* eslint-enable no-console */
}
}
}
class ActivityRequest implements IActivityRequest {
constructor(
readonly action: ExecuteAction,
readonly trigger: ActivityRequestTrigger,
readonly consecutiveRefreshes: number
) {}
authCode?: string;
authToken?: string;
attemptNumber: number = 0;
onSend: (sender: ActivityRequest) => void;
// eslint-disable-next-line @typescript-eslint/require-await
async retryAsync(): Promise<void> {
if (this.onSend) {
this.onSend(this);
}
}
}
export class AdaptiveApplet {
private static readonly _submitMagicCodeActionId = "submitMagicCode";
private static readonly _cancelMagicCodeAuthActionId = "cancelMagicCodeAuth";
private _card?: AdaptiveCard;
private _cardPayload: any;
private _allowAutomaticCardUpdate: boolean = false;
private _refreshButtonHostElement: HTMLElement;
private _cardHostElement: HTMLElement;
private _progressOverlay?: HTMLElement;
private displayCard(card: AdaptiveCard) {
if (card.renderedElement) {
Utils.clearElementChildren(this._cardHostElement);
this._refreshButtonHostElement.style.display = "none";
this._cardHostElement.appendChild(card.renderedElement);
} else {
throw new Error("displayCard: undefined card.");
}
}
private showManualRefreshButton(refreshAction: ExecuteAction) {
const displayBuiltInManualRefreshButton = this.onShowManualRefreshButton
? this.onShowManualRefreshButton(this)
: true;
if (displayBuiltInManualRefreshButton) {
this._refreshButtonHostElement.style.display = "none";
let renderedRefreshButton: HTMLElement | undefined = undefined;
if (this.onRenderManualRefreshButton) {
renderedRefreshButton = this.onRenderManualRefreshButton(this);
} else {
let message = Strings.runtime.refreshThisCard();
if (GlobalSettings.applets.refresh.mode === Enums.RefreshMode.Automatic) {
let autoRefreshPausedMessage = Strings.runtime.automaticRefreshPaused();
if (autoRefreshPausedMessage[autoRefreshPausedMessage.length - 1] !== " ") {
autoRefreshPausedMessage += " ";
}
message = Strings.runtime.clckToRestartAutomaticRefresh();
}
const cardPayload = {
type: "AdaptiveCard",
version: "1.2",
body: [
{
type: "RichTextBlock",
horizontalAlignment: "right",
inlines: [
{
type: "TextRun",
text: message,
selectAction: {
type: "Action.Submit",
id: "refreshCard"
}
}
]
}
]
};
const card = new AdaptiveCard();
card.parse(cardPayload, new SerializationContext(Versions.v1_2));
card.onExecuteAction = (action: Action) => {
if (action.id === "refreshCard") {
Utils.clearElementChildren(this._refreshButtonHostElement);
this.internalExecuteAction(
refreshAction,
ActivityRequestTrigger.Automatic,
0
);
}
};
renderedRefreshButton = card.render();
}
if (renderedRefreshButton) {
Utils.clearElementChildren(this._refreshButtonHostElement);
this._refreshButtonHostElement.appendChild(renderedRefreshButton);
this._refreshButtonHostElement.style.removeProperty("display");
}
}
}
private createActivityRequest(
action: ExecuteAction,
trigger: ActivityRequestTrigger,
consecutiveRefreshes: number
): ActivityRequest | undefined {
if (this.card) {
const request = new ActivityRequest(action, trigger, consecutiveRefreshes);
request.onSend = (sender: ActivityRequest) => {
sender.attemptNumber++;
void this.internalSendActivityRequestAsync(request);
};
const cancel = this.onPrepareActivityRequest
? !this.onPrepareActivityRequest(this, request, action)
: false;
return cancel ? undefined : request;
} else {
throw new Error("createActivityRequest: no card has been set.");
}
}
private createMagicCodeInputCard(attemptNumber: number): AdaptiveCard {
const payload = {
type: "AdaptiveCard",
version: "1.0",
body: [
{
type: "TextBlock",
color: "attention",
text: attemptNumber === 1 ? undefined : "That didn't work... let's try again.",
wrap: true,
horizontalAlignment: "center"
},
{
type: "TextBlock",
text: 'Please login in the popup. You will obtain a magic code. Paste that code below and select "Submit"',
wrap: true,
horizontalAlignment: "center"
},
{
type: "Input.Text",
id: "magicCode",
placeholder: "Enter magic code"
},
{
type: "ActionSet",
horizontalAlignment: "center",
actions: [
{
type: "Action.Submit",
id: AdaptiveApplet._submitMagicCodeActionId,
title: "Submit"
},
{
type: "Action.Submit",
id: AdaptiveApplet._cancelMagicCodeAuthActionId,
title: "Cancel"
}
]
}
]
};
const card = new AdaptiveCard();
card.parse(payload);
return card;
}
private cancelAutomaticRefresh() {
if (this._allowAutomaticCardUpdate) {
logEvent(
Enums.LogLevel.Warning,
"Automatic card refresh has been cancelled as a result of the user interacting with the card."
);
}
this._allowAutomaticCardUpdate = false;
}
private createSerializationContext(): SerializationContext {
return this.onCreateSerializationContext
? this.onCreateSerializationContext(this)
: new SerializationContext();
}
private internalSetCard(payload: any, consecutiveRefreshes: number) {
if (typeof payload === "object" && payload["type"] === "AdaptiveCard") {
this._cardPayload = payload;
}
if (this._cardPayload) {
try {
const card = new AdaptiveCard();
if (this.hostConfig) {
card.hostConfig = this.hostConfig;
}
const serializationContext = this.createSerializationContext();
card.parse(this._cardPayload, serializationContext);
const doChangeCard = this.onCardChanging
? this.onCardChanging(this, this._cardPayload)
: true;
if (doChangeCard) {
this._card = card;
if (
this._card.authentication &&
this._card.authentication.tokenExchangeResource &&
this.onPrefetchSSOToken
) {
this.onPrefetchSSOToken(
this,
this._card.authentication.tokenExchangeResource
);
}
this._card.onExecuteAction = (action: Action) => {
// If the user takes an action, cancel any pending automatic refresh
this.cancelAutomaticRefresh();
this.internalExecuteAction(action, ActivityRequestTrigger.Manual, 0);
};
this._card.onInputValueChanged = (_input: Input) => {
// If the user modifies an input, cancel any pending automatic refresh
this.cancelAutomaticRefresh();
};
this._card.render();
if (this._card.renderedElement) {
this.displayCard(this._card);
if (this.onCardChanged) {
this.onCardChanged(this);
}
if (this._card.refresh) {
if (
GlobalSettings.applets.refresh.mode ===
Enums.RefreshMode.Automatic &&
consecutiveRefreshes <
GlobalSettings.applets.refresh
.maximumConsecutiveAutomaticRefreshes
) {
if (
GlobalSettings.applets.refresh.timeBetweenAutomaticRefreshes <=
0
) {
logEvent(
Enums.LogLevel.Info,
"Triggering automatic card refresh number " +
(consecutiveRefreshes + 1)
);
this.internalExecuteAction(
this._card.refresh.action,
ActivityRequestTrigger.Automatic,
consecutiveRefreshes + 1
);
} else {
logEvent(
Enums.LogLevel.Info,
"Scheduling automatic card refresh number " +
(consecutiveRefreshes + 1) +
" in " +
GlobalSettings.applets.refresh
.timeBetweenAutomaticRefreshes +
"ms"
);
const action = this._card.refresh.action;
this._allowAutomaticCardUpdate = true;
window.setTimeout(() => {
if (this._allowAutomaticCardUpdate) {
this.internalExecuteAction(
action,
ActivityRequestTrigger.Automatic,
consecutiveRefreshes + 1
);
}
}, GlobalSettings.applets.refresh.timeBetweenAutomaticRefreshes);
}
} else if (
GlobalSettings.applets.refresh.mode !== Enums.RefreshMode.Disabled
) {
if (consecutiveRefreshes > 0) {
logEvent(
Enums.LogLevel.Warning,
"Stopping automatic refreshes after " +
consecutiveRefreshes +
" consecutive refreshes."
);
} else {
logEvent(
Enums.LogLevel.Warning,
"The card has a refresh section, but automatic refreshes are disabled."
);
}
if (
GlobalSettings.applets.refresh
.allowManualRefreshesAfterAutomaticRefreshes ||
GlobalSettings.applets.refresh.mode === Enums.RefreshMode.Manual
) {
logEvent(Enums.LogLevel.Info, "Showing manual refresh button.");
this.showManualRefreshButton(this._card.refresh.action);
}
}
}
}
}
} catch (error) {
// Ignore all errors
logEvent(Enums.LogLevel.Error, "setCard: " + error);
}
}
}
private internalExecuteAction(
action: Action,
trigger: ActivityRequestTrigger,
consecutiveRefreshes: number
) {
if (action instanceof ExecuteAction) {
if (this.channelAdapter) {
const request = this.createActivityRequest(action, trigger, consecutiveRefreshes);
if (request) {
void request.retryAsync();
}
} else {
throw new Error("internalExecuteAction: No channel adapter set.");
}
}
if (this.onAction) {
this.onAction(this, action);
}
}
private createProgressOverlay(request: ActivityRequest): HTMLElement | undefined {
if (!this._progressOverlay) {
if (this.onCreateProgressOverlay) {
this._progressOverlay = this.onCreateProgressOverlay(this, request);
} else {
this._progressOverlay = document.createElement("div");
this._progressOverlay.className = "aaf-progress-overlay";
const spinner = document.createElement("div");
spinner.className = "aaf-spinner";
spinner.style.width = "28px";
spinner.style.height = "28px";
this._progressOverlay.appendChild(spinner);
}
}
return this._progressOverlay;
}
private removeProgressOverlay(request: IActivityRequest) {
if (this.onRemoveProgressOverlay) {
this.onRemoveProgressOverlay(this, request);
}
if (this._progressOverlay !== undefined) {
this.renderedElement.removeChild(this._progressOverlay);
this._progressOverlay = undefined;
}
}
private activityRequestSucceeded(
response: SuccessResponse,
parsedContent: string | AdaptiveCard | undefined
) {
if (this.onActivityRequestSucceeded) {
this.onActivityRequestSucceeded(this, response, parsedContent);
}
}
private activityRequestFailed(response: ErrorResponse): number {
return this.onActivityRequestFailed
? this.onActivityRequestFailed(this, response)
: GlobalSettings.applets.defaultTimeBetweenRetryAttempts;
}
private showAuthCodeInputDialog(request: ActivityRequest) {
const showBuiltInAuthCodeInputCard = this.onShowAuthCodeInputDialog
? this.onShowAuthCodeInputDialog(this, request)
: true;
if (showBuiltInAuthCodeInputCard) {
const authCodeInputCard = this.createMagicCodeInputCard(request.attemptNumber);
authCodeInputCard.render();
authCodeInputCard.onExecuteAction = (submitMagicCodeAction: Action) => {
if (this.card && submitMagicCodeAction instanceof SubmitAction) {
switch (submitMagicCodeAction.id) {
case AdaptiveApplet._submitMagicCodeActionId:
let authCode: string | undefined = undefined;
if (
submitMagicCodeAction.data &&
typeof (<any>submitMagicCodeAction.data)["magicCode"] === "string"
) {
authCode = (<any>submitMagicCodeAction.data)["magicCode"];
}
if (authCode) {
this.displayCard(this.card);
request.authCode = authCode;
void request.retryAsync();
} else {
alert("Please enter the magic code you received.");
}
break;
case AdaptiveApplet._cancelMagicCodeAuthActionId:
logEvent(Enums.LogLevel.Warning, "Authentication cancelled by user.");
this.displayCard(this.card);
break;
default:
logEvent(
Enums.LogLevel.Error,
"Unexpected action taken from magic code input card (id = " +
submitMagicCodeAction.id +
")"
);
alert(Strings.magicCodeInputCard.somethingWentWrong());
break;
}
}
};
this.displayCard(authCodeInputCard);
}
}
private async internalSendActivityRequestAsync(request: ActivityRequest) {
if (!this.channelAdapter) {
throw new Error("internalSendActivityRequestAsync: channelAdapter is not set.");
}
const overlay = this.createProgressOverlay(request);
if (overlay !== undefined) {
this.renderedElement.appendChild(overlay);
}
let done = false;
while (!done) {
let response: ActivityResponse | undefined = undefined;
if (request.attemptNumber === 1) {
logEvent(
Enums.LogLevel.Info,
"Sending activity request to channel (attempt " + request.attemptNumber + ")"
);
} else {
logEvent(
Enums.LogLevel.Info,
"Re-sending activity request to channel (attempt " + request.attemptNumber + ")"
);
}
try {
response = await this.channelAdapter.sendRequestAsync(request);
} catch (error) {
logEvent(Enums.LogLevel.Error, "Activity request failed: " + error);
this.removeProgressOverlay(request);
done = true;
}
if (response) {
if (response instanceof SuccessResponse) {
this.removeProgressOverlay(request);
if (response.rawContent === undefined) {
throw new Error(
"internalSendActivityRequestAsync: Action.Execute result is undefined"
);
}
let parsedContent = response.rawContent;
try {
parsedContent = JSON.parse(response.rawContent);
} catch {
// Leave parseContent as is
}
if (typeof parsedContent === "string") {
logEvent(
Enums.LogLevel.Info,
"The activity request returned a string after " +
request.attemptNumber +
" attempt(s)."
);
this.activityRequestSucceeded(response, parsedContent);
} else if (
typeof parsedContent === "object" &&
parsedContent["type"] === "AdaptiveCard"
) {
logEvent(
Enums.LogLevel.Info,
"The activity request returned an Adaptive Card after " +
request.attemptNumber +
" attempt(s)."
);
this.internalSetCard(parsedContent, request.consecutiveRefreshes);
this.activityRequestSucceeded(response, this.card);
} else {
throw new Error(
"internalSendActivityRequestAsync: Action.Execute result is of unsupported type (" +
typeof response.rawContent +
")"
);
}
done = true;
} else if (response instanceof ErrorResponse) {
const retryIn: number = this.activityRequestFailed(response);
if (
retryIn >= 0 &&
request.attemptNumber < GlobalSettings.applets.maximumRetryAttempts
) {
logEvent(
Enums.LogLevel.Warning,
`Activity request failed: ${response.error.message}. Retrying in ${retryIn}ms`
);
request.attemptNumber++;
await new Promise<void>((resolve, _reject) => {
window.setTimeout(() => {
resolve();
}, retryIn);
});
} else {
logEvent(
Enums.LogLevel.Error,
`Activity request failed: ${response.error.message}. Giving up after ${request.attemptNumber} attempt(s)`
);
this.removeProgressOverlay(request);
done = true;
}
} else if (response instanceof LoginRequestResponse) {
logEvent(
Enums.LogLevel.Info,
"The activity request returned a LoginRequestResponse after " +
request.attemptNumber +
" attempt(s)."
);
if (request.attemptNumber <= GlobalSettings.applets.maximumRetryAttempts) {
let attemptOAuth = true;
if (response.tokenExchangeResource && this.onSSOTokenNeeded) {
// Attempt to use SSO. The host will return true if it can handle SSO, in which case
// we bypass OAuth
attemptOAuth = !this.onSSOTokenNeeded(
this,
request,
response.tokenExchangeResource
);
}
if (attemptOAuth) {
// Attempt to use OAuth
this.removeProgressOverlay(request);
if (response.signinButton === undefined) {
throw new Error(
"internalSendActivityRequestAsync: the login request doesn't contain a valid signin URL."
);
}
logEvent(
Enums.LogLevel.Info,
"Login required at " + response.signinButton.value
);
if (this.onShowSigninPrompt) {
// Bypass the built-in auth prompt if the host app handles it
this.onShowSigninPrompt(this, request, response.signinButton);
} else {
this.showAuthCodeInputDialog(request);
const left =
window.screenX +
(window.outerWidth - GlobalSettings.applets.authPromptWidth) /
2;
const top =
window.screenY +
(window.outerHeight - GlobalSettings.applets.authPromptHeight) /
2;
window.open(
response.signinButton.value,
response.signinButton.title
? response.signinButton.title
: "Sign in",
`width=${GlobalSettings.applets.authPromptWidth},height=${GlobalSettings.applets.authPromptHeight},left=${left},top=${top}`
);
}
}
} else {
logEvent(
Enums.LogLevel.Error,
"Authentication failed. Giving up after " +
request.attemptNumber +
" attempt(s)"
);
alert(Strings.magicCodeInputCard.authenticationFailed());
}
// Exit the loop. After a LoginRequestResponse, the host app is responsible for retrying the request
break;
} else {
throw new Error("Unhandled response type: " + JSON.stringify(response));
}
}
}
}
readonly renderedElement: HTMLElement;
hostConfig?: HostConfig;
channelAdapter?: ChannelAdapter;
onCardChanging?: (sender: AdaptiveApplet, card: any) => boolean;
onCardChanged?: (sender: AdaptiveApplet) => void;
onPrefetchSSOToken?: (
sender: AdaptiveApplet,
tokenExchangeResource: TokenExchangeResource
) => void;
onSSOTokenNeeded?: (
sender: AdaptiveApplet,
request: IActivityRequest,
tokenExchangeResource: TokenExchangeResource
) => boolean;
onPrepareActivityRequest?: (
sender: AdaptiveApplet,
request: IActivityRequest,
action: ExecuteAction
) => boolean;
onActivityRequestSucceeded?: (
sender: AdaptiveApplet,
response: SuccessResponse,
parsedContent: string | AdaptiveCard | undefined
) => void;
onActivityRequestFailed?: (sender: AdaptiveApplet, response: ErrorResponse) => number;
onCreateSerializationContext?: (sender: AdaptiveApplet) => SerializationContext;
onCreateProgressOverlay?: (
sender: AdaptiveApplet,
request: IActivityRequest
) => HTMLElement | undefined;
onRemoveProgressOverlay?: (sender: AdaptiveApplet, request: IActivityRequest) => void;
onRenderManualRefreshButton?: (sender: AdaptiveApplet) => HTMLElement | undefined;
onAction?: (sender: AdaptiveApplet, action: Action) => void;
onShowManualRefreshButton?: (sender: AdaptiveApplet) => boolean;
onShowAuthCodeInputDialog?: (sender: AdaptiveApplet, request: IActivityRequest) => boolean;
onShowSigninPrompt?: (
sender: AdaptiveApplet,
request: IActivityRequest,
signinButton: AuthCardButton
) => void;
constructor() {
this.renderedElement = document.createElement("div");
this.renderedElement.className = "aaf-cardHost";
this.renderedElement.style.position = "relative";
this.renderedElement.style.display = "flex";
this.renderedElement.style.flexDirection = "column";
this._cardHostElement = document.createElement("div");
this._refreshButtonHostElement = document.createElement("div");
this._refreshButtonHostElement.className = "aaf-refreshButtonHost";
this._refreshButtonHostElement.style.display = "none";
this.renderedElement.appendChild(this._cardHostElement);
this.renderedElement.appendChild(this._refreshButtonHostElement);
}
refreshCard() {
if (this._card && this._card.refresh) {
this.internalExecuteAction(this._card.refresh.action, ActivityRequestTrigger.Manual, 0);
}
}
setCard(payload: any) {
this.internalSetCard(payload, 0);
}
get card(): AdaptiveCard | undefined {
return this._card;
}
} | the_stack |
import * as vscode from 'vscode';
import fs = require('fs');
import path = require('path');
import Timeout from './timeout';
import glob = require('glob');
import rimraf = require('rimraf');
// import mkdirp = require('mkdirp');
import anymatch = require('anymatch');
// node 8.5 has natively fs.copyFile
// import copyFile = require('fs-copy-file');
import {IHistorySettings, HistorySettings} from './history.settings';
interface IHistoryActionValues {
active: string;
selected: string;
previous: string;
}
export interface IHistoryFileProperties {
dir: string;
name: string;
ext: string;
file?: string;
date?: Date;
history?: string[];
}
/**
* Controller for handling history.
*/
export class HistoryController {
private settings: HistorySettings;
private saveBatch;
private pattern = '_'+('[0-9]'.repeat(14));
private regExp = /_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/;
constructor() {
this.settings = new HistorySettings();
this.saveBatch = new Map();
}
public saveFirstRevision(document: vscode.TextDocument) {
// Put a timeout of 1000 ms, cause vscode wait until a delay and then continue the saving.
// Timeout avoid to save a wrong version, because it's to late and vscode has already saved the file.
// (if an error occured 3 times this code will not be called anymore.)
// cf. https://github.com/Microsoft/vscode/blob/master/src/vs/workbench/api/node/extHostDocumentSaveParticipant.ts
return this.internalSave(document, true, new Timeout(1000));
}
public saveRevision(document: vscode.TextDocument): Promise<vscode.TextDocument> {
return this.internalSave(document);
}
public showAll(editor: vscode.TextEditor) {
this.internalShowAll(this.actionOpen, editor, this.getSettings(editor.document.uri));
}
public showCurrent(editor: vscode.TextEditor) {
let document = (editor && editor.document);
if (document)
return this.internalOpen(this.findCurrent(document.fileName, this.getSettings(editor.document.uri)), editor.viewColumn);
}
public compareToActive(editor: vscode.TextEditor) {
this.internalShowAll(this.actionCompareToActive, editor, this.getSettings(editor.document.uri));
}
public compareToCurrent(editor: vscode.TextEditor) {
this.internalShowAll(this.actionCompareToCurrent, editor, this.getSettings(editor.document.uri));
}
public compareToPrevious(editor: vscode.TextEditor) {
this.internalShowAll(this.actionCompareToPrevious, editor, this.getSettings(editor.document.uri));
}
public compare(file1: vscode.Uri, file2: vscode.Uri, column?: string, range?: vscode.Range) {
return this.internalCompare(file1, file2, column, range);
}
public findAllHistory(fileName: string, settings: IHistorySettings, noLimit?: boolean): Promise<IHistoryFileProperties> {
return new Promise((resolve, reject) => {
if (!settings.enabled)
resolve();
let fileProperties = this.decodeFile(fileName, settings, true);
this.getHistoryFiles(fileProperties && fileProperties.file, settings, noLimit)
.then(files => {
fileProperties.history = files;
resolve(fileProperties);
})
.catch(err => reject(err));
});
}
public findGlobalHistory(find: string, findFile: boolean, settings: IHistorySettings, noLimit?: boolean): Promise<string[]> {
return new Promise((resolve, reject) => {
if (!settings.enabled)
resolve();
if (findFile)
this.findAllHistory(find, settings, noLimit)
.then(fileProperties => resolve(fileProperties && fileProperties.history));
else
this.getHistoryFiles(find, settings, noLimit)
.then(files => {
resolve(files);
})
.catch(err => reject(err));
});
}
public decodeFile(filePath: string, settings: IHistorySettings, history?: boolean): IHistoryFileProperties {
return this.internalDecodeFile(filePath, settings, history);
}
public getSettings(file: vscode.Uri): IHistorySettings {
return this.settings.get(file);
}
public clearSettings() {
this.settings.clear();
}
public deleteFile(fileName: string): Promise<void> {
return this.deleteFiles([fileName]);
}
public deleteFiles(fileNames: string[]): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.internalDeleteHistory(fileNames)
.then(() => resolve())
.catch((err) => reject());
});
}
public deleteAll(fileHistoryPath: string) {
return new Promise((resolve, reject) => {
rimraf(fileHistoryPath, err => {
if (err)
return reject(err);
return resolve();
});
});
}
public deleteHistory(fileName: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const settings = this.getSettings(vscode.Uri.file(fileName));
const fileProperties = this.decodeFile(fileName, settings, true);
this.getHistoryFiles(fileProperties && fileProperties.file, settings, true)
.then((files) => this.internalDeleteHistory(files))
.then(() => resolve())
.catch((err) => reject());
});
}
public restore(fileName: vscode.Uri) {
const src = fileName.fsPath;
const settings = this.getSettings(vscode.Uri.file(src));
const fileProperties = this.decodeFile(src, settings, false);
if (fileProperties && fileProperties.file) {
return new Promise((resolve, reject) => {
// Node v.8.5 has fs.copyFile
// const fnCopy = fs.copyFile || copyFile;
fs.copyFile(src, fileProperties.file, err => {
if (err)
return reject(err);
return resolve();
});
});
}
}
/* private */
private internalSave(document: vscode.TextDocument, isOriginal?: boolean, timeout?: Timeout): Promise<vscode.TextDocument> {
const settings = this.getSettings(document.uri);
if (!this.allowSave(settings, document)) {
return Promise.resolve(undefined);
}
if (!isOriginal && settings.saveDelay) {
if (!this.saveBatch.get(document.fileName)) {
this.saveBatch.set(document.fileName, document);
return this.timeoutPromise(this.internalSaveDocument, settings.saveDelay * 1000, [document, settings]);
} else return Promise.reject(undefined); // waiting
}
return this.internalSaveDocument(document, settings, isOriginal, timeout);
}
private timeoutPromise(f, delay, args): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => {
f.apply(this, args)
.then(value => resolve(value))
.catch(value => reject(value));
}, delay);
});
}
private internalSaveDocument(document: vscode.TextDocument, settings: IHistorySettings, isOriginal?: boolean, timeout?: Timeout): Promise<vscode.TextDocument> {
return new Promise((resolve, reject) => {
let revisionDir;
if (!settings.absolute) {
revisionDir = path.dirname(this.getRelativePath(document.fileName).replace(/\//g, path.sep));
} else {
revisionDir = this.normalizePath(path.dirname(document.fileName), false);
}
const p = path.parse(document.fileName);
const revisionPattern = this.joinPath(settings.historyPath, revisionDir, p.name, p.ext); // toto_[0-9]...
if (isOriginal) {
// if already some files exists, don't save an original version (cause: the really original version is lost) !
// (Often the case...)
const files = glob.sync(revisionPattern, {cwd: settings.historyPath.replace(/\\/g, '/')});
if (files && files.length > 0)
return resolve();
if (timeout && timeout.isTimedOut()) {
vscode.window.showErrorMessage(`Timeout when internalSave: ' ${document.fileName}`);
return reject('timedout');
}
}
else if (settings.saveDelay)
this.saveBatch.delete(document.fileName);
let now = new Date(),
nowInfo;
if (isOriginal) {
// find original date (if any)
const state = fs.statSync(document.fileName);
if (state)
now = state.mtime;
}
// remove 1 sec to original version, to avoid same name as currently version
now = new Date(now.getTime() - (now.getTimezoneOffset() * 60000) - (isOriginal ? 1000 : 0));
nowInfo = now.toISOString().substring(0, 19).replace(/[-:T]/g, '');
const revisionFile = this.joinPath(settings.historyPath, revisionDir, p.name, p.ext, `_${nowInfo}`); // toto_20151213215326.js
if (this.mkDirRecursive(revisionFile) && this.copyFile(document.fileName, revisionFile, timeout)) {
if (settings.daysLimit > 0 && !isOriginal)
this.purge(document, settings, revisionPattern);
return resolve(document);
} else
return reject('Error occured');
});
}
private allowSave(settings: IHistorySettings, document: vscode.TextDocument): boolean {
if (!settings.enabled) {
return false;
}
if (!(document && /*document.isDirty &&*/ document.fileName)) {
return false;
}
// Use '/' with glob
const docFile = document.fileName.replace(/\\/g, '/');
// @ts-ignore
if (settings.exclude && settings.exclude.length > 0 && anymatch(settings.exclude, docFile))
return false;
return true;
}
private getHistoryFiles(patternFilePath: string, settings: IHistorySettings, noLimit?: boolean): Promise<string[]> {
return new Promise((resolve, reject) => {
if (!patternFilePath)
reject('no pattern path');
// glob must use character /
const historyPath = settings.historyPath.replace(/\\/g, '/');
glob(patternFilePath, {cwd: historyPath, absolute: true}, (err, files: string[]) => {
if (!err) {
if (files && files.length) {
// files are sorted in ascending order
// limitation
if (settings.maxDisplay && !noLimit)
files = files.slice(settings.maxDisplay * -1);
// files are absolute
}
resolve(files);
} else
reject(err);
});
});
}
private internalShowAll(action, editor: vscode.TextEditor, settings: IHistorySettings) {
if (!settings.enabled)
return;
let me = this,
document = (editor && editor.document);
if (!document)
return;
me.findAllHistory(document.fileName, settings)
.then(fileProperties => {
const files = fileProperties.history;
if (!files || !files.length) {
return;
}
let displayFiles = [];
let file, relative, properties;
// desc order history
for (let index = files.length - 1; index >= 0; index--) {
file = files[index];
relative = path.relative(settings.historyPath, file);
properties = me.decodeFile(file, settings);
displayFiles.push({
description: relative,
label: properties.date.toLocaleString(settings.dateLocale),
filePath: file,
previous: files[index - 1]
});
}
vscode.window.showQuickPick(displayFiles)
.then(val=> {
if (val) {
let actionValues: IHistoryActionValues = {
active: document.fileName,
selected: val.filePath,
previous: val.previous
};
action.apply(me, [actionValues, editor]);
}
});
});
}
private actionOpen(values: IHistoryActionValues, editor: vscode.TextEditor) {
return this.internalOpen(vscode.Uri.file(values.selected), editor.viewColumn);
}
private actionCompareToActive(values: IHistoryActionValues, editor: vscode.TextEditor) {
return this.internalCompare(vscode.Uri.file(values.selected), vscode.Uri.file(values.active));
}
private actionCompareToCurrent(values: IHistoryActionValues, editor: vscode.TextEditor, settings: IHistorySettings) {
return this.internalCompare(vscode.Uri.file(values.selected), this.findCurrent(values.active, settings));
}
private actionCompareToPrevious(values: IHistoryActionValues, editor: vscode.TextEditor) {
if (values.previous)
return this.internalCompare(vscode.Uri.file(values.selected), vscode.Uri.file(values.previous));
}
private internalOpen(filePath: vscode.Uri, column: number) {
if (filePath)
return new Promise((resolve, reject) => {
vscode.workspace.openTextDocument(filePath)
.then(d=> {
vscode.window.showTextDocument(d, column)
.then(()=>resolve(), (err)=>reject(err));
}, (err)=>reject(err));
});
}
private internalCompare(file1: vscode.Uri, file2: vscode.Uri, column?: string, range?: vscode.Range) {
if (file1 && file2) {
const option: any = {};
if (column)
option.viewColumn = Number.parseInt(column, 10);
option.selection = range;
// Diff on the active column
let title = path.basename(file1.fsPath)+'<->'+path.basename(file2.fsPath);
vscode.commands.executeCommand('vscode.diff', file1, file2, title, option);
}
}
private internalDecodeFile(filePath: string, settings: IHistorySettings, history?: boolean): IHistoryFileProperties {
let me = this,
file, p,
date,
isHistory = false;
p = path.parse(filePath);
if (filePath.includes('/.history/') || filePath.includes('\\.history\\') ) { //startsWith(this.settings.historyPath))
isHistory = true;
let index = p.name.match(me.regExp);
if (index) {
date = new Date(index[1],index[2]-1,index[3],index[4],index[5],index[6]);
p.name = p.name.substring(0, index.index);
} else
return null; // file in history with bad pattern !
}
if (history != null) {
let root = '';
if (history !== isHistory) {
if (history === true) {
root = settings.historyPath;
if (!settings.absolute)
p.dir = path.relative(settings.folder.fsPath, p.dir);
else
p.dir = this.normalizePath(p.dir, false);
} else { // if (history === false)
p.dir = path.relative(settings.historyPath, p.dir);
if (!settings.absolute) {
root = settings.folder.fsPath;
} else {
root = '';
p.dir = this.normalizePath(p.dir, true);
}
}
}
file = me.joinPath(root, p.dir, p.name, p.ext, history ? undefined : '' );
}
else
file = filePath;
return {
dir: p.dir,
name: p.name,
ext: p.ext,
file: file,
date: date
};
}
private joinPath(root: string, dir: string, name: string, ext: string, pattern: string = this.pattern): string {
return path.join(root, dir, name + pattern + ext);
}
private findCurrent(activeFilename: string, settings: IHistorySettings): vscode.Uri {
if (!settings.enabled)
return vscode.Uri.file(activeFilename);
let fileProperties = this.decodeFile(activeFilename, settings, false);
if (fileProperties !== null)
return vscode.Uri.file(fileProperties.file);
else
return vscode.Uri.file(activeFilename);
}
private internalDeleteFile(fileName: string): Promise<any> {
return new Promise((resolve, reject) => {
fs.unlink(fileName, err => {
if (err)
// Not reject to avoid Promise.All to stop
return resolve({fileName: fileName, err: err});
return resolve(fileName);
});
});
}
private internalDeleteHistory(fileNames: string[]): Promise<void> {
return new Promise<void>((resolve, reject) => {
Promise.all(fileNames.map(file => this.internalDeleteFile(file)))
.then(results => {
// Display 1st error
results.some((item: any) => {
if (item.err) {
vscode.window.showErrorMessage(`Error when delete files history: '${item.err}' file '${item.fileName}`);
return true;
}
});
resolve();
})
.catch(() => reject());
});
}
private purge(document: vscode.TextDocument, settings: IHistorySettings, pattern: string) {
let me = this;
me.getHistoryFiles(pattern, settings, true)
.then(files => {
if (!files || !files.length) {
return;
}
let stat: fs.Stats,
now: number = new Date().getTime(),
endTime: number;
for (let file of files) {
stat = fs.statSync(file);
if (stat && stat.isFile()) {
endTime = stat.birthtime.getTime() + settings.daysLimit * 24*60*60*1000;
if (now > endTime) {
fs.unlinkSync(file);
}
}
}
});
}
private getRelativePath(fileName: string) {
let relative = vscode.workspace.asRelativePath(fileName, false);
if (fileName !== relative) {
return relative;
} else
return path.basename(fileName);
}
private mkDirRecursive(fileName: string): boolean {
try {
fs.mkdirSync(path.dirname(fileName), {recursive: true});
// mkdirp.sync(path.dirname(fileName));
return true;
}
catch (err) {
vscode.window.showErrorMessage(`Error with mkdir: '${err.toString()}' file '${fileName}`);
return false;
}
}
private copyFile(source: string, target: string, timeout?: Timeout): boolean {
try {
let buffer;
buffer = fs.readFileSync(source);
if (timeout && timeout.isTimedOut()) {
vscode.window.showErrorMessage(`Timeout when copyFile: ' ${source} => ${target}`);
return false;
}
fs.writeFileSync(target, buffer);
return true;
}
catch (err) {
vscode.window.showErrorMessage(`Error with copyFile: '${err.toString()} ${source} => ${target}`);
return false;
}
}
private normalizePath(dir: string, withDrive: boolean) {
if (process.platform === 'win32') {
if (!withDrive)
return dir.replace(':', '');
else
return dir.replace('\\', ':\\');
} else
return dir;
}
} | the_stack |
import * as coreHttp from "@azure/core-http";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { StorageClientContext } from "../storageClientContext";
import {
BlobServiceProperties,
ServiceSetPropertiesOptionalParams,
ServiceSetPropertiesResponse,
ServiceGetPropertiesOptionalParams,
ServiceGetPropertiesResponse,
ServiceGetStatisticsOptionalParams,
ServiceGetStatisticsResponse,
ServiceListContainersSegmentOptionalParams,
ServiceListContainersSegmentResponse,
KeyInfo,
ServiceGetUserDelegationKeyOptionalParams,
ServiceGetUserDelegationKeyResponse,
ServiceGetAccountInfoResponse,
ServiceSubmitBatchOptionalParams,
ServiceSubmitBatchResponse,
ServiceFilterBlobsOptionalParams,
ServiceFilterBlobsResponse
} from "../models";
/** Class representing a Service. */
export class Service {
private readonly client: StorageClientContext;
/**
* Initialize a new instance of the class Service class.
* @param client Reference to the service client
*/
constructor(client: StorageClientContext) {
this.client = client;
}
/**
* Sets properties for a storage account's Blob service endpoint, including properties for Storage
* Analytics and CORS (Cross-Origin Resource Sharing) rules
* @param blobServiceProperties The StorageService properties.
* @param options The options parameters.
*/
setProperties(
blobServiceProperties: BlobServiceProperties,
options?: ServiceSetPropertiesOptionalParams
): Promise<ServiceSetPropertiesResponse> {
const operationArguments: coreHttp.OperationArguments = {
blobServiceProperties,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
setPropertiesOperationSpec
) as Promise<ServiceSetPropertiesResponse>;
}
/**
* gets the properties of a storage account's Blob service, including properties for Storage Analytics
* and CORS (Cross-Origin Resource Sharing) rules.
* @param options The options parameters.
*/
getProperties(
options?: ServiceGetPropertiesOptionalParams
): Promise<ServiceGetPropertiesResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getPropertiesOperationSpec
) as Promise<ServiceGetPropertiesResponse>;
}
/**
* Retrieves statistics related to replication for the Blob service. It is only available on the
* secondary location endpoint when read-access geo-redundant replication is enabled for the storage
* account.
* @param options The options parameters.
*/
getStatistics(
options?: ServiceGetStatisticsOptionalParams
): Promise<ServiceGetStatisticsResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getStatisticsOperationSpec
) as Promise<ServiceGetStatisticsResponse>;
}
/**
* The List Containers Segment operation returns a list of the containers under the specified account
* @param options The options parameters.
*/
listContainersSegment(
options?: ServiceListContainersSegmentOptionalParams
): Promise<ServiceListContainersSegmentResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
listContainersSegmentOperationSpec
) as Promise<ServiceListContainersSegmentResponse>;
}
/**
* Retrieves a user delegation key for the Blob service. This is only a valid operation when using
* bearer token authentication.
* @param keyInfo Key information
* @param options The options parameters.
*/
getUserDelegationKey(
keyInfo: KeyInfo,
options?: ServiceGetUserDelegationKeyOptionalParams
): Promise<ServiceGetUserDelegationKeyResponse> {
const operationArguments: coreHttp.OperationArguments = {
keyInfo,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getUserDelegationKeyOperationSpec
) as Promise<ServiceGetUserDelegationKeyResponse>;
}
/**
* Returns the sku name and account kind
* @param options The options parameters.
*/
getAccountInfo(
options?: coreHttp.OperationOptions
): Promise<ServiceGetAccountInfoResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getAccountInfoOperationSpec
) as Promise<ServiceGetAccountInfoResponse>;
}
/**
* The Batch operation allows multiple API calls to be embedded into a single HTTP request.
* @param contentLength The length of the request.
* @param multipartContentType Required. The value of this header must be multipart/mixed with a batch
* boundary. Example header value: multipart/mixed; boundary=batch_<GUID>
* @param body Initial data
* @param options The options parameters.
*/
submitBatch(
contentLength: number,
multipartContentType: string,
body: coreHttp.HttpRequestBody,
options?: ServiceSubmitBatchOptionalParams
): Promise<ServiceSubmitBatchResponse> {
const operationArguments: coreHttp.OperationArguments = {
contentLength,
multipartContentType,
body,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
submitBatchOperationSpec
) as Promise<ServiceSubmitBatchResponse>;
}
/**
* The Filter Blobs operation enables callers to list blobs across all containers whose tags match a
* given search expression. Filter blobs searches across all containers within a storage account but
* can be scoped within the expression to a single container.
* @param options The options parameters.
*/
filterBlobs(
options?: ServiceFilterBlobsOptionalParams
): Promise<ServiceFilterBlobsResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
filterBlobsOperationSpec
) as Promise<ServiceFilterBlobsResponse>;
}
}
// Operation Specifications
const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true);
const setPropertiesOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "PUT",
responses: {
202: {
headersMapper: Mappers.ServiceSetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceSetPropertiesExceptionHeaders
}
},
requestBody: Parameters.blobServiceProperties,
queryParameters: [
Parameters.restype,
Parameters.comp,
Parameters.timeoutInSeconds
],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.contentType,
Parameters.accept,
Parameters.version,
Parameters.requestId
],
isXML: true,
contentType: "application/xml; charset=utf-8",
mediaType: "xml",
serializer: xmlSerializer
};
const getPropertiesOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BlobServiceProperties,
headersMapper: Mappers.ServiceGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceGetPropertiesExceptionHeaders
}
},
queryParameters: [
Parameters.restype,
Parameters.comp,
Parameters.timeoutInSeconds
],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.accept1
],
isXML: true,
serializer: xmlSerializer
};
const getStatisticsOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BlobServiceStatistics,
headersMapper: Mappers.ServiceGetStatisticsHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceGetStatisticsExceptionHeaders
}
},
queryParameters: [
Parameters.restype,
Parameters.timeoutInSeconds,
Parameters.comp1
],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.accept1
],
isXML: true,
serializer: xmlSerializer
};
const listContainersSegmentOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ListContainersSegmentResponse,
headersMapper: Mappers.ServiceListContainersSegmentHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceListContainersSegmentExceptionHeaders
}
},
queryParameters: [
Parameters.timeoutInSeconds,
Parameters.comp2,
Parameters.prefix,
Parameters.marker,
Parameters.maxPageSize,
Parameters.include
],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.accept1
],
isXML: true,
serializer: xmlSerializer
};
const getUserDelegationKeyOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.UserDelegationKey,
headersMapper: Mappers.ServiceGetUserDelegationKeyHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceGetUserDelegationKeyExceptionHeaders
}
},
requestBody: Parameters.keyInfo,
queryParameters: [
Parameters.restype,
Parameters.timeoutInSeconds,
Parameters.comp3
],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.contentType,
Parameters.accept,
Parameters.version,
Parameters.requestId
],
isXML: true,
contentType: "application/xml; charset=utf-8",
mediaType: "xml",
serializer: xmlSerializer
};
const getAccountInfoOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
200: {
headersMapper: Mappers.ServiceGetAccountInfoHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceGetAccountInfoExceptionHeaders
}
},
queryParameters: [Parameters.comp, Parameters.restype1],
urlParameters: [Parameters.url],
headerParameters: [Parameters.version, Parameters.accept1],
isXML: true,
serializer: xmlSerializer
};
const submitBatchOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "POST",
responses: {
202: {
bodyMapper: {
type: { name: "Stream" },
serializedName: "parsedResponse"
},
headersMapper: Mappers.ServiceSubmitBatchHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceSubmitBatchExceptionHeaders
}
},
requestBody: Parameters.body,
queryParameters: [Parameters.timeoutInSeconds, Parameters.comp4],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.contentType,
Parameters.accept,
Parameters.version,
Parameters.requestId,
Parameters.contentLength,
Parameters.multipartContentType
],
isXML: true,
contentType: "application/xml; charset=utf-8",
mediaType: "xml",
serializer: xmlSerializer
};
const filterBlobsOperationSpec: coreHttp.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FilterBlobSegment,
headersMapper: Mappers.ServiceFilterBlobsHeaders
},
default: {
bodyMapper: Mappers.StorageError,
headersMapper: Mappers.ServiceFilterBlobsExceptionHeaders
}
},
queryParameters: [
Parameters.timeoutInSeconds,
Parameters.marker,
Parameters.maxPageSize,
Parameters.comp5,
Parameters.where
],
urlParameters: [Parameters.url],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.accept1
],
isXML: true,
serializer: xmlSerializer
}; | the_stack |
import { Widget } from './Widget';
import { DragManager } from './event/DragManager';
import { Tween } from './Tween';
import { Ease } from './Ease/Ease';
import { Helpers } from './Helpers';
import { Sprite } from './Sprite';
import * as PIXI from 'pixi.js';
import { MeasureMode } from './IMeasurable';
export interface ISliderOptions
{
track?: PIXI.Container | Widget;
handle?: PIXI.Container | Widget;
fill?: Sprite;
orientation?: number;
value?: number;
minValue?: number;
maxValue?: number;
decimals?: number;
onValueChange?: () => void;
onValueChanging?: () => void;
}
/**
* @memberof PUXI
* @interface ISliderOptions
* @property {PIXI.Container}[track]
* @property {PIXI.Container}[handle]
*/
/**
* These options are used to configure a `PUXI.Slider`.
*
* @memberof PUXI
* @interface ISliderOptions
* @property {PIXI.Container}[track]
* @property {PIXI.Container}[fill]
* @property {boolean}[vertical]
* @property {number}[value]
* @property {number}[minValue]
* @property {number}[maxValue]
* @property {number}[decimals]
* @property {Function}[onValueChange]
* @property {Function}[onValueChanging]
*/
/**
* A slider is a form of input to set a variable to a value in a continuous
* range. It cannot have its own children.
*
* @memberof PUXI
* @class
* @extends PUXI.Widget
*/
export class Slider extends Widget
{
protected _disabled: boolean;
track: Widget;
handle: Widget;
fill: Sprite;
public readonly orientation: number;
protected percentValue: number;
protected _minValue: number;
protected _maxValue: number;
private _localCursor: PIXI.Point;
decimals: number;
vertical: boolean;
_lastChange: number;
_lastChanging: number;
onValueChange: (n: number) => void;
onValueChanging: (n: number) => void;
/**
* @param options {Object} Slider settings
* @param options.track {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} Any type of UIOBject, will be used for the slider track
* @param options.handle {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as slider handle
* @param [options.fill=null] {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used for slider fill
* @param [options.vertical=false] {boolean} Direction of the slider
* @param [options.value=0] {number} value of the slider
* @param [options.minValue=0] {number} minimum value
* @param [options.maxValue=100] {number} max value
* @param [options.decimals=0] {boolean} the decimal precision (use negative to round tens and hundreds)
* @param [options.onValueChange=null] {callback} Callback when the value has changed
* @param [options.onValueChanging=null] {callback} Callback while the value is changing
*/
constructor(options: ISliderOptions)
{
super();
/**
* The value expressed as a percentage from min. to max. This will always
* be between 0 and 1.
*
* The actual value is: `this.minValue + this.percentValue * (this.maxValue - this.minValue`).
*
* @member {number}
*/
this.percentValue = 0;
this._disabled = false;
this.fill = options.fill || null;
this.percentValue = this._minValue;
this._minValue = options.minValue || 0;
this._maxValue = options.maxValue || 100;
this.decimals = options.decimals || 0;
this.orientation = options.orientation || Slider.HORIZONTAL;
this.onValueChange = options.onValueChange || null;
this.onValueChanging = options.onValueChanging || null;
this.value = options.value || 50;
// set options
this.track = Widget.fromContent(options.track
|| (this.orientation === Slider.HORIZONTAL
? Slider.DEFAULT_HORIZONTAL_TRACK.clone()
: Slider.DEFAULT_VERTICAL_TRACK.clone()));
this.handle = Widget.fromContent(options.handle || Slider.DEFAULT_HANDLE.clone());
this.addChild(this.track, this.handle);// initialize(), update() usage
this._localCursor = new PIXI.Point();
this.handle.contentContainer.buttonMode = true;
}
initialize(): void
{
super.initialize();
let startValue = 0;
let trackSize;
const triggerValueChange = (): void =>
{
this.emit('change', this.value);
if (this._lastChange != this.value)
{
this._lastChange = this.value;
if (typeof this.onValueChange === 'function')
{
this.onValueChange(this.value);
}
}
};
const triggerValueChanging = (): void =>
{
this.emit('changing', this.value);
if (this._lastChanging != this.value)
{
this._lastChanging = this.value;
if (typeof this.onValueChanging === 'function')
{
this.onValueChanging(this.value);
}
}
};
const updatePositionToMouse = (mousePosition, soft): void =>
{
this.percentValue = this.getValueAtPhysicalPosition(mousePosition);
this.layoutHandle();
triggerValueChanging();
};
// Handles dragging
const handleDrag: DragManager = this.handle.eventBroker.dnd as DragManager;
handleDrag.onPress = (event: PIXI.interaction.InteractionEvent): void =>
{
event.stopPropagation();
};
handleDrag.onDragStart = (): void =>
{
startValue = this.percentValue;
trackSize = this.orientation === Slider.HORIZONTAL
? this.track.width
: this.track.height;
};
handleDrag.onDragMove = (event, offset: PIXI.Point): void =>
{
this.percentValue = Math.max(0, Math.min(
1,
startValue + ((this.orientation === Slider.HORIZONTAL ? offset.x : offset.y) / trackSize
)));
triggerValueChanging();
this.layoutHandle();
};
handleDrag.onDragEnd = (): void =>
{
triggerValueChange();
this.layoutHandle();
};
// Bar pressing/dragging
const trackDrag: DragManager = this.track.eventBroker.dnd as DragManager;
trackDrag.onPress = (event, isPressed): void =>
{
if (isPressed)
{
updatePositionToMouse(event.data.global, true);
}
event.stopPropagation();
};
trackDrag.onDragMove = (event: PIXI.interaction.InteractionEvent): void =>
{
updatePositionToMouse(event.data.global, false);
};
trackDrag.onDragEnd = (): void =>
{
triggerValueChange();
};
this.layoutHandle();
}
get value(): number
{
return Helpers.Round(Helpers.Lerp(this._minValue, this._maxValue, this.percentValue), this.decimals);
}
set value(val: number)
{
if (val === this.value)
{
return;
}
if (isNaN(val))
{
throw new Error('Cannot use NaN as a value');
}
this.percentValue = (Math.max(this._minValue, Math.min(this._maxValue, val)) - this._minValue) / (this._maxValue - this._minValue);
if (typeof this.onValueChange === 'function')
{
this.onValueChange(this.value);
}
if (typeof this.onValueChanging === 'function')
{
this.onValueChanging(this.value);
}
if (this.handle && this.initialized)
{
this.layoutHandle();
}
}
get minValue(): number
{
return this._minValue;
}
set minValue(val: number)
{
this._minValue = val;
this.update();
}
get maxValue(): number
{
return this._maxValue;
}
set maxValue(val: number)
{
this._maxValue = val;
this.update();
}
get disabled(): boolean
{
return this._disabled;
}
set disabled(val: boolean)
{
if (val !== this._disabled)
{
this._disabled = val;
this.handle.contentContainer.buttonMode = !val;
this.handle.contentContainer.interactive = !val;
this.track.contentContainer.interactive = !val;
}
}
/**
* @protected
* @returns the amount of the freedom that handle has in physical units, i.e. pixels. This
* is the width of the track minus the handle's size.
*/
protected getPhysicalRange(): number
{
return this.orientation === Slider.HORIZONTAL
? this.contentWidth - this.handle.getMeasuredWidth()
: this.contentHeight - this.handle.getMeasuredHeight();
}
/**
* @protected
* @param {PIXI.Point} cursor
* @returns the value of the slider if the handle's center were (globally)
* positioned at the given point.
*/
protected getValueAtPhysicalPosition(cursor: PIXI.Point): number
{
// Transform position
const localCursor = this.contentContainer.toLocal(cursor, null, this._localCursor, true);
let offset: number;
let range: number;
if (this.orientation === Slider.HORIZONTAL)
{
const handleWidth = this.handle.getMeasuredWidth();
offset = localCursor.x - this.paddingLeft - (handleWidth / 4);
range = this.contentWidth - handleWidth;
}
else
{
const handleHeight = this.handle.getMeasuredHeight();
offset = localCursor.y - this.paddingTop - (handleHeight / 4);
range = this.contentHeight - handleHeight;
}
return offset / range;
}
/**
* Re-positions the handle. This should be called after `_value` has been changed.
*/
protected layoutHandle(): void
{
const handle = this.handle;
const handleWidth = handle.getMeasuredWidth();
const handleHeight = handle.getMeasuredHeight();
let width = this.width - this.paddingHorizontal;
let height = this.height - this.paddingVertical;
let handleX: number;
let handleY: number;
if (this.orientation === Slider.HORIZONTAL)
{
width -= handleWidth;
handleY = (height - handleHeight) / 2;
handleX = (width * this.percentValue);
}
else
{
height -= handleHeight;
handleX = (width - handleWidth) / 2;
handleY = (height * this.percentValue);
}
handle.layout(handleX, handleY, handleX + handleWidth, handleY + handleHeight);
}
/**
* Slider measures itself using the track's natural dimensions in its non-oriented
* direction. The oriented direction will be the equal the range's size times
* the track's resolution.
*
* @param width
* @param height
* @param widthMode
* @param heightMode
*/
onMeasure(width: number, height: number, widthMode: number, heightMode: number): void
{
const naturalWidth = ((this.orientation === Slider.HORIZONTAL)
? this._maxValue - this._minValue
: Math.max(this.handle.contentContainer.width, this.track.contentContainer.width))
+ this.paddingHorizontal;
const naturalHeight = ((this.orientation === Slider.VERTICAL)
? this._maxValue - this._minValue
: Math.max(this.handle.contentContainer.height, this.track.contentContainer.height))
+ this.paddingVertical;
switch (widthMode)
{
case MeasureMode.EXACTLY:
this._measuredWidth = width;
break;
case MeasureMode.UNBOUNDED:
this._measuredWidth = naturalWidth;
break;
case MeasureMode.AT_MOST:
this._measuredWidth = Math.min(width, naturalWidth);
break;
}
switch (heightMode)
{
case MeasureMode.EXACTLY:
this._measuredHeight = height;
break;
case MeasureMode.UNBOUNDED:
this._measuredHeight = naturalHeight;
break;
case MeasureMode.AT_MOST:
this._measuredHeight = Math.min(height, naturalHeight);
break;
}
}
/**
* `Slider` lays the track to fill all of its width and height. The handle is aligned
* in the middle in the non-oriented direction.
*
* @param l
* @param t
* @param r
* @param b
* @param dirty
* @override
*/
onLayout(l: number, t: number, r: number, b: number, dirty: boolean): void
{
super.onLayout(l, t, r, b, dirty);
const { handle, track } = this;
track.layout(0, 0, this.width - this.paddingHorizontal, this.height - this.paddingVertical);
// Layout doesn't scale the widget
// TODO: Create a Track widget, this won't work for custom tracks that don't wanna
// scale (and it looks ugly.)
track.insetContainer.width = track.width;
track.insetContainer.height = track.height;
handle.measure(this.width, this.height, MeasureMode.AT_MOST, MeasureMode.AT_MOST);
this.layoutHandle();
}
/**
* The default track for horizontally oriented sliders.
* @static
*/
static DEFAULT_HORIZONTAL_TRACK: PIXI.Graphics = new PIXI.Graphics()
.beginFill(0xffffff, 1)
.drawRect(0, 0, 16, 16) // natural width & height = 16
.endFill()
.lineStyle(1, 0x000000, 0.7, 1, true) // draw line in middle
.moveTo(1, 8)
.lineTo(15, 8);
/**
* The default track for vertically oriented sliders.
* @static
*/
static DEFAULT_VERTICAL_TRACK: PIXI.Graphics = new PIXI.Graphics()
.beginFill(0xffffff, 1)
.drawRect(0, 0, 16, 16) // natural width & height = 16
.endFill()
.lineStyle(1, 0x000000, 0.7, 1, true) // draw line in middle
.moveTo(8, 1)
.lineTo(8, 15);
/**
* @static
*/
static DEFAULT_HANDLE: PIXI.Graphics = new PIXI.Graphics()
.beginFill(0x000000)
.drawCircle(16, 16, 8)
.endFill()
.beginFill(0x000000, 0.5)
.drawCircle(16, 16, 16)
.endFill();
/**
* Horizontal orientation
* @static
*/
static HORIZONTAL = 0xff5;
/**
* Vertical orientation
* @static
*/
static VERTICAL = 0xffe;
} | the_stack |
import { encode, decode } from "https://unpkg.com/@msgpack/msgpack@2.7.2/mod.ts";
import type {
Body,
DocExampleEnum,
DocExampleStruct,
ExplicitedlyImportedType,
FlattenedStruct,
FloatingPoint,
FpAdjacentlyTagged,
FpFlatten,
FpInternallyTagged,
FpPropertyRenaming,
FpUntagged,
FpVariantRenaming,
GroupImportedType1,
GroupImportedType2,
HttpResult,
Int64,
MyDateTime,
Point,
ReduxAction,
Request,
RequestError,
Response,
Result,
SerdeAdjacentlyTagged,
SerdeFlatten,
SerdeInternallyTagged,
SerdePropertyRenaming,
SerdeUntagged,
SerdeVariantRenaming,
StateUpdate,
StructWithGenerics,
} from "./types.ts";
type FatPtr = bigint;
export type Imports = {
importFpAdjacentlyTagged: (arg: FpAdjacentlyTagged) => FpAdjacentlyTagged;
importFpEnum: (arg: FpVariantRenaming) => FpVariantRenaming;
importFpFlatten: (arg: FpFlatten) => FpFlatten;
importFpInternallyTagged: (arg: FpInternallyTagged) => FpInternallyTagged;
importFpStruct: (arg: FpPropertyRenaming) => FpPropertyRenaming;
importFpUntagged: (arg: FpUntagged) => FpUntagged;
importGenerics: (arg: StructWithGenerics<number>) => StructWithGenerics<number>;
importMultiplePrimitives: (arg1: number, arg2: string) => bigint;
importPrimitiveBool: (arg: boolean) => boolean;
importPrimitiveF32: (arg: number) => number;
importPrimitiveF64: (arg: number) => number;
importPrimitiveI16: (arg: number) => number;
importPrimitiveI32: (arg: number) => number;
importPrimitiveI64: (arg: bigint) => bigint;
importPrimitiveI8: (arg: number) => number;
importPrimitiveU16: (arg: number) => number;
importPrimitiveU32: (arg: number) => number;
importPrimitiveU64: (arg: bigint) => bigint;
importPrimitiveU8: (arg: number) => number;
importSerdeAdjacentlyTagged: (arg: SerdeAdjacentlyTagged) => SerdeAdjacentlyTagged;
importSerdeEnum: (arg: SerdeVariantRenaming) => SerdeVariantRenaming;
importSerdeFlatten: (arg: SerdeFlatten) => SerdeFlatten;
importSerdeInternallyTagged: (arg: SerdeInternallyTagged) => SerdeInternallyTagged;
importSerdeStruct: (arg: SerdePropertyRenaming) => SerdePropertyRenaming;
importSerdeUntagged: (arg: SerdeUntagged) => SerdeUntagged;
importString: (arg: string) => string;
importTimestamp: (arg: MyDateTime) => MyDateTime;
importVoidFunction: () => void;
log: (message: string) => void;
makeHttpRequest: (request: Request) => Promise<HttpResult>;
};
export type Exports = {
exportAsyncStruct?: (arg1: FpPropertyRenaming, arg2: bigint) => Promise<FpPropertyRenaming>;
exportFpAdjacentlyTagged?: (arg: FpAdjacentlyTagged) => FpAdjacentlyTagged;
exportFpEnum?: (arg: FpVariantRenaming) => FpVariantRenaming;
exportFpFlatten?: (arg: FpFlatten) => FpFlatten;
exportFpInternallyTagged?: (arg: FpInternallyTagged) => FpInternallyTagged;
exportFpStruct?: (arg: FpPropertyRenaming) => FpPropertyRenaming;
exportFpUntagged?: (arg: FpUntagged) => FpUntagged;
exportGenerics?: (arg: StructWithGenerics<number>) => StructWithGenerics<number>;
exportMultiplePrimitives?: (arg1: number, arg2: string) => bigint;
exportPrimitiveBool?: (arg: boolean) => boolean;
exportPrimitiveF32?: (arg: number) => number;
exportPrimitiveF64?: (arg: number) => number;
exportPrimitiveI16?: (arg: number) => number;
exportPrimitiveI32?: (arg: number) => number;
exportPrimitiveI64?: (arg: bigint) => bigint;
exportPrimitiveI8?: (arg: number) => number;
exportPrimitiveU16?: (arg: number) => number;
exportPrimitiveU32?: (arg: number) => number;
exportPrimitiveU64?: (arg: bigint) => bigint;
exportPrimitiveU8?: (arg: number) => number;
exportSerdeAdjacentlyTagged?: (arg: SerdeAdjacentlyTagged) => SerdeAdjacentlyTagged;
exportSerdeEnum?: (arg: SerdeVariantRenaming) => SerdeVariantRenaming;
exportSerdeFlatten?: (arg: SerdeFlatten) => SerdeFlatten;
exportSerdeInternallyTagged?: (arg: SerdeInternallyTagged) => SerdeInternallyTagged;
exportSerdeStruct?: (arg: SerdePropertyRenaming) => SerdePropertyRenaming;
exportSerdeUntagged?: (arg: SerdeUntagged) => SerdeUntagged;
exportString?: (arg: string) => string;
exportTimestamp?: (arg: MyDateTime) => MyDateTime;
exportVoidFunction?: () => void;
fetchData?: (rType: string) => Promise<Result<string, string>>;
init?: () => void;
reducerBridge?: (action: ReduxAction) => StateUpdate;
exportAsyncStructRaw?: (arg1: Uint8Array, arg2: bigint) => Promise<Uint8Array>;
exportFpAdjacentlyTaggedRaw?: (arg: Uint8Array) => Uint8Array;
exportFpEnumRaw?: (arg: Uint8Array) => Uint8Array;
exportFpFlattenRaw?: (arg: Uint8Array) => Uint8Array;
exportFpInternallyTaggedRaw?: (arg: Uint8Array) => Uint8Array;
exportFpStructRaw?: (arg: Uint8Array) => Uint8Array;
exportFpUntaggedRaw?: (arg: Uint8Array) => Uint8Array;
exportGenericsRaw?: (arg: Uint8Array) => Uint8Array;
exportMultiplePrimitivesRaw?: (arg1: number, arg2: Uint8Array) => bigint;
exportPrimitiveBoolRaw?: (arg: boolean) => boolean;
exportPrimitiveI16Raw?: (arg: number) => number;
exportPrimitiveI32Raw?: (arg: number) => number;
exportPrimitiveI64Raw?: (arg: bigint) => bigint;
exportPrimitiveI8Raw?: (arg: number) => number;
exportSerdeAdjacentlyTaggedRaw?: (arg: Uint8Array) => Uint8Array;
exportSerdeEnumRaw?: (arg: Uint8Array) => Uint8Array;
exportSerdeFlattenRaw?: (arg: Uint8Array) => Uint8Array;
exportSerdeInternallyTaggedRaw?: (arg: Uint8Array) => Uint8Array;
exportSerdeStructRaw?: (arg: Uint8Array) => Uint8Array;
exportSerdeUntaggedRaw?: (arg: Uint8Array) => Uint8Array;
exportStringRaw?: (arg: Uint8Array) => Uint8Array;
exportTimestampRaw?: (arg: Uint8Array) => Uint8Array;
fetchDataRaw?: (rType: Uint8Array) => Promise<Uint8Array>;
reducerBridgeRaw?: (action: Uint8Array) => Uint8Array;
};
/**
* Represents an unrecoverable error in the FP runtime.
*
* After this, your only recourse is to create a new runtime, probably with a different WASM plugin.
*/
export class FPRuntimeError extends Error {
constructor(message: string) {
super(message);
}
}
/**
* Creates a runtime for executing the given plugin.
*
* @param plugin The raw WASM plugin.
* @param importFunctions The host functions that may be imported by the plugin.
* @returns The functions that may be exported by the plugin.
*/
export async function createRuntime(
plugin: ArrayBuffer,
importFunctions: Imports
): Promise<Exports> {
const promises = new Map<FatPtr, ((result: FatPtr) => void) | FatPtr>();
function createAsyncValue(): FatPtr {
const len = 12; // std::mem::size_of::<AsyncValue>()
const fatPtr = malloc(len);
const [ptr] = fromFatPtr(fatPtr);
const buffer = new Uint8Array(memory.buffer, ptr, len);
buffer.fill(0);
return fatPtr;
}
function interpretSign(num: number, cap: number) {
if (num < cap) {
return num;
} else {
return num - (cap << 1);
}
}
function interpretBigSign(num: bigint, cap: bigint) {
if (num < cap) {
return num;
} else {
return num - (cap << 1n);
}
}
function parseObject<T>(fatPtr: FatPtr): T {
const [ptr, len] = fromFatPtr(fatPtr);
const buffer = new Uint8Array(memory.buffer, ptr, len);
const object = decode(buffer) as unknown as T;
free(fatPtr);
return object;
}
function promiseFromPtr(ptr: FatPtr): Promise<FatPtr> {
const resultPtr = promises.get(ptr);
if (resultPtr) {
if (typeof resultPtr === "function") {
throw new FPRuntimeError("Already created promise for this value");
}
promises.delete(ptr);
return Promise.resolve(resultPtr);
} else {
return new Promise((resolve) => {
promises.set(ptr, resolve as (result: FatPtr) => void);
});
}
}
function resolvePromise(asyncValuePtr: FatPtr, resultPtr: FatPtr) {
const resolve = promises.get(asyncValuePtr);
if (resolve) {
if (typeof resolve !== "function") {
throw new FPRuntimeError("Tried to resolve invalid promise");
}
promises.delete(asyncValuePtr);
resolve(resultPtr);
} else {
promises.set(asyncValuePtr, resultPtr);
}
}
function serializeObject<T>(object: T): FatPtr {
return exportToMemory(encode(object));
}
function exportToMemory(serialized: Uint8Array): FatPtr {
const fatPtr = malloc(serialized.length);
const [ptr, len] = fromFatPtr(fatPtr);
const buffer = new Uint8Array(memory.buffer, ptr, len);
buffer.set(serialized);
return fatPtr;
}
function importFromMemory(fatPtr: FatPtr): Uint8Array {
const [ptr, len] = fromFatPtr(fatPtr);
const buffer = new Uint8Array(memory.buffer, ptr, len);
const copy = new Uint8Array(len);
copy.set(buffer);
free(fatPtr);
return copy;
}
const { instance } = await WebAssembly.instantiate(plugin, {
fp: {
__fp_gen_import_fp_adjacently_tagged: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<FpAdjacentlyTagged>(arg_ptr);
return serializeObject(importFunctions.importFpAdjacentlyTagged(arg));
},
__fp_gen_import_fp_enum: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<FpVariantRenaming>(arg_ptr);
return serializeObject(importFunctions.importFpEnum(arg));
},
__fp_gen_import_fp_flatten: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<FpFlatten>(arg_ptr);
return serializeObject(importFunctions.importFpFlatten(arg));
},
__fp_gen_import_fp_internally_tagged: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<FpInternallyTagged>(arg_ptr);
return serializeObject(importFunctions.importFpInternallyTagged(arg));
},
__fp_gen_import_fp_struct: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<FpPropertyRenaming>(arg_ptr);
return serializeObject(importFunctions.importFpStruct(arg));
},
__fp_gen_import_fp_untagged: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<FpUntagged>(arg_ptr);
return serializeObject(importFunctions.importFpUntagged(arg));
},
__fp_gen_import_generics: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<StructWithGenerics<number>>(arg_ptr);
return serializeObject(importFunctions.importGenerics(arg));
},
__fp_gen_import_multiple_primitives: (arg1: number, arg2_ptr: FatPtr): bigint => {
const arg2 = parseObject<string>(arg2_ptr);
return interpretBigSign(importFunctions.importMultiplePrimitives(arg1, arg2), 9223372036854775808n);
},
__fp_gen_import_primitive_bool: (arg: boolean): boolean => {
return !!importFunctions.importPrimitiveBool(arg);
},
__fp_gen_import_primitive_f32: (arg: number): number => {
return importFunctions.importPrimitiveF32(arg);
},
__fp_gen_import_primitive_f64: (arg: number): number => {
return importFunctions.importPrimitiveF64(arg);
},
__fp_gen_import_primitive_i16: (arg: number): number => {
return interpretSign(importFunctions.importPrimitiveI16(arg), 32768);
},
__fp_gen_import_primitive_i32: (arg: number): number => {
return interpretSign(importFunctions.importPrimitiveI32(arg), 2147483648);
},
__fp_gen_import_primitive_i64: (arg: bigint): bigint => {
return interpretBigSign(importFunctions.importPrimitiveI64(arg), 9223372036854775808n);
},
__fp_gen_import_primitive_i8: (arg: number): number => {
return interpretSign(importFunctions.importPrimitiveI8(arg), 128);
},
__fp_gen_import_primitive_u16: (arg: number): number => {
return importFunctions.importPrimitiveU16(arg);
},
__fp_gen_import_primitive_u32: (arg: number): number => {
return importFunctions.importPrimitiveU32(arg);
},
__fp_gen_import_primitive_u64: (arg: bigint): bigint => {
return importFunctions.importPrimitiveU64(arg);
},
__fp_gen_import_primitive_u8: (arg: number): number => {
return importFunctions.importPrimitiveU8(arg);
},
__fp_gen_import_serde_adjacently_tagged: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<SerdeAdjacentlyTagged>(arg_ptr);
return serializeObject(importFunctions.importSerdeAdjacentlyTagged(arg));
},
__fp_gen_import_serde_enum: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<SerdeVariantRenaming>(arg_ptr);
return serializeObject(importFunctions.importSerdeEnum(arg));
},
__fp_gen_import_serde_flatten: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<SerdeFlatten>(arg_ptr);
return serializeObject(importFunctions.importSerdeFlatten(arg));
},
__fp_gen_import_serde_internally_tagged: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<SerdeInternallyTagged>(arg_ptr);
return serializeObject(importFunctions.importSerdeInternallyTagged(arg));
},
__fp_gen_import_serde_struct: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<SerdePropertyRenaming>(arg_ptr);
return serializeObject(importFunctions.importSerdeStruct(arg));
},
__fp_gen_import_serde_untagged: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<SerdeUntagged>(arg_ptr);
return serializeObject(importFunctions.importSerdeUntagged(arg));
},
__fp_gen_import_string: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<string>(arg_ptr);
return serializeObject(importFunctions.importString(arg));
},
__fp_gen_import_timestamp: (arg_ptr: FatPtr): FatPtr => {
const arg = parseObject<MyDateTime>(arg_ptr);
return serializeObject(importFunctions.importTimestamp(arg));
},
__fp_gen_import_void_function: () => {
importFunctions.importVoidFunction();
},
__fp_gen_log: (message_ptr: FatPtr) => {
const message = parseObject<string>(message_ptr);
importFunctions.log(message);
},
__fp_gen_make_http_request: (request_ptr: FatPtr): FatPtr => {
const request = parseObject<Request>(request_ptr);
const _async_result_ptr = createAsyncValue();
importFunctions.makeHttpRequest(request)
.then((result) => {
resolveFuture(_async_result_ptr, serializeObject(result));
})
.catch((error) => {
console.error(
'Unrecoverable exception trying to call async host function "make_http_request"',
error
);
});
return _async_result_ptr;
},
__fp_host_resolve_async_value: resolvePromise,
},
});
const getExport = <T>(name: string): T => {
const exp = instance.exports[name];
if (!exp) {
throw new FPRuntimeError(`Plugin did not export expected symbol: "${name}"`);
}
return exp as unknown as T;
};
const memory = getExport<WebAssembly.Memory>("memory");
const malloc = getExport<(len: number) => FatPtr>("__fp_malloc");
const free = getExport<(ptr: FatPtr) => void>("__fp_free");
const resolveFuture = getExport<(asyncValuePtr: FatPtr, resultPtr: FatPtr) => void>("__fp_guest_resolve_async_value");
return {
exportAsyncStruct: (() => {
const export_fn = instance.exports.__fp_gen_export_async_struct as any;
if (!export_fn) return;
return (arg1: FpPropertyRenaming, arg2: bigint) => {
const arg1_ptr = serializeObject(arg1);
return promiseFromPtr(export_fn(arg1_ptr, arg2)).then((ptr) => parseObject<FpPropertyRenaming>(ptr));
};
})(),
exportFpAdjacentlyTagged: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_adjacently_tagged as any;
if (!export_fn) return;
return (arg: FpAdjacentlyTagged) => {
const arg_ptr = serializeObject(arg);
return parseObject<FpAdjacentlyTagged>(export_fn(arg_ptr));
};
})(),
exportFpEnum: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_enum as any;
if (!export_fn) return;
return (arg: FpVariantRenaming) => {
const arg_ptr = serializeObject(arg);
return parseObject<FpVariantRenaming>(export_fn(arg_ptr));
};
})(),
exportFpFlatten: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_flatten as any;
if (!export_fn) return;
return (arg: FpFlatten) => {
const arg_ptr = serializeObject(arg);
return parseObject<FpFlatten>(export_fn(arg_ptr));
};
})(),
exportFpInternallyTagged: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_internally_tagged as any;
if (!export_fn) return;
return (arg: FpInternallyTagged) => {
const arg_ptr = serializeObject(arg);
return parseObject<FpInternallyTagged>(export_fn(arg_ptr));
};
})(),
exportFpStruct: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_struct as any;
if (!export_fn) return;
return (arg: FpPropertyRenaming) => {
const arg_ptr = serializeObject(arg);
return parseObject<FpPropertyRenaming>(export_fn(arg_ptr));
};
})(),
exportFpUntagged: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_untagged as any;
if (!export_fn) return;
return (arg: FpUntagged) => {
const arg_ptr = serializeObject(arg);
return parseObject<FpUntagged>(export_fn(arg_ptr));
};
})(),
exportGenerics: (() => {
const export_fn = instance.exports.__fp_gen_export_generics as any;
if (!export_fn) return;
return (arg: StructWithGenerics<number>) => {
const arg_ptr = serializeObject(arg);
return parseObject<StructWithGenerics<number>>(export_fn(arg_ptr));
};
})(),
exportMultiplePrimitives: (() => {
const export_fn = instance.exports.__fp_gen_export_multiple_primitives as any;
if (!export_fn) return;
return (arg1: number, arg2: string) => {
const arg2_ptr = serializeObject(arg2);
return interpretBigSign(export_fn(arg1, arg2_ptr), 9223372036854775808n);
};
})(),
exportPrimitiveBool: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_bool as any;
if (!export_fn) return;
return (arg: boolean) => !!export_fn(arg);
})(),
exportPrimitiveF32: instance.exports.__fp_gen_export_primitive_f32 as any,
exportPrimitiveF64: instance.exports.__fp_gen_export_primitive_f64 as any,
exportPrimitiveI16: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i16 as any;
if (!export_fn) return;
return (arg: number) => interpretSign(export_fn(arg), 32768);
})(),
exportPrimitiveI32: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i32 as any;
if (!export_fn) return;
return (arg: number) => interpretSign(export_fn(arg), 2147483648);
})(),
exportPrimitiveI64: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i64 as any;
if (!export_fn) return;
return (arg: bigint) => interpretBigSign(export_fn(arg), 9223372036854775808n);
})(),
exportPrimitiveI8: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i8 as any;
if (!export_fn) return;
return (arg: number) => interpretSign(export_fn(arg), 128);
})(),
exportPrimitiveU16: instance.exports.__fp_gen_export_primitive_u16 as any,
exportPrimitiveU32: instance.exports.__fp_gen_export_primitive_u32 as any,
exportPrimitiveU64: instance.exports.__fp_gen_export_primitive_u64 as any,
exportPrimitiveU8: instance.exports.__fp_gen_export_primitive_u8 as any,
exportSerdeAdjacentlyTagged: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_adjacently_tagged as any;
if (!export_fn) return;
return (arg: SerdeAdjacentlyTagged) => {
const arg_ptr = serializeObject(arg);
return parseObject<SerdeAdjacentlyTagged>(export_fn(arg_ptr));
};
})(),
exportSerdeEnum: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_enum as any;
if (!export_fn) return;
return (arg: SerdeVariantRenaming) => {
const arg_ptr = serializeObject(arg);
return parseObject<SerdeVariantRenaming>(export_fn(arg_ptr));
};
})(),
exportSerdeFlatten: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_flatten as any;
if (!export_fn) return;
return (arg: SerdeFlatten) => {
const arg_ptr = serializeObject(arg);
return parseObject<SerdeFlatten>(export_fn(arg_ptr));
};
})(),
exportSerdeInternallyTagged: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_internally_tagged as any;
if (!export_fn) return;
return (arg: SerdeInternallyTagged) => {
const arg_ptr = serializeObject(arg);
return parseObject<SerdeInternallyTagged>(export_fn(arg_ptr));
};
})(),
exportSerdeStruct: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_struct as any;
if (!export_fn) return;
return (arg: SerdePropertyRenaming) => {
const arg_ptr = serializeObject(arg);
return parseObject<SerdePropertyRenaming>(export_fn(arg_ptr));
};
})(),
exportSerdeUntagged: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_untagged as any;
if (!export_fn) return;
return (arg: SerdeUntagged) => {
const arg_ptr = serializeObject(arg);
return parseObject<SerdeUntagged>(export_fn(arg_ptr));
};
})(),
exportString: (() => {
const export_fn = instance.exports.__fp_gen_export_string as any;
if (!export_fn) return;
return (arg: string) => {
const arg_ptr = serializeObject(arg);
return parseObject<string>(export_fn(arg_ptr));
};
})(),
exportTimestamp: (() => {
const export_fn = instance.exports.__fp_gen_export_timestamp as any;
if (!export_fn) return;
return (arg: MyDateTime) => {
const arg_ptr = serializeObject(arg);
return parseObject<MyDateTime>(export_fn(arg_ptr));
};
})(),
exportVoidFunction: instance.exports.__fp_gen_export_void_function as any,
fetchData: (() => {
const export_fn = instance.exports.__fp_gen_fetch_data as any;
if (!export_fn) return;
return (rType: string) => {
const type_ptr = serializeObject(rType);
return promiseFromPtr(export_fn(type_ptr)).then((ptr) => parseObject<Result<string, string>>(ptr));
};
})(),
init: instance.exports.__fp_gen_init as any,
reducerBridge: (() => {
const export_fn = instance.exports.__fp_gen_reducer_bridge as any;
if (!export_fn) return;
return (action: ReduxAction) => {
const action_ptr = serializeObject(action);
return parseObject<StateUpdate>(export_fn(action_ptr));
};
})(),
exportAsyncStructRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_async_struct as any;
if (!export_fn) return;
return (arg1: Uint8Array, arg2: bigint) => {
const arg1_ptr = exportToMemory(arg1);
return promiseFromPtr(export_fn(arg1_ptr, arg2)).then(importFromMemory);
};
})(),
exportFpAdjacentlyTaggedRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_adjacently_tagged as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportFpEnumRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_enum as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportFpFlattenRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_flatten as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportFpInternallyTaggedRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_internally_tagged as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportFpStructRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_struct as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportFpUntaggedRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_fp_untagged as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportGenericsRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_generics as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportMultiplePrimitivesRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_multiple_primitives as any;
if (!export_fn) return;
return (arg1: number, arg2: Uint8Array) => {
const arg2_ptr = exportToMemory(arg2);
return interpretBigSign(export_fn(arg1, arg2_ptr), 9223372036854775808n);
};
})(),
exportPrimitiveBoolRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_bool as any;
if (!export_fn) return;
return (arg: boolean) => !!export_fn(arg);
})(),
exportPrimitiveI16Raw: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i16 as any;
if (!export_fn) return;
return (arg: number) => interpretSign(export_fn(arg), 32768);
})(),
exportPrimitiveI32Raw: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i32 as any;
if (!export_fn) return;
return (arg: number) => interpretSign(export_fn(arg), 2147483648);
})(),
exportPrimitiveI64Raw: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i64 as any;
if (!export_fn) return;
return (arg: bigint) => interpretBigSign(export_fn(arg), 9223372036854775808n);
})(),
exportPrimitiveI8Raw: (() => {
const export_fn = instance.exports.__fp_gen_export_primitive_i8 as any;
if (!export_fn) return;
return (arg: number) => interpretSign(export_fn(arg), 128);
})(),
exportSerdeAdjacentlyTaggedRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_adjacently_tagged as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportSerdeEnumRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_enum as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportSerdeFlattenRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_flatten as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportSerdeInternallyTaggedRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_internally_tagged as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportSerdeStructRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_struct as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportSerdeUntaggedRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_serde_untagged as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportStringRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_string as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
exportTimestampRaw: (() => {
const export_fn = instance.exports.__fp_gen_export_timestamp as any;
if (!export_fn) return;
return (arg: Uint8Array) => {
const arg_ptr = exportToMemory(arg);
return importFromMemory(export_fn(arg_ptr));
};
})(),
fetchDataRaw: (() => {
const export_fn = instance.exports.__fp_gen_fetch_data as any;
if (!export_fn) return;
return (rType: Uint8Array) => {
const type_ptr = exportToMemory(rType);
return promiseFromPtr(export_fn(type_ptr)).then(importFromMemory);
};
})(),
reducerBridgeRaw: (() => {
const export_fn = instance.exports.__fp_gen_reducer_bridge as any;
if (!export_fn) return;
return (action: Uint8Array) => {
const action_ptr = exportToMemory(action);
return importFromMemory(export_fn(action_ptr));
};
})(),
};
}
function fromFatPtr(fatPtr: FatPtr): [ptr: number, len: number] {
return [
Number.parseInt((fatPtr >> 32n).toString()),
Number.parseInt((fatPtr & 0xffff_ffffn).toString()),
];
}
function toFatPtr(ptr: number, len: number): FatPtr {
return (BigInt(ptr) << 32n) | BigInt(len);
} | the_stack |
type Upper = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" |
"N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z";
type Kebab<T extends string> = T extends `${infer L}${Upper}${infer R}` ?
T extends `${L}${infer U}${R}` ? `${L}-${Lowercase<U>}${Kebab<R>}` : T : T;
type KebabKeys<T> = { [K in keyof T as K extends string ? Kebab<K> : K]: T[K] };
declare namespace ZSoft {
interface ZingGridElementEventMap {
'menu:click': CustomEvent;
'cell:beforerender': CustomEvent;
'cell:click': CustomEvent;
'cell:closeedit': CustomEvent;
'cell:copy': CustomEvent;
'cell:mouseout': CustomEvent;
'cell:mouseover': CustomEvent;
'cell:openedit': CustomEvent;
'cell:paste': CustomEvent;
'cell:rightclick': CustomEvent;
'grid:beforerender': CustomEvent;
'grid:contextmenuclose': CustomEvent;
'grid:contextmenuopen': CustomEvent;
'grid:deselect': CustomEvent;
'grid:hydrate': CustomEvent;
'grid:keydownesc': CustomEvent;
'grid:pagechange': CustomEvent;
'grid:pagefirst': CustomEvent;
'grid:pagelast': CustomEvent;
'grid:pagenext': CustomEvent;
'grid:pageprev': CustomEvent;
'grid:pagesizechange': CustomEvent;
'grid:ready': CustomEvent;
'grid:refresh': CustomEvent;
'grid:render': CustomEvent;
'grid:scroll': CustomEvent;
'grid:search': CustomEvent;
'grid:select': CustomEvent;
'grid:selectall': CustomEvent;
'data:cell:beforechange': CustomEvent;
'data:cell:change': CustomEvent;
'data:load': CustomEvent;
'data:record:beforechange': CustomEvent;
'data:record:beforedelete': CustomEvent;
'data:record:beforeinsert': CustomEvent;
'data:record:change': CustomEvent;
'data:record:delete': CustomEvent;
'data:record:insert': CustomEvent;
'data:record:openinsert': CustomEvent;
'row:click': CustomEvent;
'row:mouseout': CustomEvent;
'row:mouseover': CustomEvent;
'row:select': CustomEvent;
'column:click': CustomEvent;
'column:filter': CustomEvent;
'column:mouseout': CustomEvent;
'column:mouseover': CustomEvent;
'card:click': CustomEvent;
'card:mouseout': CustomEvent;
'card:mouseover': CustomEvent;
'record:click': CustomEvent;
'record:mouseout': CustomEvent;
'record:mouseover': CustomEvent;
'header:click': CustomEvent;
}
interface ZingGridEventHandlers {
/**
* @description Fires the event when custom menu item is clicked.
*/
'onMenuClick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event before a cell is rendered.
*/
'onCellBeforerender'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when a click occurs to a cell.
*/
'onCellClick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the cell editor is closed.
*/
'onCellCloseedit'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when copying (ctrl+c) occurs in a cell.
*/
'onCellCopy'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when mouse is moved out of a cell.
*/
'onCellMouseout'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when mouse is moved over a cell.
*/
'onCellMouseover'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the cell editor is opened.
*/
'onCellOpenedit'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when pasting (ctrl+p) occurs in a cell.
*/
'onCellPaste'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when right click occurs on a cell.
*/
'onCellRightclick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event once before the grid renders.
*/
'onGridBeforerender'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the contextmenu is closed.
*/
'onGridContextmenuclose'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the contextmenu is opened.
*/
'onGridContextmenuopen'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when selection is deselected in the grid.
*/
'onGridDeselect'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the pre-rendered grid is finished being hydrated.
*/
'onGridHydrate'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the (Esc) key is pressed.
*/
'onGridKeydownesc'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when a page changes in the grid.
*/
'onGridPagechange'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the grid changes to the first page.
*/
'onGridPagefirst'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the grid changes to the last page.
*/
'onGridPagelast'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the grid changes to the next page.
*/
'onGridPagenext'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the grid changes to the previous page.
*/
'onGridPageprev'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the "page-size" (amount of rows displaying) changes on the grid.
*/
'onGridPagesizechange'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the grid ready event when grid is ready.
*/
'onGridReady'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when the grid is refreshed through grid controls or API method "refresh()".
*/
'onGridRefresh'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event once when grid renders.
*/
'onGridRender'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when scrolling occurs in grid.
*/
'onGridScroll'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when a the grid is searched.
*/
'onGridSearch'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when selection is made in the grid.
*/
'onGridSelect'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when selecting every cell (ctrl+a) in the grid.
*/
'onGridSelectall'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event before a single cell value is changed.
*/
'onDataCellBeforechange'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event after a single cell value is changed.
*/
'onDataCellChange'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event every time a new dataset is loaded in the grid.
*/
'onDataLoad'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event before a record (row) is changed.
*/
'onDataRecordBeforechange'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event before a record (row) is deleted from the grid.
*/
'onDataRecordBeforedelete'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event before a new record (row) is added to the grid.
*/
'onDataRecordBeforeinsert'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event after a record (row) is changed.
*/
'onDataRecordChange'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when a record (row) is deleted from the grid.
*/
'onDataRecordDelete'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event after a new record (row) is added to the grid.
*/
'onDataRecordInsert'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires event when the insert dialog is opened
*/
'onDataRecordOpeninsert'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the "row:click" and "record:click" event when a click occurs on a record (row).
*/
'onRowClick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when mouse is moved out a record (row).
*/
'onRowMouseout'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when mouse is moved over a record (row).
*/
'onRowMouseover'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires when the row selector changes
*/
'onRowSelect'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires event when click on a column.
*/
'onColumnClick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when a column is filtered.
*/
'onColumnFilter'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires event when mouseout on a column.
*/
'onColumnMouseout'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires event when mouseover on a column.
*/
'onColumnMouseover'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the "card:click" and "record:click" event when a click occurs on a record (card).
*/
'onCardClick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when mouse is moved out a record (card).
*/
'onCardMouseout'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the event when mouse is moved over a record (card).
*/
'onCardMouseover'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires the "row:click" and "record:click" event when a click occurs on a record (row).
*/
'onRecordClick'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires when the mouse cursor leaves the record (row).
*/
'onRecordMouseout'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires when the mouse cursor enter the record (row).
*/
'onRecordMouseover'?: ((this: Window, ev: CustomEvent) => any) | null;
/**
* @description Fires event when click on a header cell.
*/
'onHeaderClick'?: ((this: Window, ev: CustomEvent) => any) | null;
}
interface CatchAll {
[attr: string]: any;
}
namespace ZingGridAttributes {
interface ZGButton {
/**
* @description Sets the action of the button
*/
action?: string;
/**
* @description Presence of attribute determines if the button is disabled or not
*/
disabled?: boolean;
/**
* @description Sets the icon for the button
*/
icon?: string;
}
interface ZGCaption {
/**
* @description The alignment of content in the caption
*/
align?: string;
/**
* @description Indicates where to position the caption
*/
position?: string;
}
interface ZGCard {
/**
* @description Sets the custom editor
*/
editor?: string;
/**
* @description Points to an external template element to be used as the template for the card's editor
*/
editorTemplate?: string;
/**
* @description The return value of the method is set as the innerHTML of "<zg-card>". If nothing is returned,
* it will not change the currently rendered card. The method takes the paramters "data", "domCard", and "rowObject".
*/
renderer?: string;
/**
* @description Points to an external template element to be used as the template for the card's render.
*/
rendererTemplate?: string;
}
interface ZGCheckbox {
/**
* @description Presence of attribute determines if the checkbox is checked
*/
checked?: boolean;
}
interface ZGColumn {
/**
* @description Aligns the contents of the cell
*/
align?: 'center' | 'left' | 'right';
/**
* @description If the index is an array of objects, use array-index to indicate which index of the array object to include
*/
arrayIndex?: string;
/**
* @description If the index is an array, you can use array-slice to indicate which array indexes to include.
*/
arraySlice?: string | number;
/**
* @description The type of "word-break" style for body cells. When not set, "cell-break" style is "normal" by default.
* If the width of a column is set, "cell-break" is "word" by default.
*/
cellBreak?: 'all' | 'ellipsis' | 'normal' | 'word';
/**
* @description The class to be set directly on "<zg-cell>" within the column. "cell-class" applied to
* "<zg-column>" will overwrite the "cell-class" applied to "<zing-grid>".
*/
cellClass?: string;
/**
* @description Sets the execution method of custom 'icon' type tooltips to either activate on hover or click of the icon
*/
cellTooltipAction?: 'click' | 'hover';
/**
* @description Sets the hover delay in milliseconds before displaying the tooltip
*/
cellTooltipDelay?: number;
/**
* @description Specifies the icon to use for the cell tooltip trigger icon when using the info column type
*/
cellTooltipIcon?: string;
/**
* @description Sets the tooltip-position for the cell
*/
cellTooltipPosition?: 'top' | 'left' | 'right' | 'bottom';
/**
* @description Gets the name of the user's custom render function, on window, to use the function's return value as the tooltip content
*/
cellTooltipRenderer?: string;
/**
* @description Points to an external template element to be used as the template for the tooltip display
*/
cellTooltipTemplate?: string;
/**
* @description Sets the tooltip text for the cell of the column. Can pass this value to renderer or template if using
*/
cellTooltipText?: string;
/**
* @description Sets the style to use for the tooltips. Uses the "default" style by default. Can set to "system" to match the tooltips used on icons throughout "<zing-grid>".
*/
cellTooltipType?: 'default' | 'system';
/**
* @description When an additional HTML element is added to the renderer, as in the case of image and url,
* "content-style" will be put into a style attribute directly on the element.
*/
contentStyle?: string;
/**
* @description Sets the width of the content inside of the cell. Used on cells of column type
* "element", "iframe", "image", or "url".
*/
contentWidth?: string | number;
/**
* @description The data to display in each cell where the data value is null or undefined
*/
defaultDisplay?: string;
/**
* @description Renderer for the details page of a column.
* To use a custom renderer, the attribute should be set to the name of the function.
* The renderer function takes in the following arguments, "value of index" (for each index), "domCell", and "cellObject".
* The returned value of the renderer function is set as the innerHTML of the details dialog.
*/
detailsRenderer?: string;
/**
* @description Points to an external template element to be used as the template for the column's details
*/
detailsTemplate?: string;
/**
* @description Disables the drag state of a specific column when "column-drag" enabled on "<zing-grid>"
*/
drag?: 'disabled';
/**
* @description Overrides the default editor for the column. Can be set to a different built-in editor (based on type of column),
* custom editor, or "false" to turn off editor.
* If set to a custom editor, the attribute value should be set to the name of the object.
* See "Features" page on "Editing: Custom Editor Grid" for more details on custom editor.
*/
editor?: string | string;
/**
* @description Points to an external template element to be used as the template for the column's editor
*/
editorTemplate?: string;
/**
* @description Overrides the grid level "filter" attribute. Presence of attribute enables on "filter" column, otherwise
* set to "disabled" to disable.
*/
filter?: 'disabled' | boolean;
/**
* @description Sets the data field index to filter on if index itself has multiple fields. The value set in index is the default.
*/
filterIndex?: string;
/**
* @description The aggregate function, tokenized string, or function to evaluate for the foot cell of the column.
* If using a function, the function takes the parameters "columnData" and "columnFieldIndex".
*/
footCell?: 'sum' | 'avg' | 'max' | 'min' | 'count' | 'tokenized string' | 'functionName' | string;
/**
* @description The aggregate function to evaluate for the head cell of the column.
* If using a function, the function takes the parameters "columnData" and "columnFieldIndex".
*/
headCell?: 'sum' | 'avg' | 'max' | 'min' | 'count' | 'tokenized string' | 'functionName' | string;
/**
* @description The header name for the column. If it is not set, the default is to format the "index" value.
*/
header?: string;
/**
* @description Setting to "disabled" will turn off formatting on the header of the column. By default, headers will
* convert camel, dash, or kebab case to a properly spaced and capitalized string. Or
* set to a function name to customize formatting of header text. The custom function takes in two parameters,
* "index" and "headerText", and returns the formatted header text.
*/
headerAutoFormat?: 'disabled' | 'functionName' | string;
/**
* @description Sets the execution method of custom 'icon' type tooltips to either activate on hover or click of the icon
*/
headerTooltipAction?: 'click' | 'hover';
/**
* @description Sets the hover delay in milliseconds before displaying the header tooltip
*/
headerTooltipDelay?: number;
/**
* @description Specifies the icon to use for the header tooltip trigger icon
*/
headerTooltipIcon?: string;
/**
* @description Sets the tooltip icon position for the tooltip icon in the header cells
*/
headerTooltipIconPosition?: 'left' | 'right' | 'after-text';
/**
* @description Sets the tooltip-position for the header cell
*/
headerTooltipPosition?: 'top' | 'left' | 'right' | 'bottom';
/**
* @description Gets the name of the user's custom render function, on window, to use the function's return value as the tooltip content
*/
headerTooltipRenderer?: string;
/**
* @description Points to an external template element to be used as the template for the tooltip display
*/
headerTooltipTemplate?: string;
/**
* @description Sets the tooltip text for the header cell of the column. Can pass this value to renderer or template if using
*/
headerTooltipText?: string;
/**
* @description Sets what part of the header triggers the tooltip. If set to 'icon', an info icon is added to the header.
*/
headerTooltipTrigger?: 'text' | 'icon';
/**
* @description Sets the style to use for the tooltips. Uses the "default" style by default. Can set to "system" to match the tooltips used on icons throughout "<zing-grid>".
*/
headerTooltipType?: 'default' | 'system';
/**
* @description Presence of attribute hides the column
*/
hidden?: boolean;
/**
* @description A single index or multiple indices (separated by comma), to associate information in the data source
* to a column in the grid. Nested data keys are referenced by the member character "." (Ex. data.key).
*/
index?: string;
/**
* @description Localization code used with column type "currency" and "number"
*/
locale?: string;
/**
* @description The text to display in the control menu for the column. If it is not set, it is set to the header text.
*/
menuText?: string;
/**
* @description Sets the minimum width of the column in pixels
*/
minWidth?: number;
/**
* @description Overrides the default renderer for the column. Can be set to a different built-in or custom renderer.
* To use a custom renderer, the attribute should be set to the name of the function.
* The renderer function takes in the following arguments, "value of index" (for each index), "domCell", and "cellObject".
* The returned value of the renderer function is set as the innerHTML of the cell.
*/
renderer?: string;
/**
* @description Points to an external template element to be used as the template for the column's renderer
*/
rendererTemplate?: string;
/**
* @description Indicates that the column is required to have a value on edit
*/
required?: boolean;
/**
* @description Turns on column resizing for single column. Set to "disabled" to turn off resizing on a single column.
*/
resizable?: 'disabled';
/**
* @description Sets the maximum width the column can be set to when resizing
*/
resizableMaxWidth?: number;
/**
* @description Sets the minimum width the column can be set to when resizing
*/
resizableMinWidth?: number;
/**
* @description Modifies the default column resizable persistence. Set to "disabled" to turn off persistence on a single column.
*/
resizablePersistent?: boolean;
/**
* @description Turns off the search on a column if "search" is present on "<zing-grid>"
*/
search?: 'disabled';
/**
* @description If multiple indices are set, this is the string that separates them in the display. By default, it is a comma.
*/
separator?: string;
/**
* @description Turns off the sort on a column if "sort" is present on "<zing-grid>"
*/
sort?: 'disabled';
/**
* @description Presence of attribute sorts the column data in ascending order
*/
sortAsc?: boolean;
/**
* @description Presence of attribute sorts the column data in descending order
*/
sortDesc?: boolean;
/**
* @description Overrides default behavior for setting special sort for international data
*/
sortIntl?: 'disabled';
/**
* @description Overrides the default sorter for the column. It is also possible to override the column sorting by
* passing in method name of sort function instead or setting to "disabled" to disable sorting. Sorter function
* takes in two values (a, b) and returns 1, -1, or 0 indicating if "a > b", "a < b", or "a = b".
* Can also be set to a path in the dataset to perform the sort on. This is useful for sorting object indices.
*/
sorter?: string;
/**
* @description The type of the data stored in the column. The column renderer/editor will behave based on the column type.
*/
type?: 'boolean' | 'button' | 'currency' | 'custom' | 'date' | 'editor' | 'element' | 'email' | 'icon' | 'image' | 'iframe' | 'number' | 'password' | 'range' | 'remover' | 'row-number'
| 'select' | 'selector' | 'tel' | 'text' | 'toggle' | 'url';
/**
* @description Presence of attribute sets the button to be in a disabled state. Can also set to "true" or "false".
*/
typeButtonDisabled?: boolean;
/**
* @description When the column type is set to "button", use "typeButtonHander" to hook up a function call to the button click.
* Callback receives rowData, zg-cell DOM, and zg-cell object as arguments.
*/
typeButtonHandler?: string;
/**
* @description When the column type is set to "button", use "typeButtonIcon" to add an icon next to the rendered button in the cell
*/
typeButtonIcon?: string;
/**
* @description When the column type is set to "button", use "typeButtonLabel" to add a label to the rendered button in the cell
*/
typeButtonLabel?: string;
/**
* @description When the column type is set to "button", use "typeButtonURL" to add a shortcut handler on button click. The click will automatically open the url in a new window.
*/
typeButtonUrl?: string;
/**
* @description When the column type is set to "checkbox", use "typeCheckboxLabel" to add a label next to the rendered checkbox in the cell
*/
typeCheckboxLabel?: string;
/**
* @description The currency to be used in currency formatting.
* Currency is set using using the 3 letter currency code specified by ISO 4217 specification (https://en.wikipedia.org/wiki/ISO_4217)
*/
typeCurrency?: string;
/**
* @description The tokenized formatting for a date column
*/
typeDateFormat?: string;
/**
* @description Indicates if date should be displayed in FromNow format
*/
typeDateFromNow?: boolean;
/**
* @description Sets the attribute of the custom-element in the column when "<zg-column>" has "type" set to "element"
*/
typeElementAttributeName?: string;
/**
* @description Sets the tag to wrap content when "<zg-column>" has "type" set to "element".
* If "type-element-attribute-name" isn't set, it will put the rendered data into the body of the element.
* If "type-element-attribute-name" is set, it will set the attribute to the indexed value.
*/
typeElementTagName?: string;
/**
* @description Sets a "square" ratio instead of the default "16:9"
*/
typeIframeRatio?: 'square';
/**
* @description The alternative text used with the "image" type column
*/
typeImageAlt?: string;
/**
* @description The alternative shape to mask the image
*/
typeImageMask?: 'circle';
/**
* @description If the column type is "image", use the "type-image-src" attribute to set the src for the image. The src will be the index value by default.
*/
typeImageSrc?: string;
/**
* @description Indicates the exact numbers to display after the decimal
*/
typeNumberDecimals?: number;
/**
* @description Set to "disabled" to turn off default number formatting
*/
typeNumberFormatting?: 'disabled';
/**
* @description Indicates the maximum numbers to display after the decimal
*/
typeNumberMaxDecimals?: number;
/**
* @description When the column type is set to "radio", use "typeRadioOptions" to add rendered radio options in the cell.
* Can also set as array of name/value pairs where the name is displayed for the given value
*/
typeRadioOptions?: any[] | string;
/**
* @description Maximum value for the input box. Used with the "range" type column in edit mode.
*/
typeRangeMax?: number;
/**
* @description Minimum value for the input box. Used with "range" type column in edit mode.
*/
typeRangeMin?: number;
/**
* @description Specifies the step between each legal value for the input box. Used with "range" type column in edit mode.
*/
typeRangeStep?: number;
/**
* @description In edit mode, presence of attribute allows column type "select" to have multiple selections, instead of the default
* of a single selection
*/
typeSelectMultiple?: boolean;
/**
* @description To set the options for the select box for a "select" column when "editor" is enabled on "<zing-grid>".
* Can also set as array of name/value pairs where the name is displayed for the given value
*/
typeSelectOptions?: string | any[];
/**
* @description When the column type is set to "toggle", use "typeToggleOptions" to set the list of options for the display.
*/
typeToggleOptions?: any[];
/**
* @description When the column type is set, the render and value will be the same. This prevents the default creating of true/false for toggles.
*/
typeToggleRenderValue?: boolean;
/**
* @description If the column type is "url", use this attribute to reference any "<zg-icon>" within the library
* to replace the link text with this icon.
*/
typeUrlIcon?: 'link' | 'outsidearrow';
/**
* @description If the column type is "url", use the "type-url-src" attribute to set the src for the link. The link will be the index value by default.
*/
typeUrlSrc?: string;
/**
* @description If the column type is "url", use the "type-url-text" attribute to set the text displayed for the link.
*/
typeUrlText?: string;
/**
* @description Sets the color mode to configure the color picker. Choose between HSL, RGBA, and the default Hex.
*/
typeColorMode?: string;
/**
* @description Disable the default color swatch UI preview with a false value.
*/
typeColorPreview?: boolean;
/**
* @description Sets the validation error message for the column. Overrides any other settings.
*/
validationErrorMessage?: string;
/**
* @description Sets the validation required message for the column. Overrides any other settings.
*/
validationRequiredMessage?: string;
/**
* @description Sets the validation method for the column. Overrides the default for the column type
*/
validator?: string | string;
/**
* @description Used in the case of automatically removing columns on resize. Columns without a "visibility-priority" never
* gets removed. The rest of the columns are removed from highest "visibility-priority" value to the lowest.
*/
visibilityPriority?: number;
/**
* @description Sets the width of the column.
*/
width?: 'fit' | 'fitheader' | 'fitcontent' | 'stretch' | '10%' | '150px' | '150' | string | number;
}
interface ZGData {
/**
* @description Adapter is a shortcut to set known options for specific third party datasets. Currently supports "graphql" and "firebase".
* Developers could register their own custom adapters. For more information on custom adapters, visit Guides > ZingGrid Object > registerAdapter().
*/
adapter?: string;
/**
* @description Data for the grid presented as an array or object. If set as an attribute value, the
* data needs to be in JSON format.
*/
data?: any;
/**
* @description In the case of non-key based objects, the idKey can be set to indicate the id to send back to the datasource on CRUD commands.
* For example, if the READ URL was https://zinggrid-named.firebaseio.com/ then the UPDATE would be https://zinggrid-named.firebaseio.com/VALUE_OF_IDKEY.
*/
idKey?: string;
/**
* @description Used to set "<zg-param>", the configuration data for "<zg-data>". This should never be used directly as an attribute and
* is meant for object instantiation and for setting in JavaScript.
*/
options?: any;
/**
* @description Specifies the absolute or relative URL to fetch data from to populate the grid
*/
src?: string;
}
interface ZGDialog {
/**
* @description Callback method to call on custom dialog when the dialog's "cancel"
* button is clicked
*/
cancel?: string;
/**
* @description Callback method to call on custom dialog when the dialog's "confirm"
* button is clicked
*/
confirm?: string;
/**
* @description Sets the dialog's header 'label' text
*/
label?: string;
/**
* @description The presence of the specification-standard "open" attribute designates whether the dialog is shown or hidden
*/
open?: string;
}
interface ZGIcon {
/**
* @description Sets the icon type of "<zg-icon>"
*/
name?: string;
}
interface ZGInput {
/**
* @description The built-in behavior and display of the input. Gets and sets the associated grid property.
*/
action?: string;
/**
* @description The type of the input if not using a built-in action
*/
type?: string;
/**
* @description The value of the input
*/
value?: string;
}
interface ZGMenu {
/**
* @description Presence of attribute replaces the default context menu with a custom menu.
* If "replace" is not set, the custom menu will be appended to the end of the default menu.
*/
replace?: boolean;
}
interface ZGPager {
/**
* @description Sets the number of records or rows to display per page
*/
pageSize?: number;
/**
* @description Sets the number of cards to display per page when in card mode
*/
pageSizeCard?: number;
/**
* @description Sets the number of rows to display per page when in row mode
*/
pageSizeRow?: number;
/**
* @description Determines max number of page buttons to display. Default is 5.
*/
pagerButtonLimit?: number;
/**
* @description Determines which type of pagination to use, input or buttons
*/
pagerType?: string;
/**
* @description Indicates where to position the pager
*/
position?: string;
/**
* @description Sets the options for page size in "zg-option-list"
*/
sizeOptions?: string;
}
interface ZGParam {
/**
* @description Name of parameter
*/
name?: string;
/**
* @description The value for given data key. If the value is an object, format as JSON encoded version of string.
*/
value?: string;
}
interface ZGSource {
/**
* @description Indicates where to position the source
*/
position?: string;
}
interface ZGText {
/**
* @description Specifies what value to generate in text field. Current built-in options are
* pager-related information.
*/
value?: string;
}
interface ZingGrid {
/**
* @description Aligns the contents of all column's cells
*/
align?: 'center' | 'left' | 'right';
/**
* @description The caption for the grid
*/
caption?: string;
/**
* @description Specifies the defined "<zg-card>" of the grid. More appropriate to use "<zg-card>" in most cases or set the property programmatically.
*/
card?: any;
/**
* @description The type of "word-break" style for body cells. When not set, "cell-break" style is "normal" by default.
* If the width of a column is set, "cell-break" is "word" by default.
* To overwrite "cell-break" for cells in a specific column, set "cell-break" for that column.
*/
cellBreak?: 'all' | 'ellipsis' | 'normal' | 'word';
/**
* @description Adds a class to each "<zg-cell>" in the grid. This attribute can be applied to both
* "<zing-grid>" or "<zg-column>". If the attribute is applied to both, "<zg-column>"'s "cell-class" overwrites "<zing-grid>"'s "cell-class".
* To set a class conditionally, set "cell-class" to the name of the function, which takes in the arguments: "cellData", "domContainer", "cellObject".
*/
cellClass?: string;
/**
* @description Turns cell editing on or off. Automatically turned on when setting "editor" or "editor-controls".
*/
cellEditor?: 'disabled' | boolean;
/**
* @description Turns off keyboard nav cell focus if set to disabled
*/
cellFocus?: 'disabled';
/**
* @description Sets the execution method of custom 'icon' type tooltips to either activate on hover or click of the icon
*/
cellTooltipAction?: 'click' | 'hover';
/**
* @description Sets the hover delay in milliseconds before displaying the tooltip. If delay is not specified,
* it is 1000ms on cell tooltips without an icon and 0ms on cell tooltips with an icon.
*/
cellTooltipDelay?: number;
/**
* @description Specifies the icon to use for the info column types
*/
cellTooltipIcon?: string;
/**
* @description Sets the tooltip-position for the cell
*/
cellTooltipPosition?: 'top' | 'left' | 'right' | 'bottom';
/**
* @description Gets the name of the user's custom render function, on window, to use the function's return value as the tooltip content
*/
cellTooltipRenderer?: string;
/**
* @description Points to an external template element to be used as the template for the tooltip display
*/
cellTooltipTemplate?: string;
/**
* @description Sets the style to use for the tooltips. Uses the "default" style by default. Can set to "system" to match the tooltips used on icons throughout "<zing-grid>".
*/
cellTooltipType?: 'default' | 'system';
/**
* @description Adds a class to each "<zg-cell>" in targeted "<zg-column>". To
* apply a class conditionally, set the value to the name of the function to run
* on each cell value. The function takes the parameters "fieldIndex", "domContainer",
* and "colObject", and returns a string which is the class name to apply.
*/
colClass?: string;
/**
* @description Enables column dragging
*/
columnDrag?: boolean;
/**
* @description Specifies the action of dragging allowed. By default, if "column-drag" is
* enabled then "column-drag-action" is set ""both"". This property will turn on column-drag if not already set.
*/
columnDragAction?: 'reorder' | 'hide' | 'both';
/**
* @description Presence of attribute turns on column resizing for all columns
*/
columnResizable?: boolean;
/**
* @description Sets the maximum width columns can be set to when resizing
*/
columnResizableMaxWidth?: number;
/**
* @description Sets the minimum width columns can be set to when resizing
*/
columnResizableMinWidth?: number;
/**
* @description Presence of attribute displays column resizing for all columns without hover
*/
columnResizablePersistent?: boolean;
/**
* @description Sets the width each of the columns
*/
columnWidth?: 'fit' | 'fitheader' | 'fitcontent' | 'stretch' | '10%' | '150px' | '150' | string | number;
/**
* @description Specifies the columns of the grid. More appropriate to use "<zg-column>" in most cases or set the property programmatically.
*/
columns?: ZGColumn[];
/**
* @description Presence of attribute turns on the menu to show and hide columns
*/
columnsControl?: boolean;
/**
* @description Augments internal themes to a compact mode
*/
compact?: boolean;
/**
* @description Used to set multiple grid properties at once. This should never be used directly.
* This is meant for object instantiation.
*/
config?: any;
/**
* @description Turns off delete confirmation if set to disable
*/
confirmDelete?: 'disabled';
/**
* @description Enables the default "<zing-grid>" context menu or set to the id name of a custom "<zg-menu>". If
* set to a custom menu and "<zg-menu>" has the "replace" attribute present, then the custom menu will replace the context menu.
* Otherwise the contents of the custom menu is appended to the end of context menu.
*/
contextMenu?: string | boolean;
/**
* @description Data for the grid presented as an array or object
*/
data?: any;
/**
* @description The data to display in each cell where the data value is null or undefined
*/
defaultDisplay?: string;
/**
* @description Sets "<zg-dialog>" to display dialog and mask within the grid dimensions instead of the whole screen
*/
dialog?: boolean;
/**
* @description The HTML standard direction to indicate direction of grid's columns and text
*/
dir?: string;
/**
* @description Turns on the grid editor. Enables single cell editing via double click.
* Sets the editor to inline (default) or modal.
*/
editor?: 'modal' | boolean;
/**
* @description Adds columns for the editor controls. If it is added, default is "all".
*/
editorControls?: 'editor' | 'remover' | 'creator' | 'all' | boolean;
/**
* @description Enables filtering for all columns. Can be turned on/off individually via column.
*/
filter?: boolean;
/**
* @description Adds a class to each "<zg-cell>" in the "<zg-foot>". To
* apply a class conditionally, set the value to the name of the function to run
* on each cell value. The function takes the parameters "fieldIndex", "domContainer",
* and "colObject", and returns a string which is the class name to apply.
*/
footClass?: string;
/**
* @description Sets vertical, horizontal or both grid lines to the grid
*/
gridlines?: 'both' | 'horz' | 'horizontal' | 'vert' | 'vertical';
/**
* @description Adds a class to each "<zg-cell>" in the "<zg-head>". To
* apply a class conditionally, set the value to the name of the function to run
* on each cell value. The function takes the parameters "fieldIndex", "domContainer",
* and "colObject", and returns a string which is the class name to apply.
*/
headClass?: string;
/**
* @description Converts camel, dash, and kebab case to properly spaced and capitalized typography.
* Setting to "disabled" will turn off formatting on headers. Set to a function name to customize formatting of headers.
*/
headerAutoFormat?: string;
/**
* @description Sets the execution method of custom 'icon' type tooltips to either activate on hover or click of the icon
*/
headerTooltipAction?: 'click' | 'hover';
/**
* @description Sets the hover delay in milliseconds before displaying the header tooltip
*/
headerTooltipDelay?: number;
/**
* @description Specifies the icon to use for the header tooltip trigger icon
*/
headerTooltipIcon?: string;
/**
* @description Sets the tooltip icon position for the tooltip icon in the header cells
*/
headerTooltipIconPosition?: 'left' | 'right' | 'after-text';
/**
* @description Sets the tooltip-position for the header cell
*/
headerTooltipPosition?: 'top' | 'left' | 'right' | 'bottom';
/**
* @description Gets the name of the user's custom render function, on window, to use the function's return value as the tooltip content
*/
headerTooltipRenderer?: string;
/**
* @description Points to an external template element to be used as the template for the tooltip display
*/
headerTooltipTemplate?: string;
/**
* @description Sets what part of the header triggers the tooltip. If set to 'icon', an info icon is added to the header.
*/
headerTooltipTrigger?: 'text' | 'icon';
/**
* @description Sets the style to use for the tooltips. Uses the "default" style by default. Can set to "system" to match the tooltips used on icons throughout "<zing-grid>".
*/
headerTooltipType?: 'default' | 'system';
/**
* @description Sets the height of the grid. If the height is less than the size of the content, scrolling is added
* to grid body.
*/
height?: string | number;
/**
* @description Allows the user to change the grid icon set to an allowed 3rd-party type (e.g., Font-Awesome).
* To use a custom icon set, the icon set must first be registered.
*/
iconSet?: string;
/**
* @description If setting [icon-set="custom"], points to the custom JSON key/value mapping
*/
iconSetData?: string;
/**
* @description Sets the language to use for the grid
*/
lang?: string;
/**
* @description Sets the grid layout to be either "card" or "row" and adds "<zg-layout-controls>" to the grid.
* The default is based on the size of the user's screen, unless "layout" is set.
*/
layout?: 'card' | 'row';
/**
* @description When "layout" is set, by default "layout-controls" is enabled.
* To hide, set "layout-controls" to "disabled". Presence of this attribute will enable
* "<zg-layout-controls>" even if "layout" is not set.
*/
layoutControls?: 'disabled' | boolean;
/**
* @description Presence of attribute adds loading state to grid, which triggers "<zg-load-mask>" to show.
* This attribute allows styling the height of the grid (via CSS) before the data has loaded in the grid.
*/
loading?: boolean;
/**
* @description Sets the text to display in the "<zg-load-mask>" on data load
*/
loadingText?: string;
/**
* @description Set "loadmask="disabled"" to prevent the "<zg-load-mask>" from showing on data load.
*/
loadmask?: 'disabled';
/**
* @description Sets the message that appears in the "<zg-no-data>" element when there are no records
*/
noData?: string;
/**
* @description Sets the number of records or rows to display per page. Can be set only if "pager" is set.
*/
pageSize?: number;
/**
* @description Sets the number of cards to display per page when in card mode. Can be set only if "pager" is set.
*/
pageSizeCard?: number;
/**
* @description Sets the options for page size in "zg-option-list". Can be set only if "pager" is set.
*/
pageSizeOptions?: string;
/**
* @description Sets the number of rows to display per page when in row mode. Can be set only if "pager" is set.
*/
pageSizeRow?: number;
/**
* @description Adds pagination functionality and controls to the grid
*/
pager?: boolean;
/**
* @description Determines max number of page buttons to display. Default is 5.
*/
pagerButtonLimit?: number;
/**
* @description Sets pager position. Note: "pager" attribute or "<zg-pager>" must be present in
* order to position pager.
*/
pagerPosition?: 'top' | 'bottom';
/**
* @description Determines which type of pagination to use, input or buttons
*/
pagerType?: 'button-text' | 'button-arrows';
/**
* @description Name/Value pairs of "<zg-param>" values. More appropriate to use "<zg-param>" in most cases.
*/
params?: any;
/**
* @description Sets the total record count. Useful for "loadByPage" when the response packet
* does not return total count of records.
*/
recordCount?: number;
/**
* @description Adds a class to each "<zg-row>" element. To
* apply a class conditionally, set the value to the name of the function to run
* on each cell value. The function takes the parameters "data", "rowIndex" (1-based),
* "domRow", and "rowObject", and returns a string which is the class name to apply.
*/
rowClass?: string;
/**
* @description Sets the height of each row. By default, the row height is set to 'auto' where it will auto fit the content.
* In the case of frozen columns, the default row height is '48px' because there is a performance hit when using 'auto' with
* frozen columns.
*/
rowHeight?: string | number;
/**
* @description Adds "selector" type column to the rows as the first column
*/
rowSelector?: boolean;
/**
* @description Turns on the search feature and adds "<zg-search>" to the grid.
* The search button appears in the caption header.
*/
search?: boolean;
/**
* @description Turns on the selector feature on the grid and adds
* "<zg-selector-mask>" to the grid
*/
selector?: boolean;
/**
* @description Indicates that the grid was completely rendered on the server and embedded in the page
*/
serverRendered?: boolean;
/**
* @description Enables sorting on all columns. It is possible to disable specific columns
* via the column's object or setting "sort="disabled"" to specified columns.
*/
sort?: boolean;
/**
* @description Overrides default behavior for international sorting. Turn off international sorting with "sort-intl="disabled"".
*/
sortIntl?: 'disabled';
/**
* @description Override the column sorting by passing in method name of sort function instead. Sorter function
* takes in two values (a, b) and returns 1, -1, or 0 indicating if "a > b", "a < b", or "a = b".
*/
sorter?: string;
/**
* @description Defines the source of the data in the grid. Adds the "<zg-source>" element.
*/
source?: string;
/**
* @description Specifies the absolute or relative URL to fetch data from to populate the grid
*/
src?: string;
/**
* @description Adds a display button that launches the contextmenu.
*/
staticMenu?: boolean;
/**
* @description Changes the duration a status message will remain visible until it automatically closes (in milliseconds)
*/
statusDelay?: number;
/**
* @description Prevents status messages from automatically closing after a delay
*/
statusPersist?: boolean;
/**
* @description Positions the status message in one of nine positions relative to the grid
*/
statusPosition?: 'top left' | 'center left' | 'bottom left' | 'top center' | 'center' | 'bottom center' | 'top right' | 'center right' | 'bottom right' | 'bar';
/**
* @description Defines the regex expression for closing data binding
*/
templateEndDelimiter?: string;
/**
* @description Defines the regex expression for starting data binding
*/
templateStartDelimiter?: string;
/**
* @description Sets the theme of the grid. Built-in themes are specified by keyword, but custom theme
* names are also accepted by setting a URL path to your custom css theme file. For custom themes, on load set "theme"
* to the path to the custom theme file. After, set to theme name to switch themes.
*/
theme?: 'android' | 'black' | 'default' | 'dark' | 'ios' | 'urlToThemeFile' | 'customThemeName' | string;
/**
* @description Sets the default validation error message
*/
validationErrorMessage?: string;
/**
* @description Sets the default validation required message
*/
validationRequiredMessage?: string;
/**
* @description Internal attribute. Should not be set.
*/
viewport?: string;
/**
* @description Keeps current value of "viewport" and freezes the breakpoint
*/
viewportPause?: boolean;
/**
* @description Removes "viewport" attribute, disabling viewport resizing
*/
viewportStop?: boolean;
/**
* @description Sets custom "viewport" breakpoints (value string-object must be valid JSON).
* NOTE: If you don't set "mobile", the grid won't auto-set card or row mode.
*/
viewportTypes?: string;
/**
* @description Sets the width of the grid. If the width is less than the size of the content, scroll is added to "<zg-body>".
*/
width?: string | number;
/**
* @description Presence of attribute adds the classes, "zebra-1" and "zebra-2", alternating on "<zg-row>" elements. Setting to a
* list of class names will assign classes in sequential order. For conditional zebra classes, "zebra" also accepts name of function that
* returns a class name to use for zebra striping.
*/
zebra?: string;
}
}
type ZingGridConfig = ZingGridAttributes.ZingGrid;
interface NonoptionalAttributes {
/**
* @description Presence of attribute hides the column
*/
hidden: boolean;
/**
* @description Enables the default "<zing-grid>" context menu or set to the id name of a custom "<zg-menu>". If
* set to a custom menu and "<zg-menu>" has the "replace" attribute present, then the custom menu will replace the context menu.
* Otherwise the contents of the custom menu is appended to the end of context menu.
*/
contextMenu: string | boolean;
/**
* @description The HTML standard direction to indicate direction of grid's columns and text
*/
dir: string;
/**
* @description Sets the language to use for the grid
*/
lang: string;
}
interface ZGBody extends CatchAll, HTMLElement {}
interface ZGButton extends ZingGridAttributes.ZGButton, CatchAll, HTMLElement {}
interface ZGCaption extends ZingGridAttributes.ZGCaption, CatchAll, HTMLElement {}
interface ZGCard extends ZingGridAttributes.ZGCard, CatchAll, HTMLElement {}
interface ZGCell extends CatchAll, HTMLElement {}
interface ZGCheckbox extends ZingGridAttributes.ZGCheckbox, CatchAll, HTMLElement {}
interface ZGColgroup extends CatchAll, HTMLElement {}
interface ZGColumn extends NonoptionalAttributes, Omit<ZingGridAttributes.ZGColumn, 'accessKey'
| 'accessKeyLabel' | 'animationcancel_event' | 'animationend_event' | 'animationiteration_event' | 'animationstart_event' | 'attachInternals' | 'autocapitalize'
| 'beforeinput_event' | 'blur' | 'click' | 'contentEditable' | 'contextMenu' | 'dataset' | 'dir'
| 'draggable' | 'enterKeyHint' | 'focus' | 'gotpointercapture_event' | 'hidden' | 'inert' | 'innerText'
| 'input_event' | 'inputMode' | 'isContentEditable' | 'itemId' | 'itemProp' | 'itemRef' | 'itemScope'
| 'itemType' | 'itemValue' | 'lang' | 'lostpointercapture_event' | 'nonce' | 'offsetHeight' | 'offsetLeft'
| 'offsetParent' | 'offsetTop' | 'offsetWidth' | 'oncopy' | 'oncut' | 'onpaste' | 'outerText'
| 'pointercancel_event' | 'pointerdown_event' | 'pointerenter_event' | 'pointerleave_event' | 'pointermove_event' | 'pointerout_event' | 'pointerover_event'
| 'pointerrawupdate_event' | 'pointerup_event' | 'spellcheck' | 'tabIndex' | 'title' | 'transitioncancel_event' | 'transitionend_event'
| 'transitionrun_event' | 'transitionstart_event' | 'translate' | 'attributeStyleMap' | 'style'>, CatchAll, HTMLElement {}
interface ZGControlBar extends CatchAll, HTMLElement {}
interface ZGData extends ZingGridAttributes.ZGData, CatchAll, HTMLElement {}
interface ZGDialog extends ZingGridAttributes.ZGDialog, CatchAll, HTMLElement {}
interface ZGEditorRow extends CatchAll, HTMLElement {}
interface ZGFocus extends CatchAll, HTMLElement {}
interface ZGFoot extends CatchAll, HTMLElement {}
interface ZGFooter extends CatchAll, HTMLElement {}
interface ZGFrozenColgroup extends CatchAll, HTMLElement {}
interface ZGHead extends CatchAll, HTMLElement {}
interface ZGHeadCell extends CatchAll, HTMLElement {}
interface ZGHeader extends CatchAll, HTMLElement {}
interface ZGIcon extends ZingGridAttributes.ZGIcon, CatchAll, HTMLElement {}
interface ZGInput extends ZingGridAttributes.ZGInput, CatchAll, HTMLElement {}
interface ZGLayoutControls extends CatchAll, HTMLElement {}
interface ZGLoadMask extends CatchAll, HTMLElement {}
interface ZGMenu extends ZingGridAttributes.ZGMenu, CatchAll, HTMLElement {}
interface ZGMenuGroup extends CatchAll, HTMLElement {}
interface ZGMenuItem extends CatchAll, HTMLElement {}
interface ZGNoData extends CatchAll, HTMLElement {}
interface ZGPager extends ZingGridAttributes.ZGPager, CatchAll, HTMLElement {}
interface ZGParam extends ZingGridAttributes.ZGParam, CatchAll, HTMLElement {}
interface ZGRow extends CatchAll, HTMLElement {}
interface ZGSearch extends CatchAll, HTMLElement {}
interface ZGSelectorMask extends CatchAll, HTMLElement {}
interface ZGSeparator extends CatchAll, HTMLElement {}
interface ZGSource extends ZingGridAttributes.ZGSource, CatchAll, HTMLElement {}
interface ZGStatus extends CatchAll, HTMLElement {}
interface ZGText extends ZingGridAttributes.ZGText, CatchAll, HTMLElement {}
interface ZGTooltip extends CatchAll, HTMLElement {}
class ZingGrid {
constructor(config: ZingGridConfig, ref: HTMLElement | Element);
constructor(ref: HTMLElement | Element, config: ZingGridConfig);
addEventListener<K extends keyof ZingGridElementEventMap>(type: K, listener: (this: ZingGrid, ev: ZingGridElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: ZingGrid, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof ZingGridElementEventMap>(type: K, listener: (this: ZingGrid, ev: ZingGridElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: ZingGrid, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
// ZGDialog
/**
* @description Customizes the user's dialog
* @param type The type of dialog to customize. If you set as null, the config will be applied to all dialogs.
* Options are:
* <ul>
* <li>record-create
* <li>record-delete
* <li>record-info
* <li>record-update
* <li>view-error
* <li>view-info
* <li>view-success
* <li>view-warn
* <li>zg-version
* </ul>
* @param config Options for the data retrieval. Options are:
* <ul>
* <li>cancel: Text for the Cancel Button
* <li>confirm: Text for the Confirm Button
* <li>title: The Title to display on the Dialog
* </ul>
*/
customizeDialog: (type: string, config: any) => ZingGrid;
// ZGColumn
/**
* @description Fetches the targeted column.
* @param fieldIndex Field index of column to fetch.
*/
column: (fieldIndex: any[]) => any;
/**
* @description Filters the column specified by column index. Note: "filter" attribute must be present for
* this method to work.
* @param columnIndex Index of column.
* @param filter Filter string.
*/
filterColumn: (columnIndex: string, filter: string) => ZingGrid;
/**
* @description Gets the value of the "col-class" attribute
*/
getColClass: () => string;
/**
* @description Gets the value of the "header-auto-format" attribute
*/
getHeaderAutoFormat: () => boolean;
/**
* @description Hides a column based on index
* @param columnIndex Index of column to hide
*/
hideColumn: (columnIndex: string) => ZingGrid;
/**
* @description Sets the "col-class" attribute
* @param type Class name or function name
*/
setColClass: (type: string) => ZingGrid;
/**
* @description Sets the "columns" property
* @param columns Array of column objects
*/
setColumns: (columns: any[]) => ZingGrid;
/**
* @description Sets the "columns-control" attribute
* @param activate Value to add or remove
*/
setColumnsControl: (activate: boolean) => ZingGrid;
/**
* @description Sets the "header-auto-format" attribute
* @param activate Value to add or remove
*/
setHeaderAutoFormat: (activate: boolean) => ZingGrid;
/**
* @description Sets column to be visible
* @param columnIndex Index of column to show
*/
showColumn: (columnIndex: string) => ZingGrid;
/**
* @description Sorts the given column with the given sort direction
* @param columnIndex Index of column to sort
* @param direction Sort Direction: asc, desc, or none
*/
sortColumn: (columnIndex: string, direction: string) => ZingGrid;
/**
* @description Toggles the visibility of a column by index
* @param columnIndex Index of column to toggle
* @param hide Visibility of column
*/
toggleColumn: (columnIndex: string, hide: boolean) => ZingGrid;
// ZGSelector
/**
* @description Returns an array of selected rows
*/
getSelectedRows: () => any[];
/**
* @description Gets the value of the "selector" attribute
*/
getSelector: () => boolean;
/**
* @description Selects one or more cells
* @param rowIndex Row of cell to select
* @param colIndex Column of cell to select
* @param endRowIndex Optional end cell row for multi-cell selection
* @param endColIndex Optional end cell column for multi-cell selection
*/
select: (rowIndex: string, colIndex: string, endRowIndex?: string, endColIndex?: string) => ZingGrid;
/**
* @description Sets the "selector" attribute
* @param activate Value to add or remove
*/
setSelector: (activate: boolean) => ZingGrid;
// ZGPager
/**
* @description Navigates to first page in the grid
*/
firstPage: () => ZingGrid;
/**
* @description Gets the current page. Does not apply to cursor paging.
*/
getPageIndex: () => number;
/**
* @description Gets the current "page-size"
*/
getPageSize: () => number;
/**
* @description Gets the value of the "page-size-card" attribute
*/
getPageSizeCard: () => string;
/**
* @description Gets the value of the "page-size-row" attribute
*/
getPageSizeRow: () => string;
/**
* @description Gets the value of the "pager" attribute
*/
getPager: () => boolean;
/**
* @description Navigates to the last page in the grid
*/
lastPage: () => ZingGrid;
/**
* @description Navigates to the next page in the grid
*/
nextPage: () => ZingGrid;
/**
* @description Navigates to the previous page in the grid
*/
prevPage: () => ZingGrid;
/**
* @description Changes the current page index to be the specified value
* @param pageIndex New page index
*/
setPageIndex: (pageIndex: number) => ZingGrid;
/**
* @description Changes the current page size to be the specified value
* @param pageSize New page size
*/
setPageSize: (pageSize: number) => ZingGrid;
/**
* @description Changes the current page size to be the specified value in card mode
* @param pageSize New card page size
*/
setPageSizeCard: (pageSize: number) => ZingGrid;
/**
* @description Sets the page size options for the pager drop down
* @param options Comma separated list of numerical page sizes
*/
setPageSizeOptions: (options: string) => ZingGrid;
/**
* @description Changes the current page size to be the specified value in row mode
* @param pageSize New row page size
*/
setPageSizeRow: (pageSize: number) => ZingGrid;
/**
* @description Sets the "pager" attribute
* @param activate Value to add or remove
*/
setPager: (activate: boolean) => ZingGrid;
// ZGCaption
/**
* @description Gets the value of the "caption" attribute
*/
getCaption: () => string;
/**
* @description Set the caption text
* @param sCaption Text to set the caption to. If no string is passed, it will remove the caption.
*/
setCaption: (sCaption: string) => ZingGrid;
// ZGData
/**
* @description Fetches the internal property referencing the dataset for the grid
* @param config Optional, options for the data retrieval. Options are:
* <ul>
* <li>csv: Boolean indicating if it should be sent as a csv string. Default is false.</li>
* <li>headers: Boolean indicating if headers should be included. Default is false.
* Only applies to csv or JSON array of arrays as JSON objects have a key already.</li>
* <li>cols: String indicating if we should return all columns or only visible. 'all' or 'visible' are options.
* <li>rows: String indicating if we should return all rows or only filtered/searched. 'all' or 'visible' are options.
* </ul>
*/
getData: (config?: any) => any;
/**
* @description Gets the value of the "src" attribute
*/
getSrc: () => string;
/**
* @description Gets the value of the "template-end-delimiter" attribute
*/
getTemplateEndDelimiter: () => string;
/**
* @description Gets the value of the "template-start-delimiter" attribute
*/
getTemplateStartDelimiter: () => string;
/**
* @description Inserts a new row into the grid
* @param data Data to insert into new row
* @param id If the id is already set on the new record, pass it in here
* @param noDataSource If you only want to do a local insert, set "noDataSource" to "true"
*/
insertRow: (data: any, id: string, noDataSource: boolean) => ZingGrid;
/**
* @description Refreshes all cells. Note: if using static data, original cell value will be restored.
*/
refresh: () => undefined;
/**
* @description Refreshes entire grid. Useful for language change.
*/
refreshGrid: () => undefined;
/**
* @description Removes a record from the grid
* @param id ID of the record to remove
* @param noDataSource If you only want to remove from the grid and not the external datasource, set "noDataSource" to "true"
*/
removeRecord: (id: string, noDataSource: boolean) => ZingGrid;
/**
* @description Removes a row from the grid
* @param rowIndex Row index (0 based) of the record to remove
* @param noDataSource If you only want to remove from the grid and not the external datasource, set "noDataSource" to "true"
*/
removeRow: (rowIndex: string, noDataSource: boolean) => ZingGrid;
/**
* @description Sets or updates the dataset for the grid
* @param data JSON data
*/
setData: (data: any) => ZingGrid;
/**
* @description Sets the "src" attribute
* @param src Value to indicate a path to a remote data source
*/
setSrc: (src: string) => ZingGrid;
/**
* @description Sets the "template-end-delimiter" attribute
* @param delim Value to indicate regex expression for closing data binding
*/
setTemplateEndDelimiter: (delim: string) => ZingGrid;
/**
* @description Sets the "template-start-delimiter" attribute
* @param delim Value to indicate regex expression for opening data binding
*/
setTemplateStartDelimiter: (delim: string) => ZingGrid;
/**
* @description Updates a cell in the grid
* @param id ID of the record to update
* @param fieldIndex Field index of the cell to update
* @param val New Value
* @param noDataSource If you only want to update the grid and not the external datasource, set "noDataSource" to "true"
*/
updateCellByID: (id: number, fieldIndex: number, val: any, noDataSource: boolean) => ZingGrid;
/**
* @description Updates a cell in the grid
* @param rowIndex Row index (0 based) of the cell to update
* @param columnIndex Column index (0 based) of the cell to update
* @param val New Value
* @param noDataSource If you only want to update the grid and not the external datasource, set "noDataSource" to "true"
*/
updateCellByPosition: (rowIndex: number, columnIndex: number, val: any, noDataSource: boolean) => ZingGrid;
/**
* @description Updates a record in the grid
* @param id ID of the record to update
* @param data Data to update
* @param noDataSource If you only want to update the grid and not the external datasource, set "noDataSource" to "true"
*/
updateRecord: (id: string, data: any, noDataSource: boolean) => ZingGrid;
/**
* @description Updates a row in the grid
* @param rowIndex Row index (0 based) of the record to update
* @param data Data to update
* @param noDataSource If you only want to update the grid and not the external datasource, set "noDataSource" to "true"
*/
updateRow: (rowIndex: string, data: any, noDataSource: boolean) => ZingGrid;
// ZGSearch
/**
* @description Gets the value of the "search" attribute
*/
getSearch: () => boolean;
/**
* @description Searches the grid with the search term indicated
* @param search Search term
*/
searchGrid: (search: string) => ZingGrid;
/**
* @description Sets the "search" attribute
* @param activate Value to add or remove
*/
setSearch: (activate: boolean) => ZingGrid;
// ZGCell
/**
* @description Fetches the targeted cell.
* @param rowContainerIndex The index of the row to fetch.
* @param columnContainerIndex The index of the column fetch.
*/
cell: (rowContainerIndex: number, columnContainerIndex: number) => any;
/**
* @description Get the value of the "cell-break" attribute.
*/
getCellBreak: () => string;
/**
* @description Gets the value of the "cell-class" attribute
*/
getCellClass: () => string;
/**
* @description Fetches all cells
*/
getCells: () => any[];
/**
* @description Gets the value of the "column-drag" attribute
*/
getColumnDrag: () => boolean;
/**
* @description Gets the value of the "default-display" attribute
*/
getDefaultDisplay: () => string | boolean;
/**
* @description Sets the "cell-break" attribute
* @param type Type of cell-break
*/
setCellBreak: (type: 'all' | 'ellipsis' | 'word') => ZingGrid;
/**
* @description Sets the "cell-class" attribute
* @param type Class name or function name
*/
setCellClass: (type: string) => ZingGrid;
/**
* @description Sets the "default-display" attribute
* @param value Value to use as default cell display if data is undefined or null
*/
setDefaultDisplay: (value: string) => ZingGrid;
// ZGRow
/**
* @description Gets the value of the "row-class" attribute
*/
getRowClass: () => string;
/**
* @description Gets the value of the "zebra" attribute
*/
getZebra: () => string;
/**
* @description Fetches the targeted row.
* @param rowContainerIndex The index of the row to fetch.
*/
row: (rowContainerIndex: number) => any;
/**
* @description Sets the "row-class" attribute
* @param type Class name or function name
*/
setRowClass: (type: string) => ZingGrid;
/**
* @description Sets the "zebra" attribute
* @param type Class name or function name
*/
setZebra: (type: string) => ZingGrid;
// ZGMenu
/**
* @description Closes currently opened contextmenu.
*/
closeContextMenu: () => ZingGrid;
/**
* @description Gets the value of the "columns-control" attribute
*/
getColumnsControl: () => boolean;
/**
* @description Gets the value of the "context-menu" attribute
*/
getContextMenu: () => string | boolean;
/**
* @description Gets the value of the "static-menu" attribute
*/
getStaticMenu: () => string;
/**
* @description Sets the "context-menu" attribute.
* @param types Boolean value to indicate add or remove, or string value to indicate reference to id of context-menu.
*/
setContextMenu: (types: boolean | string) => ZingGrid;
/**
* @description Sets the "static-menu" attribute
* @param activate Value to add or remove
*/
setStaticMenu: (activate: boolean) => ZingGrid;
// ZingGrid
/**
* @description Executes callback function when grid completes load. If grid is already loaded, it will execute immediately.
* @param callback Callback function to execute
*/
executeOnLoad: (callback: any) => undefined;
/**
* @description Formats a Date
* @param date The Date to format
* @param format The tokenized format to format the date
*/
formatDate: (date: string | Date, format: string) => string;
/**
* @description Formats a Date in from now format
* @param date The Date to format
* @param raw Indicates if we should include 'ago/to' to indicate past/future
*/
fromNow: (date: Date, raw: boolean) => string;
/**
* @description Gets the value of the "column-drag-action" attribute
*/
getColumnDragAction: () => string;
/**
* @description Gets the value of the "compact" attribute
*/
getCompact: () => string | boolean;
/**
* @description Gets the dir setting for the grid
*/
getDir: () => string;
/**
* @description Gets the value of the "gridlines" attribute
*/
getGridlines: () => string;
/**
* @description Gets the value of the "height" attribute
*/
getHeight: () => string;
/**
* @description Gets the language used on the grid
*/
getLang: () => string;
/**
* @description Gets the value of the "width" attribute
*/
getWidth: () => string;
/**
* @description Sets the "column-drag" attribute
* @param activate Boolean value to indicate add or remove
*/
setColumnDrag: (activate: boolean) => ZingGrid;
/**
* @description Sets the "column-drag-action" attribute
* @param type Type of drag to enable
*/
setColumnDragAction: (type: 'reorder' | 'remove' | 'both') => ZingGrid;
/**
* @description Sets the "compact" attribute
* @param activate Value to add or remove
*/
setCompact: (activate: boolean) => ZingGrid;
/**
* @description Sets the "dir" attribute
* @param type Type of dir
*/
setDir: (type: 'ltr' | 'rtl') => ZingGrid;
/**
* @description Sets the "gridlines" attribute
* @param type Type of gridlines to set on the grid
*/
setGridlines: (type: 'both' | 'horz' | 'horizontal' | 'vert' | 'vertical') => ZingGrid;
/**
* @description Sets the "height" attribute
* @param height Value setting the height of the grid
*/
setHeight: (height: number) => ZingGrid;
/**
* @description Sets the "lang" attribute
* @param lang Language to set on the grid
*/
setLang: (lang: string) => ZingGrid;
/**
* @description Sets the "record-count" attribute
* @param count Value setting the count
*/
setRecordCount: (count: number) => ZingGrid;
/**
* @description Sets the "width" attribute
* @param width Value setting the width of the grid
*/
setWidth: (width: number) => ZingGrid;
/**
* @description Forces a resize event to be triggered and to partially repaint the grid. Useful when the container updates size without the window updating.
*/
updateSize: () => ZingGrid;
// ZGEditor
/**
* @description Gets the value of the "editor" attribute
*/
getEditor: () => string;
/**
* @description Gets the value of the "editor-controls" attribute
*/
getEditorControls: () => string;
/**
* @description Gets the value of the "row-selector" attribute
*/
getRowSelector: () => boolean;
/**
* @description Sets the "editor" attribute
* @param activate Boolean value to indicate add or remove, or string value to indicate the editor type
*/
setEditor: (activate: boolean | string) => ZingGrid;
/**
* @description Sets the "editor-controls" attribute
* @param types Boolean value to indicate add or remove, or string value to indicate what editor controls to add
*/
setEditorControls: (types: boolean | string) => ZingGrid;
/**
* @description Sets the "row-selector" attribute
* @param activate Value to add or remove
*/
setRowSelector: (activate: boolean) => ZingGrid;
// ZGFilter
/**
* @description Gets the value of the "filter" attribute
*/
getFilter: () => boolean;
/**
* @description Sets the "filter" attribute
* @param activate Value to add or remove
*/
setFilter: (activate: boolean) => ZingGrid;
// ZGFoot
/**
* @description Gets the value of the "foot-class" attribute
*/
getFootClass: () => string;
/**
* @description Sets the "foot-class" attribute
* @param type class name or function name
*/
setFootClass: (type: string) => ZingGrid;
// ZGHead
/**
* @description Gets the value of the "head-class" attribute
*/
getHeadClass: () => string;
/**
* @description Sets the "head-class" attribute
* @param type Class name or function name
*/
setHeadClass: (type: string) => ZingGrid;
// ZGIcon
/**
* @description Gets the value of the "icon-set" attribute
*/
getIconSet: () => string;
/**
* @description Sets the "icon-set" attribute
* @param type Icon set to use in the grid
*/
setIconSet: (type: string) => ZingGrid;
// ZGLayout
/**
* @description Gets the value of the "layout" attribute
*/
getLayout: () => string;
/**
* @description Gets the value of the "layout-controls" attribute
*/
getLayoutControls: () => string;
/**
* @description Sets the "layout" attribute
* @param type Value to indicate the grid layout
*/
setLayout: (type: 'row' | 'card') => ZingGrid;
/**
* @description Sets the "layout-controls" attribute
* @param activate Value to add or remove
*/
setLayoutControls: (activate: boolean) => ZingGrid;
// ZGNoData
/**
* @description Gets the value of the "no-data" attribute
*/
getNodata: () => string;
/**
* @description Sets the "no-data" attribute
* @param value Message to display when there is no data
*/
setNoData: (value: string) => ZingGrid;
// ZGSorter
/**
* @description Gets the value of the "sort" attribute
*/
getSort: () => string;
/**
* @description Gets the value of the "sorter" attribute
*/
getSorter: () => string;
/**
* @description Sets the "sort" attribute
* @param types Boolean value to indicate add or remove
*/
setSort: (types: boolean) => ZingGrid;
/**
* @description Sets the "sorter" attribute
* @param types String value to indicate reference to custom sorter function
*/
setSorter: (types: boolean | string) => ZingGrid;
// ZGSource
/**
* @description Gets the value of the "source" attribute
*/
getSource: () => string;
/**
* @description Sets the "source" attribute. Not to be confused with "src" attribute, the "source" attribute is for citation.
* @param value Source of the data in the grid
*/
setSource: (value: string) => ZingGrid;
// ZGTheme
/**
* @description Gets the value of the "theme" attribute
*/
getTheme: () => string;
/**
* @description Sets the "theme" attribute
* @param theme Value to indicate which theme to set
*/
setTheme: (theme: string) => ZingGrid;
// ZGViewport
/**
* @description Gets the value of the "viewport" attribute
*/
getViewport: () => string;
/**
* @description Gets the value of the "viewport-pause" attribute
*/
getViewportPause: () => boolean;
/**
* @description Gets the value of the "viewport-stop" attribute
*/
getViewportStop: () => boolean;
/**
* @description Gets the value of the "viewport-types" attribute
*/
getViewportTypes: () => string;
/**
* @description Sets the "viewport-pause" attribute
* @param activate Value to add or remove
*/
setViewportPause: (activate: boolean) => ZingGrid;
/**
* @description Sets the "viewport-stop" attribute
* @param activate Value to add or remove
*/
setViewportStop: (activate: boolean) => ZingGrid;
// ZGCard
/**
* @description Sets the id to reference an external "template" to be used as "<zg-card>"
* @param id Value of id to use the card template.
*/
setCardTemplate: (id: string) => ZingGrid;
}
interface ZingGrid extends NonoptionalAttributes, Omit<ZingGridAttributes.ZingGrid, 'accessKey'
| 'accessKeyLabel' | 'animationcancel_event' | 'animationend_event' | 'animationiteration_event' | 'animationstart_event' | 'attachInternals' | 'autocapitalize'
| 'beforeinput_event' | 'blur' | 'click' | 'contentEditable' | 'contextMenu' | 'dataset' | 'dir'
| 'draggable' | 'enterKeyHint' | 'focus' | 'gotpointercapture_event' | 'hidden' | 'inert' | 'innerText'
| 'input_event' | 'inputMode' | 'isContentEditable' | 'itemId' | 'itemProp' | 'itemRef' | 'itemScope'
| 'itemType' | 'itemValue' | 'lang' | 'lostpointercapture_event' | 'nonce' | 'offsetHeight' | 'offsetLeft'
| 'offsetParent' | 'offsetTop' | 'offsetWidth' | 'oncopy' | 'oncut' | 'onpaste' | 'outerText'
| 'pointercancel_event' | 'pointerdown_event' | 'pointerenter_event' | 'pointerleave_event' | 'pointermove_event' | 'pointerout_event' | 'pointerover_event'
| 'pointerrawupdate_event' | 'pointerup_event' | 'spellcheck' | 'tabIndex' | 'title' | 'transitioncancel_event' | 'transitionend_event'
| 'transitionrun_event' | 'transitionstart_event' | 'translate' | 'attributeStyleMap' | 'style'>, CatchAll, HTMLElement {}
}
interface HTMLElementTagNameMap {
'zg-body': ZSoft.ZGBody;
'zg-button': ZSoft.ZGButton;
'zg-caption': ZSoft.ZGCaption;
'zg-card': ZSoft.ZGCard;
'zg-cell': ZSoft.ZGCell;
'zg-checkbox': ZSoft.ZGCheckbox;
'zg-colgroup': ZSoft.ZGColgroup;
'zg-column': ZSoft.ZGColumn;
'zg-control-bar': ZSoft.ZGControlBar;
'zg-data': ZSoft.ZGData;
'zg-dialog': ZSoft.ZGDialog;
'zg-editor-row': ZSoft.ZGEditorRow;
'zg-focus': ZSoft.ZGFocus;
'zg-foot': ZSoft.ZGFoot;
'zg-footer': ZSoft.ZGFooter;
'zg-frozen-colgroup': ZSoft.ZGFrozenColgroup;
'zg-head': ZSoft.ZGHead;
'zg-head-cell': ZSoft.ZGHeadCell;
'zg-header': ZSoft.ZGHeader;
'zg-icon': ZSoft.ZGIcon;
'zg-input': ZSoft.ZGInput;
'zg-layout-controls': ZSoft.ZGLayoutControls;
'zg-load-mask': ZSoft.ZGLoadMask;
'zg-menu': ZSoft.ZGMenu;
'zg-menu-group': ZSoft.ZGMenuGroup;
'zg-menu-item': ZSoft.ZGMenuItem;
'zg-no-data': ZSoft.ZGNoData;
'zg-pager': ZSoft.ZGPager;
'zg-param': ZSoft.ZGParam;
'zg-row': ZSoft.ZGRow;
'zg-search': ZSoft.ZGSearch;
'zg-selector-mask': ZSoft.ZGSelectorMask;
'zg-separator': ZSoft.ZGSeparator;
'zg-source': ZSoft.ZGSource;
'zg-status': ZSoft.ZGStatus;
'zg-text': ZSoft.ZGText;
'zg-tooltip': ZSoft.ZGTooltip;
'zing-grid': ZSoft.ZingGrid;
}
declare namespace JSX {
interface IntrinsicElements {
'zg-body': ZSoft.CatchAll;
ZGBody: ZSoft.CatchAll;
'zg-button': KebabKeys<ZSoft.ZingGridAttributes.ZGButton> | ZSoft.CatchAll;
ZGButton: ZSoft.ZingGridAttributes.ZGButton | ZSoft.CatchAll;
'zg-caption': KebabKeys<ZSoft.ZingGridAttributes.ZGCaption> | ZSoft.CatchAll;
ZGCaption: ZSoft.ZingGridAttributes.ZGCaption | ZSoft.CatchAll;
'zg-card': KebabKeys<ZSoft.ZingGridAttributes.ZGCard> | ZSoft.CatchAll;
ZGCard: ZSoft.ZingGridAttributes.ZGCard | ZSoft.CatchAll;
'zg-cell': ZSoft.CatchAll;
ZGCell: ZSoft.CatchAll;
'zg-checkbox': KebabKeys<ZSoft.ZingGridAttributes.ZGCheckbox> | ZSoft.CatchAll;
ZGCheckbox: ZSoft.ZingGridAttributes.ZGCheckbox | ZSoft.CatchAll;
'zg-colgroup': ZSoft.CatchAll;
ZGColgroup: ZSoft.CatchAll;
'zg-column': KebabKeys<ZSoft.ZingGridAttributes.ZGColumn> | ZSoft.CatchAll;
ZGColumn: ZSoft.ZingGridAttributes.ZGColumn | ZSoft.CatchAll;
'zg-control-bar': ZSoft.CatchAll;
ZGControlBar: ZSoft.CatchAll;
'zg-data': KebabKeys<ZSoft.ZingGridAttributes.ZGData> | ZSoft.CatchAll;
ZGData: ZSoft.ZingGridAttributes.ZGData | ZSoft.CatchAll;
'zg-dialog': KebabKeys<ZSoft.ZingGridAttributes.ZGDialog> | ZSoft.CatchAll;
ZGDialog: ZSoft.ZingGridAttributes.ZGDialog | ZSoft.CatchAll;
'zg-editor-row': ZSoft.CatchAll;
ZGEditorRow: ZSoft.CatchAll;
'zg-focus': ZSoft.CatchAll;
ZGFocus: ZSoft.CatchAll;
'zg-foot': ZSoft.CatchAll;
ZGFoot: ZSoft.CatchAll;
'zg-footer': ZSoft.CatchAll;
ZGFooter: ZSoft.CatchAll;
'zg-frozen-colgroup': ZSoft.CatchAll;
ZGFrozenColgroup: ZSoft.CatchAll;
'zg-head': ZSoft.CatchAll;
ZGHead: ZSoft.CatchAll;
'zg-head-cell': ZSoft.CatchAll;
ZGHeadCell: ZSoft.CatchAll;
'zg-header': ZSoft.CatchAll;
ZGHeader: ZSoft.CatchAll;
'zg-icon': KebabKeys<ZSoft.ZingGridAttributes.ZGIcon> | ZSoft.CatchAll;
ZGIcon: ZSoft.ZingGridAttributes.ZGIcon | ZSoft.CatchAll;
'zg-input': KebabKeys<ZSoft.ZingGridAttributes.ZGInput> | ZSoft.CatchAll;
ZGInput: ZSoft.ZingGridAttributes.ZGInput | ZSoft.CatchAll;
'zg-layout-controls': ZSoft.CatchAll;
ZGLayoutControls: ZSoft.CatchAll;
'zg-load-mask': ZSoft.CatchAll;
ZGLoadMask: ZSoft.CatchAll;
'zg-menu': KebabKeys<ZSoft.ZingGridAttributes.ZGMenu> | ZSoft.CatchAll;
ZGMenu: ZSoft.ZingGridAttributes.ZGMenu | ZSoft.CatchAll;
'zg-menu-group': ZSoft.CatchAll;
ZGMenuGroup: ZSoft.CatchAll;
'zg-menu-item': ZSoft.CatchAll;
ZGMenuItem: ZSoft.CatchAll;
'zg-no-data': ZSoft.CatchAll;
ZGNoData: ZSoft.CatchAll;
'zg-pager': KebabKeys<ZSoft.ZingGridAttributes.ZGPager> | ZSoft.CatchAll;
ZGPager: ZSoft.ZingGridAttributes.ZGPager | ZSoft.CatchAll;
'zg-param': KebabKeys<ZSoft.ZingGridAttributes.ZGParam> | ZSoft.CatchAll;
ZGParam: ZSoft.ZingGridAttributes.ZGParam | ZSoft.CatchAll;
'zg-row': ZSoft.CatchAll;
ZGRow: ZSoft.CatchAll;
'zg-search': ZSoft.CatchAll;
ZGSearch: ZSoft.CatchAll;
'zg-selector-mask': ZSoft.CatchAll;
ZGSelectorMask: ZSoft.CatchAll;
'zg-separator': ZSoft.CatchAll;
ZGSeparator: ZSoft.CatchAll;
'zg-source': KebabKeys<ZSoft.ZingGridAttributes.ZGSource> | ZSoft.CatchAll;
ZGSource: ZSoft.ZingGridAttributes.ZGSource | ZSoft.CatchAll;
'zg-status': ZSoft.CatchAll;
ZGStatus: ZSoft.CatchAll;
'zg-text': KebabKeys<ZSoft.ZingGridAttributes.ZGText> | ZSoft.CatchAll;
ZGText: ZSoft.ZingGridAttributes.ZGText | ZSoft.CatchAll;
'zg-tooltip': ZSoft.CatchAll;
ZGTooltip: ZSoft.CatchAll;
'zing-grid': KebabKeys<ZSoft.ZingGridAttributes.ZingGrid> | ZSoft.ZingGridEventHandlers |ZSoft.CatchAll;
ZingGrid: ZSoft.ZingGridAttributes.ZingGrid | ZSoft.ZingGridEventHandlers |ZSoft.CatchAll;
}
}
declare namespace ZingGrid {
/**
* @description Customizes the user's dialog for all instances of ZingGrid
* @param type The type of dialog to customize. If you set as null, the config will be applied to all dialogs.
* Options are:
* <ul>
* <li>record-create
* <li>record-delete
* <li>record-info
* <li>record-update
* <li>view-error
* <li>view-info
* <li>view-success
* <li>view-warn
* <li>zg-version
* </ul>
* @param config Options for the data retrieval. Options are:
* <ul>
* <li>cancel: Text for the Cancel Button
* <li>confirm: Text for the Confirm Button
* <li>label: Label to display on the Dialog
* </ul>
*/
function customizeDialog(type: string, config: any): ZingGrid;
/**
* @description Formats a Date
* @param date The Date to format
* @param format The tokenized format to format the date
* @param locale The locale to use for the formatting. Optional.
*/
function formatDate(date: string | Date, format: string, locale?: string): string;
/**
* @description Formats a Date in from now format
* @param date The Date to format
* @param raw Indicates if we should include 'ago/to' to indicate past/future
*/
function fromNow(date: Date, raw: boolean): string;
/**
* @description Register a method to make connecting a remote data src to your grid even easier. If you
* have your own standardized endpoints this is very useful. A way for us to provide an ES6 style import
* mechanism and pattern for building custom data sources.
* @param sType The string name for the adapter
* @param oOptions Option list of of adapter variables you want to define. You can define ANY
* zg-param name value pair here in this option. Refer to the Store.js variable this.oDefaultDataFormat
*/
function registerAdapter(sType: string, oOptions: any): void;
/**
* @description Register a custom column type to reduce redundant markup and re-use
* similar code.
* @param sType Name of cell type.
* @param oOptions An object to define the renderer and/or editor for the cell type.
*/
function registerCellType(sType: string, oOptions: any): void;
/**
* @description Register the life cycle hooks for cell editing. This allows you to import
* and inherit editors for your library.
* @param sCellType Cell type editor to override
* @param oConfig Object containing editor hooks
*/
function registerEditor(sCellType: string, oConfig: any): void;
/**
* @description Register a method to make it available to ZingGrid even if it outside the window scope.
* This can be used to make a method accessible to renderer, editor, sorter, and custom styles
* This is useful for methods within a class or local methods.
* @param method The method that you wish to expose to ZingGrid.
* @param name The name to refer to the method. If the method is not anonymous, the name will default to the
* name of the method. If it is anonymous, a name must be set. Whatever is set here is how you should refer to the method
* in the grid. Optional.
* @param scope The scope of the method. When the method is called "this" will be set to the "scope" value. Optional.
*/
function registerMethod(method: any, name?: string, scope?: any): void;
/**
* @description Register a namespace to make it available to ZingGrid even if it outside the window scope.
* Once a namespace is registered, the methods within the namespace will be accessible to ZingGrid without having to call "ZingGrid.registerMethod"
* @param namespace The namespace that you wish to expose to ZingGrid.
* @param name The name to refer to the namespace. Optional.
* @param scope The scope of the namespace. When a method within the namespace is called, "this" will be set to the "scope" value.
* Defaults to the namespace itself. Optional.
*/
function registerNamespace(namespace: any, name?: string, scope?: any): void;
/**
* @description Register the life cycle hooks for cell validation. This allows you to import
* and inherit validators for your library.
* @param oValidator The validator that you wish to expose to ZingGrid.
* @param name The name to refer to the validator. Optional.
* @param scope The scope of the method. When the method is called "this" will be set to the "scope" value. Optional.
*/
function registerValidator(oValidator: any, name?: string, scope?: any): void;
}
declare class ZingGrid extends ZSoft.ZingGrid {}
declare module 'zingsoft' {
export = ZingGrid;
}
declare module 'zinggrid-react-wrapper' {
export = ZingGrid;
} | the_stack |
* {{cookiecutter.project_name}}
* {{cookiecutter.project_name}} API
*
* The version of the OpenAPI document: 0.1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import { Configuration } from '../configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../base';
// @ts-ignore
import { ErrorModel } from '../models';
// @ts-ignore
import { HTTPValidationError } from '../models';
// @ts-ignore
import { User } from '../models';
// @ts-ignore
import { UserUpdate } from '../models';
/**
* UsersApi - axios parameter creator
* @export
*/
export const UsersApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Get Users
* @param {number} [skip]
* @param {number} [limit]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUsers: async (skip?: number, limit?: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/users`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
if (skip !== undefined) {
localVarQueryParameter['skip'] = skip;
}
if (limit !== undefined) {
localVarQueryParameter['limit'] = limit;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Users:Current User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersCurrentUser: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/users/me`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Users:Delete User
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersDeleteUser: async (id: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'id' is not null or undefined
assertParamExists('usersDeleteUser', 'id', id)
const localVarPath = `/api/v1/users/{id}`
.replace(`{${"id"}}`, encodeURIComponent(String(id)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Users:Patch Current User
* @param {UserUpdate} userUpdate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersPatchCurrentUser: async (userUpdate: UserUpdate, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'userUpdate' is not null or undefined
assertParamExists('usersPatchCurrentUser', 'userUpdate', userUpdate)
const localVarPath = `/api/v1/users/me`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(userUpdate, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Users:Patch User
* @param {string} id
* @param {UserUpdate} userUpdate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersPatchUser: async (id: string, userUpdate: UserUpdate, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'id' is not null or undefined
assertParamExists('usersPatchUser', 'id', id)
// verify required parameter 'userUpdate' is not null or undefined
assertParamExists('usersPatchUser', 'userUpdate', userUpdate)
const localVarPath = `/api/v1/users/{id}`
.replace(`{${"id"}}`, encodeURIComponent(String(id)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(userUpdate, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Users:User
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersUser: async (id: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'id' is not null or undefined
assertParamExists('usersUser', 'id', id)
const localVarPath = `/api/v1/users/{id}`
.replace(`{${"id"}}`, encodeURIComponent(String(id)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* UsersApi - functional programming interface
* @export
*/
export const UsersApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = UsersApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Get Users
* @param {number} [skip]
* @param {number} [limit]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getUsers(skip?: number, limit?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<User>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getUsers(skip, limit, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Users:Current User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async usersCurrentUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.usersCurrentUser(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Users:Delete User
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async usersDeleteUser(id: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.usersDeleteUser(id, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Users:Patch Current User
* @param {UserUpdate} userUpdate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async usersPatchCurrentUser(userUpdate: UserUpdate, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.usersPatchCurrentUser(userUpdate, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Users:Patch User
* @param {string} id
* @param {UserUpdate} userUpdate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async usersPatchUser(id: string, userUpdate: UserUpdate, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.usersPatchUser(id, userUpdate, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Users:User
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async usersUser(id: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.usersUser(id, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* UsersApi - factory interface
* @export
*/
export const UsersApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = UsersApiFp(configuration)
return {
/**
*
* @summary Get Users
* @param {number} [skip]
* @param {number} [limit]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUsers(skip?: number, limit?: number, options?: any): AxiosPromise<Array<User>> {
return localVarFp.getUsers(skip, limit, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Users:Current User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersCurrentUser(options?: any): AxiosPromise<User> {
return localVarFp.usersCurrentUser(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Users:Delete User
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersDeleteUser(id: string, options?: any): AxiosPromise<void> {
return localVarFp.usersDeleteUser(id, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Users:Patch Current User
* @param {UserUpdate} userUpdate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersPatchCurrentUser(userUpdate: UserUpdate, options?: any): AxiosPromise<User> {
return localVarFp.usersPatchCurrentUser(userUpdate, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Users:Patch User
* @param {string} id
* @param {UserUpdate} userUpdate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersPatchUser(id: string, userUpdate: UserUpdate, options?: any): AxiosPromise<User> {
return localVarFp.usersPatchUser(id, userUpdate, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Users:User
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
usersUser(id: string, options?: any): AxiosPromise<User> {
return localVarFp.usersUser(id, options).then((request) => request(axios, basePath));
},
};
};
/**
* Request parameters for getUsers operation in UsersApi.
* @export
* @interface UsersApiGetUsersRequest
*/
export interface UsersApiGetUsersRequest {
/**
*
* @type {number}
* @memberof UsersApiGetUsers
*/
readonly skip?: number
/**
*
* @type {number}
* @memberof UsersApiGetUsers
*/
readonly limit?: number
}
/**
* Request parameters for usersDeleteUser operation in UsersApi.
* @export
* @interface UsersApiUsersDeleteUserRequest
*/
export interface UsersApiUsersDeleteUserRequest {
/**
*
* @type {string}
* @memberof UsersApiUsersDeleteUser
*/
readonly id: string
}
/**
* Request parameters for usersPatchCurrentUser operation in UsersApi.
* @export
* @interface UsersApiUsersPatchCurrentUserRequest
*/
export interface UsersApiUsersPatchCurrentUserRequest {
/**
*
* @type {UserUpdate}
* @memberof UsersApiUsersPatchCurrentUser
*/
readonly userUpdate: UserUpdate
}
/**
* Request parameters for usersPatchUser operation in UsersApi.
* @export
* @interface UsersApiUsersPatchUserRequest
*/
export interface UsersApiUsersPatchUserRequest {
/**
*
* @type {string}
* @memberof UsersApiUsersPatchUser
*/
readonly id: string
/**
*
* @type {UserUpdate}
* @memberof UsersApiUsersPatchUser
*/
readonly userUpdate: UserUpdate
}
/**
* Request parameters for usersUser operation in UsersApi.
* @export
* @interface UsersApiUsersUserRequest
*/
export interface UsersApiUsersUserRequest {
/**
*
* @type {string}
* @memberof UsersApiUsersUser
*/
readonly id: string
}
/**
* UsersApi - object-oriented interface
* @export
* @class UsersApi
* @extends {BaseAPI}
*/
export class UsersApi extends BaseAPI {
/**
*
* @summary Get Users
* @param {UsersApiGetUsersRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public getUsers(requestParameters: UsersApiGetUsersRequest = {}, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).getUsers(requestParameters.skip, requestParameters.limit, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Users:Current User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public usersCurrentUser(options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).usersCurrentUser(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Users:Delete User
* @param {UsersApiUsersDeleteUserRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public usersDeleteUser(requestParameters: UsersApiUsersDeleteUserRequest, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).usersDeleteUser(requestParameters.id, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Users:Patch Current User
* @param {UsersApiUsersPatchCurrentUserRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public usersPatchCurrentUser(requestParameters: UsersApiUsersPatchCurrentUserRequest, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).usersPatchCurrentUser(requestParameters.userUpdate, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Users:Patch User
* @param {UsersApiUsersPatchUserRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public usersPatchUser(requestParameters: UsersApiUsersPatchUserRequest, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).usersPatchUser(requestParameters.id, requestParameters.userUpdate, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Users:User
* @param {UsersApiUsersUserRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public usersUser(requestParameters: UsersApiUsersUserRequest, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).usersUser(requestParameters.id, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import { jest } from '@jest/globals'
import { createRequire } from 'node:module'
import { basename, dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { TContext, TFlow } from '../../main/ts/ifaces'
jest.mock('child_process')
jest.mock('fs-extra')
jest.mock('synp')
const cp = createRequire(import.meta.url)('child_process')
const findCacheDir = (await import('find-cache-dir')).default
const fs = (await import('fs-extra')).default
const synp = (await import('synp')).default
const lf = (await import('../../main/ts/lockfile'))._internal
const { createSymlinks, getContext, run, runSync } = await import('../../main/ts')
const { getNpm, getYarn } = await import('../../main/ts/util')
const __dirname = dirname(fileURLToPath(import.meta.url))
const noop = () => {
/* noop */
}
const fixtures = resolve(__dirname, '../fixtures')
const registryUrl = 'https://example.com'
const strMatching = (start = '', end = '') =>
expect.stringMatching(new RegExp(`^${start}.+${end}$`))
const readFixture = (name: string): string =>
(jest.requireActual('fs') as typeof fs).readFileSync(
resolve(fixtures, name),
{
encoding: 'utf-8',
},
)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter
const revive = <T = any>(data: string): T =>
JSON.parse(data, (k, v) => {
if (
v !== null &&
typeof v === 'object' &&
'type' in v &&
v.type === 'Buffer' &&
'data' in v &&
Array.isArray(v.data)
) {
return Buffer.from(v.data)
}
return v
})
const audit = revive(readFixture('lockfile/yarn-audit-report.json'))
const yarnLockBefore = readFixture('lockfile/yarn.lock.before')
const yarnLockAfter = readFixture('lockfile/yarn.lock.after')
const temp = findCacheDir({ name: 'yarn-audit-fix', create: true }) + ''
const cwd = process.cwd()
const stdio = ['inherit', 'inherit', 'inherit']
const stdionull = [null, null, null] // eslint-disable-line
const lfAudit = jest.spyOn(lf, '_audit')
const lfRead = jest.spyOn(lf, '_read')
const lfPatch = jest.spyOn(lf, '_patch')
const lfWrite = jest.spyOn(lf, '_write')
// https://ar.al/2021/02/22/cache-busting-in-node.js-dynamic-esm-imports/
const reimport = async (modulePath: string) => {
const cacheBustingModulePath = `${modulePath}?update=${Date.now()}`
return (await import(cacheBustingModulePath)).default
}
describe('yarn-audit-fix', () => {
beforeAll(() => {
// @ts-ignore
fs.emptyDirSync.mockImplementation(noop)
// @ts-ignore
fs.copyFileSync.mockImplementation(noop)
// @ts-ignore
fs.readFileSync.mockImplementation((name) => {
const _name = basename(name)
if (_name === 'yarn.lock') {
return yarnLockBefore
}
if (_name === 'package.json') {
return '{"version": "1.0.0"}'
}
return ''
})
// @ts-ignore
fs.removeSync.mockImplementation(noop)
// @ts-ignore
fs.existsSync.mockImplementation(() => true)
// @ts-ignore
fs.createSymlinkSync.mockImplementation(noop)
// @ts-ignore
synp.yarnToNpm.mockImplementation(() => '{}')
// @ts-ignore
synp.npmToYarn.mockImplementation(() => '{}')
// @ts-ignore
cp.spawnSync.mockImplementation((cmd, [$0, $1]) => {
if ($0 === 'audit' && $1 === '--json') {
return audit
}
return { status: 0, stdout: '1.0.1' }
})
})
afterEach(jest.clearAllMocks)
afterAll(jest.resetAllMocks)
describe('createSymlinks', () => {
it('establishes proper links', () => {
const temp = 'foo/bar'
const cwd = join(fixtures, 'regular-monorepo')
const manifest = {
workspaces: ['packages/*'],
}
createSymlinks({ temp, flags: {}, cwd, manifest } as unknown as TContext)
const links = ['node_modules', 'packages/a', 'packages/b']
links.forEach((link) => {
expect(fs.createSymlinkSync).toHaveBeenCalledWith(
join(cwd, link),
strMatching(temp, link),
'dir',
)
})
})
})
describe('runner', () => {
// eslint-disable-next-line
const checkTempAssets = () => {
// Preparing...
expect(fs.emptyDirSync).toHaveBeenCalledWith(expect.stringMatching(temp))
expect(fs.copyFileSync).toHaveBeenCalledWith(
'yarn.lock',
strMatching(temp, 'yarn.lock'),
)
expect(fs.copyFileSync).toHaveBeenCalledWith(
'package.json',
strMatching(temp, 'package.json'),
)
expect(fs.copyFileSync).toHaveBeenCalledWith(
'.yarnrc',
strMatching(temp, '.yarnrc'),
)
expect(fs.copyFileSync).toHaveBeenCalledWith(
'.npmrc',
strMatching(temp, '.npmrc'),
)
expect(fs.createSymlinkSync).toHaveBeenCalledWith(
join(cwd, 'node_modules'),
strMatching(temp, 'node_modules'),
'dir',
)
}
// eslint-disable-next-line
const checkConvertFlow = (skipPkgLockOnly?: boolean) => {
checkTempAssets()
// Generating package-lock.json from yarn.lock...
expect(synp.yarnToNpm).toHaveBeenCalledWith(strMatching(temp), true)
expect(fs.removeSync).toHaveBeenCalledWith(strMatching(temp, 'yarn.lock'))
// Applying npm audit fix...
expect(cp.spawnSync).toHaveBeenCalledWith(
getNpm(),
[
'audit',
'fix',
skipPkgLockOnly ? undefined : '--package-lock-only',
'--verbose',
'--registry',
registryUrl,
'--prefix',
expect.stringMatching(temp),
].filter((v) => v !== undefined),
{ cwd: expect.stringMatching(temp), stdio },
)
// Updating yarn.lock from package-lock.json...
expect(fs.copyFileSync).toHaveBeenCalledWith(
strMatching(temp, 'yarn.lock'),
'yarn.lock',
)
expect(cp.spawnSync).toHaveBeenCalledWith(
getYarn(),
[
'install',
'--update-checksums',
'--verbose',
'--registry',
registryUrl,
'--ignore-engines',
],
{ cwd, stdio },
)
expect(fs.emptyDirSync).toHaveBeenCalledWith(expect.stringMatching(temp))
}
it('executes custom flows', async () => {
const handler = jest.fn(noop)
const flow: TFlow = {
main: [['Test', handler]],
fallback: [],
}
await run({}, flow)
expect(handler).toHaveBeenCalledTimes(1)
})
it('throws error on unsupported flow', async () =>
expect(run({ flow: 'unknown' })).rejects.toEqual(
new Error('Unsupported flow: unknown'),
))
describe('`patch` flow', () => {
it('invokes cmd queue with proper args', async () => {
await run({
flow: 'patch',
})
checkTempAssets()
// Patching `yarn.lock`
expect(lfRead).toHaveBeenCalledWith(strMatching(temp, 'yarn.lock'))
expect(lfAudit).toHaveBeenCalledTimes(1)
expect(cp.spawnSync).toHaveBeenCalledWith(
getYarn(),
['audit', '--json'],
{ cwd: strMatching(temp), stdio: stdionull },
)
expect(lfPatch).toHaveBeenCalledTimes(1)
expect(lfWrite).toHaveBeenCalledTimes(1)
expect(fs.writeFileSync).toHaveBeenCalledWith(
strMatching(temp, 'yarn.lock'),
yarnLockAfter,
)
// Replaces original file, triggers `yarn --update-checksums`, resets temp directory
expect(fs.copyFileSync).toHaveBeenCalledWith(
strMatching(temp, 'yarn.lock'),
'yarn.lock',
)
expect(cp.spawnSync).toHaveBeenCalledWith(
getYarn(),
['install', '--update-checksums'],
{ cwd, stdio },
)
})
})
describe('`convert` flow', () => {
it('invokes cmd queue with proper args', async () => {
await run({
verbose: true,
foo: 'bar',
'package-lock-only': true,
registry: registryUrl,
flow: 'convert',
ignoreEngines: true,
})
checkConvertFlow()
})
it('handles exceptions', async () => {
let reason = { error: new Error('foobar') } as any
// @ts-ignore
cp.spawnSync.mockImplementation(() => reason)
await expect(run({ silent: true })).rejects.toBe(reason)
reason = { status: 1 }
// @ts-ignore
cp.spawnSync.mockImplementation(() => reason)
await expect(run({ silent: true })).rejects.toBe(reason)
reason = new TypeError('foo')
// @ts-ignore
cp.spawnSync.mockImplementation(() => {
throw reason
})
await expect(run()).rejects.toBe(reason)
})
})
describe('cli', () => {
it('invokes cmd queue with proper args', async () => {
process.argv.push(
'--verbose',
'--package-lock-only=false',
`--registry=${registryUrl}`,
'--flow=convert',
'--ignore-engines',
)
await reimport('../../main/ts/cli')
.then(() => checkConvertFlow(true))
.catch(noop)
})
describe('on error', () => {
// eslint-disable-next-line
const checkExit = async (reason: any): Promise<any> => {
let _resolve: any
const promise = new Promise((resolve) => {
_resolve = resolve
})
jest.isolateModules(() => {
// @ts-ignore
cp.spawnSync.mockImplementationOnce(() => reason)
reimport('../../main/ts/cli').catch(_resolve)
})
return promise
}
it('sets code to 1 otherwise', async () => {
await checkExit({ error: new Error('foobar') })
expect(process.exitCode).toBe(1)
})
it('returns exit code if passed', async () => {
await checkExit({ status: 2 })
expect(process.exitCode).toBe(2)
})
})
})
})
describe('#getContext', () => {
it('parses flags, returns ctx entry', () => {
const cwd = '/foo/bar'
const bar = 'baz'
const ctx = getContext({
cwd,
bar
})
expect(ctx).toEqual(expect.objectContaining({
cwd,
flags: { cwd, bar },
manifest: { version: '1.0.0' }
}))
})
})
describe('aliases', () => {
it('runSync eq run.sync', () => {
expect(run.sync).toBe(runSync)
})
})
}) | the_stack |
import FormDesign from './@types/form-design';
import { Enum } from '@/config/enum';
import { icons } from '@/iconEditor';
import { icons_antd } from '@/iconEditor_antd';
import common, { post } from './tools/common';
import serviceConfig from '@/config/service.ts';
const _service = serviceConfig;
const propertyEditors: Array<FormDesign.PropertyEditor> = [
{
name: 'any',
description: '任意',
control: [
{
control: 'a-input',
slot: {},
attrs: {
style: { width: '100%' },
allowClear: true,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.any,
format: val => eval(val)
}, {
name: 'pixel',
description: '像素',
control: [
{
control: 'a-input',
slot: {},
attrs: {
style: { width: '100%' },
maxlength: 4,
min: 10,
allowClear: true,
addonAfter: '像素',
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.pixel,
format: val => val + 'px'
}, {
name: 'color',
description: '颜色',
control: [
{
control: 'color-picker',
slot: {},
attrs: {
style: { width: '100%' },
allowClear: true,
addonAfter: '颜色',
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.color
}, {
name: 'byte',
description: '字节',
control: [
{
control: 'a-input-number',
slot: {},
attrs: {
style: { width: '100%' },
formatter: value => `${value}byte`,
parser: value => value.replace('byte', ''),
allowClear: true,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.byte
}, {
name: 'singer-line',
description: '单行文本',
control: [
{
control: 'a-input',
slot: {},
attrs: {
style: { width: '100%' },
allowClear: false,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'multi-line',
description: '多行文本',
control: [
{
control: 'a-textarea',
slot: {},
attrs: {
style: { width: '100%' },
allowClear: true,
size: 'small',
autosize: { minRows: 2, maxRows: 6 }
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.multiLine
}, {
name: 'boolean',
description: '真假',
control: [
{
control: 'a-switch',
slot: {},
attrs: {
checkedChildren: '是',
unCheckedChildren: '否'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'int',
description: '整数',
control: [
{
control: 'a-input-number',
slot: {},
attrs: {
precision: 0,
min: 0,
style: { width: '100%' },
allowClear: true,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.int
}, {
name: 'float',
description: '小数',
control: [
{
control: 'a-input-number',
slot: {},
attrs: {
step: 0.1,
min: 0,
style: { width: '100%' },
allowClear: true,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.float
}, {
name: 'list',
description: '列表',
control: [
{
control: 'a-select',
slot: {},
attrs: {
allowClear: false,
buttonStyle: 'solid',
style: { width: '100%' },
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.list
}, {
name: 'view-data',
description: '视图',
control: [
{
control: 'a-select',
slot: {
},
attrs: {
enterButton: '查询',
style: { width: '100%' },
placeholder: '选择视图数据',
// defaultActiveFirstOption: false,
// showArrow: false,
// filterOption: false,
maxTagCount: 50,
showSearch: true,
allowClear: true,
size: 'small',
get options() { return _service.viewData }
},
events: {
// search(value) {
// common.get(value, data => (this.data = data));
// }
},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.viewData
}, {
name: 'basic-data',
description: '基础数据',
control: [
{
control: 'a-select',
slot: {},
attrs: {
enterButton: '查询',
style: { width: '100%' },
placeholder: '选择基础数据',
allowClear: true,
showSearch: true,
maxTagCount: 50,
size: 'small',
filterTreeNode: true,
treeDefaultExpandAll: true,
get options() { return _service.baseData }
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.basicData
}, {
name: 'icon',
description: '图标',
control: [
{
control: 'a-select',
event: {},
attrs: {
showSearch: true,
style: {
width: '100%',
fontFamily: 'vant-icon',
color: 'rgba(0, 0, 0, 0.65)',
fontSize: '20px',
lineHeight: '12px',
// fontWeight: '700',
verticalAlign: 'middle'
},
dropdownClassName: 'icon-editor-select',
placeholder: '',
allowClear: true,
size: 'small'
},
slot: {
//@ts-ignore
default: icons.map(i => ({
control: 'a-select-option',
html: i.label,
slot: {
default: icons
},
attrs: {
value: i.value
}
}))
}
}
],
editor: Enum.FormControlPropertyEditor.icon
}, {
name: 'icon_antd',
description: '图标',
control: [
{
control: 'a-select',
event: {},
attrs: {
showSearch: true,
style: {
width: '100%',
fontFamily: 'vant-icon',
color: 'rgba(0, 0, 0, 0.65)',
fontSize: '20px',
lineHeight: '12px',
// fontWeight: '700',
verticalAlign: 'middle'
},
dropdownClassName: 'icon-editor-select',
placeholder: '',
allowClear: true,
size: 'small'
},
slot: {
//@ts-ignore
default: icons_antd.map(i => ({
control: 'a-select-option',
html: i.label,
slot: {
default: icons_antd
},
attrs: {
value: i.value
}
}))
}
}
],
editor: Enum.FormControlPropertyEditor.icon
}, {
name: 'json',
description: 'JSON',
control: [
{
control: 'object-editor',
slot: {},
attrs: {
isFormExpression: true,
language: 'javascript',
options: {
lineNumbers: "off",
scrollBeyondLastLine: false,
},
style: { width: '100%', height: '300px' }
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.json
}, {
name: 'javascript',
description: 'Javascript',
control: [
{
control: 'code-editor',
slot: {},
attrs: {
isFormExpression: true,
language: 'javascript',
options: {
lineNumbers: "off",
scrollBeyondLastLine: false,
},
style: { width: '100%', height: '300px' }
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.javascript
}, {
name: 'model-list',
description: '对象列表',
control: [
{
control: 'model-list-editor',
slot: {},
attrs: {
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.modelList
}, {
name: 'expression',
description: '表达式',
control: [
{
control: 'code-editor',
slot: {},
attrs: {
isFormExpression: true,
language: 'javascript',
options: {
lineNumbers: "off",
scrollBeyondLastLine: false,
},
style: { width: '100%', height: '80px' }
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.expression
}, {
name: 'variable',
description: '变量',
control: [
{
control: 'variable-picker',
slot: {},
attrs: {
style: { width: '100%' },
allowClear: true,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'function',
description: '函数',
control: [
{
control: 'function-picker',
slot: {},
attrs: {
style: { width: '100%' },
allowClear: true,
size: 'small'
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.function
}, {
name: 'rules',
description: '校验规则',
control: [
{
control: 'rules-editor',
slot: {},
attrs: {
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.rules
}, {
name: 'box',
description: '盒模型编辑器',
control: [
{
control: 'box-editor',
slot: {},
attrs: {
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.box
}, {
name: 'api',
description: '接口',
control: [
{
control: 'api-editor',
slot: {},
attrs: {
},
events: {},
propAttrs: {}
}
],
editor: Enum.FormControlPropertyEditor.api
},
]
export function initPropertyEditors(): Record<string, FormDesign.PropertyEditor> {
// @ts-ignore
return Object.assign.apply({}, [{}].concat(propertyEditors.map(i => ({[i.name]: i}))));
} | the_stack |
import { Page, PageSection } from "@patternfly/react-core/dist/js/components/Page";
import { EmptyState, EmptyStateBody, EmptyStateIcon } from "@patternfly/react-core/dist/js/components/EmptyState";
import { CheckCircleIcon } from "@patternfly/react-icons/dist/js/icons/check-circle-icon";
import { Text, TextContent } from "@patternfly/react-core/dist/js/components/Text";
import { Button, ButtonVariant } from "@patternfly/react-core/dist/js/components/Button";
import { GithubIcon } from "@patternfly/react-icons/dist/js/icons/github-icon";
import { Spinner } from "@patternfly/react-core/dist/js/components/Spinner";
import { Form, FormGroup } from "@patternfly/react-core/dist/js/components/Form";
import { InputGroup } from "@patternfly/react-core/dist/js/components/InputGroup";
import { TextInput } from "@patternfly/react-core/dist/js/components/TextInput";
import * as React from "react";
import { useCallback, useMemo, useState } from "react";
import { AuthStatus, useSettings, useSettingsDispatch } from "./SettingsContext";
import { ExclamationTriangleIcon } from "@patternfly/react-icons/dist/js/icons/exclamation-triangle-icon";
import { useOnlineI18n } from "../i18n";
import { ExternalLinkAltIcon } from "@patternfly/react-icons/dist/js/icons/external-link-alt-icon";
export const GITHUB_OAUTH_TOKEN_SIZE = 40;
export const GITHUB_TOKENS_URL = "https://github.com/settings/tokens";
export const GITHUB_TOKENS_HOW_TO_URL =
"https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line";
export enum GitHubSignInOption {
PERSONAL_ACCESS_TOKEN,
OAUTH,
}
enum GitHubTokenScope {
GIST = "gist",
REPO = "repo",
}
/** UNCOMMENT FOR OAUTH WEB WORKFLOW WITH GITHUB **/
/* DUPLICATED FROM JAVA CLASS */
export interface GitHubOAuthResponse {
access_token: string;
token_type: string;
scope: string;
}
export function GitHubSettingsTab() {
const settings = useSettings();
const settingsDispatch = useSettingsDispatch();
const { i18n } = useOnlineI18n();
const [githubSignInOption, setGitHubSignInOption] = useState(GitHubSignInOption.PERSONAL_ACCESS_TOKEN);
const [potentialGitHubToken, setPotentialGitHubToken] = useState<string | undefined>(undefined);
const [isGitHubTokenValid, setIsGitHubTokenValid] = useState(true);
const githubTokenValidated = useMemo(() => {
return isGitHubTokenValid ? "default" : "error";
}, [isGitHubTokenValid]);
const githubTokenHelperText = useMemo(() => {
return isGitHubTokenValid ? undefined : "Invalid token. Check if it has the 'repo' scope.";
}, [isGitHubTokenValid]);
/** UNCOMMENT FOR OAUTH WEB WORKFLOW WITH GITHUB **/
// const [allowPrivateRepositories, setAllowPrivateRepositories] = useState(true);
// const basBackendEndpoint = `http://localhost:8080/github_oauth`;
// const queryParams = useQueryParams();
// const history = useHistory();
// const githubOAuthEndpoint = `https://github.com/login/oauth/authorize`;
// const GITHUB_APP_CLIENT_ID = `2d5a6222146b382e5fd8`;
// useEffect(() => {
// const effect = async () => {
// const code = queryParams.get(QueryParams.GITHUB_OAUTH_CODE);
// if (code) {
// const url = new URL(window.location.href);
// url.searchParams.delete(QueryParams.GITHUB_OAUTH_CODE);
// url.searchParams.delete(QueryParams.GITHUB_OAUTH_STATE);
// history.replace({
// pathname: history.location.pathname,
// search: url.search,
// });
//
// const res = await fetch(`${basBackendEndpoint}?code=${code}&client_id=${GITHUB_APP_CLIENT_ID}&redirect_uri=`);
// const resJson: GitHubOAuthResponse = await res.json();
// await settings.github.authService.authenticate(resJson.access_token);
// }
// };
// effect();
// }, [history, queryParams, settings.github.authService]);
//
// const onSignInWithGitHub = useCallback(() => {
// const redirectUri = new URL(`${window.location.href}`);
// redirectUri.searchParams.set(QueryParams.SETTINGS, SettingsTabs.GITHUB);
//
// const state = new Date().getTime();
// const scope = allowPrivateRepositories
// ? `${GitHubTokenScope.GIST},${GitHubTokenScope.REPO}`
// : GitHubTokenScope.GIST;
// const encodedRedirectUri = encodeURIComponent(decodeURIComponent(redirectUri.href));
// window.location.href = `${githubOAuthEndpoint}?scope=${scope}&state=${state}&client_id=${GITHUB_APP_CLIENT_ID}&allow_signup=true&redirect_uri=${encodedRedirectUri}`;
// }, [allowPrivateRepositories]);
const githubTokenToDisplay = useMemo(() => {
return obfuscate(potentialGitHubToken ?? settings.github.token);
}, [settings.github, potentialGitHubToken]);
const onPasteGitHubToken = useCallback(
(e) => {
const token = e.clipboardData.getData("text/plain").slice(0, GITHUB_OAUTH_TOKEN_SIZE);
setPotentialGitHubToken(token);
settingsDispatch.github.authService
.authenticate(token)
.then(() => setIsGitHubTokenValid(true))
.catch((e) => setIsGitHubTokenValid(false));
},
[settingsDispatch.github.authService]
);
const onSignOutFromGitHub = useCallback(() => {
settingsDispatch.github.authService.reset();
setPotentialGitHubToken(undefined);
}, [settingsDispatch.github.authService]);
return (
<Page>
{settings.github.authStatus === AuthStatus.TOKEN_EXPIRED && (
<PageSection>
<EmptyState>
<EmptyStateIcon icon={ExclamationTriangleIcon} />
<TextContent>
<Text component={"h2"}>GitHub Token expired</Text>
</TextContent>
<br />
<EmptyStateBody>
<TextContent>Reset your token to sign in with GitHub again.</TextContent>
<br />
<Button variant={ButtonVariant.tertiary} onClick={onSignOutFromGitHub}>
Reset
</Button>
</EmptyStateBody>
</EmptyState>
</PageSection>
)}
{settings.github.authStatus === AuthStatus.LOADING && (
<PageSection>
<EmptyState>
<EmptyStateIcon icon={GithubIcon} />
<TextContent>
<Text component={"h2"}>Signing in with GitHub</Text>
</TextContent>
<br />
<br />
<Spinner />
</EmptyState>
</PageSection>
)}
{settings.github.authStatus === AuthStatus.SIGNED_IN && (
<PageSection>
<EmptyState>
<EmptyStateIcon icon={CheckCircleIcon} color={"var(--pf-global--success-color--100)"} />
<TextContent>
<Text component={"h2"}>{"You're signed in with GitHub."}</Text>
</TextContent>
<EmptyStateBody>
<TextContent>
Gists are <b>{settings.github.scopes?.includes(GitHubTokenScope.GIST) ? "enabled" : "disabled"}.</b>
</TextContent>
<TextContent>
Private repositories are{" "}
<b>{settings.github.scopes?.includes(GitHubTokenScope.REPO) ? "enabled" : "disabled"}.</b>
</TextContent>
<br />
<TextContent>
<b>Token: </b>
<i>{obfuscate(settings.github.token)}</i>
</TextContent>
<TextContent>
<b>User: </b>
<i>{settings.github.user?.login}</i>
</TextContent>
<TextContent>
<b>Scope: </b>
<i>{settings.github.scopes?.join(", ") || "(none)"}</i>
</TextContent>
<br />
<Button variant={ButtonVariant.tertiary} onClick={onSignOutFromGitHub}>
Sign out
</Button>
</EmptyStateBody>
</EmptyState>
</PageSection>
)}
{settings.github.authStatus === AuthStatus.SIGNED_OUT && (
<>
<PageSection>
{/** UNCOMMENT FOR OAUTH WEB WORKFLOW WITH GITHUB **/}
{/*{githubSignInOption == GitHubSignInOption.OAUTH && (*/}
{/* <>*/}
{/* <EmptyState>*/}
{/* <EmptyStateIcon icon={GithubIcon} />*/}
{/* <TextContent>*/}
{/* <Text component={"h2"}>{"You're not connected to GitHub."}</Text>*/}
{/* </TextContent>*/}
{/* <EmptyStateBody>*/}
{/* <TextContent>{"Signing in with GitHub enables syncing your Workspaces."}</TextContent>*/}
{/* <TextContent>*/}
{/* {"You can also sign in using a "}*/}
{/* <a href={"#"} onClick={() => setGitHubSignInOption(GitHubSignInOption.PERSONAL_ACCESS_TOKEN)}>*/}
{/* Personal Access Token*/}
{/* </a>*/}
{/* {"."}*/}
{/* </TextContent>*/}
{/* <br />*/}
{/* <br />*/}
{/* <Bullseye>*/}
{/* <Checkbox*/}
{/* id="settings-github--allow-private-repositories"*/}
{/* isChecked={allowPrivateRepositories}*/}
{/* onChange={setAllowPrivateRepositories}*/}
{/* label={"Allow private repositories"}*/}
{/* />*/}
{/* </Bullseye>*/}
{/* <br />*/}
{/* <Button variant={ButtonVariant.primary} onClick={onSignInWithGitHub}>*/}
{/* Sign in with GitHub*/}
{/* </Button>*/}
{/* </EmptyStateBody>*/}
{/* </EmptyState>*/}
{/* </>*/}
{/*)}*/}
{githubSignInOption == GitHubSignInOption.PERSONAL_ACCESS_TOKEN && (
<>
<PageSection variant={"light"} isFilled={true} style={{ height: "100%" }}>
{/** UNCOMMENT FOR OAUTH WEB WORKFLOW WITH GITHUB **/}
{/*<Button*/}
{/* variant="link"*/}
{/* isInline={true}*/}
{/* icon={<AngleLeftIcon />}*/}
{/* onClick={() => setGitHubSignInOption(GitHubSignInOption.OAUTH)}*/}
{/*>*/}
{/* Back*/}
{/*</Button>*/}
{/*<br />*/}
{/*<br />*/}
<>
<p>
<span className="pf-u-mr-sm">{i18n.githubTokenModal.body.disclaimer}</span>
<a href={GITHUB_TOKENS_HOW_TO_URL} target={"_blank"}>
{i18n.githubTokenModal.body.learnMore}
<ExternalLinkAltIcon className="pf-u-mx-sm" />
</a>
</p>
</>
<br />
<h3>
<a href={GITHUB_TOKENS_URL} target={"_blank"}>
{i18n.githubTokenModal.footer.createNewToken}
<ExternalLinkAltIcon className="pf-u-mx-sm" />
</a>
</h3>
<br />
<Form>
<FormGroup
isRequired={true}
helperTextInvalid={githubTokenHelperText}
validated={githubTokenValidated}
label={"Token"}
fieldId={"github-pat"}
helperText={"Your token must include the 'repo' scope."}
>
<InputGroup>
<TextInput
autoComplete={"off"}
id="token-input"
name="tokenInput"
aria-describedby="token-text-input-helper"
placeholder={"Paste your GitHub token here"}
maxLength={GITHUB_OAUTH_TOKEN_SIZE}
validated={githubTokenValidated}
value={githubTokenToDisplay}
onPaste={onPasteGitHubToken}
autoFocus={true}
/>
</InputGroup>
</FormGroup>
</Form>
</PageSection>
</>
)}
</PageSection>
</>
)}
</Page>
);
}
export function obfuscate(token?: string) {
if (!token) {
return undefined;
}
if (token.length <= 8) {
return token;
}
const stars = new Array(token.length - 8).join("*");
const pieceToObfuscate = token.substring(4, token.length - 4);
return token.replace(pieceToObfuscate, stars);
} | the_stack |
import { MaticPOSClient } from '@maticnetwork/maticjs'
import rootChainManagerAbi from '@maticnetwork/meta/network/mainnet/v1/artifacts/pos/RootChainManager.json'
import chai from 'chai'
import { solidity } from 'ethereum-waffle'
import { BigNumber, Contract, Signer } from 'ethers'
import hre, {
contracts,
ethers,
getNamedAccounts,
getNamedSigner,
} from 'hardhat'
import { getMarkets, isEtheremNetwork } from '../../config'
import { Market } from '../../types/custom/config-types'
import {
ITellerDiamond,
MainnetNFTFacet,
MainnetNFTFacetMock,
MainnetTellerNFT,
TellerNFT,
TellerNFTDictionary,
TellerNFTV2,
} from '../../types/typechain'
import { DUMMY_ADDRESS, NULL_ADDRESS } from '../../utils/consts'
import { mintNFTV1, mintNFTV2 } from '../helpers/nft'
chai.should()
chai.use(solidity)
const maticPOSClient = new MaticPOSClient({
network: 'testnet',
version: 'mumbai',
parentProvider:
'https://mainnet.infura.io/v3/514733758a4e4c1da27f5e2d61c97ee4',
maticProvider: 'https://rpc-mainnet.maticvigil.com',
})
if (isEtheremNetwork(hre.network)) {
describe('Bridging Assets to Polygon', () => {
getMarkets(hre.network).forEach(testBridging)
function testBridging(markets: Market): void {
const { log } = hre
// define needed variablez
let deployer: Signer
let diamond: ITellerDiamond & MainnetNFTFacet & MainnetNFTFacetMock
let nftV1: TellerNFT
let nftV2: TellerNFTV2 & MainnetTellerNFT
let tellerDictionary: TellerNFTDictionary
let borrower: string
let borrowerSigner: Signer
let ownedNFTs: BigNumber[]
let rootChainManager: Contract
beforeEach(async () => {
await hre.deployments.fixture(['protocol'], {
keepExistingDeployments: true,
})
// declare variables
nftV1 = await contracts.get('TellerNFT')
nftV2 = await contracts.get('TellerNFT_V2')
tellerDictionary = await contracts.get('TellerNFTDictionary')
diamond = await contracts.get('TellerDiamond')
deployer = await getNamedSigner('deployer')
// get a regular borrower
borrowerSigner = await getNamedSigner('borrower')
borrower = await borrowerSigner.getAddress()
// Minting NFTV1 and V2 tokens
await mintNFTV1({
tierIndex: 1,
borrower: borrower,
hre,
})
await mintNFTV1({
tierIndex: 1,
borrower: borrower,
hre,
})
await mintNFTV2({
tierIndex: 1,
borrower: borrower,
amount: 1,
hre,
})
await mintNFTV2({
tierIndex: 1,
borrower: borrower,
amount: 1,
hre,
})
// approve spending v1 and v2 tokens on behalf of the user
await nftV1
.connect(borrowerSigner)
.setApprovalForAll(diamond.address, true)
await nftV2
.connect(borrowerSigner)
.setApprovalForAll(diamond.address, true)
// get owned nfts of borrower
ownedNFTs = await nftV1
.getOwnedTokens(borrower)
.then((arr) => (arr.length > 2 ? arr.slice(0, 2) : arr))
rootChainManager = new ethers.Contract(
'0xD4888faB8bd39A663B63161F5eE1Eae31a25B653',
rootChainManagerAbi.abi,
borrowerSigner
)
})
describe('Calling mapped contracts', () => {
it('should be able to bridge an unstaked NFTV1 to Polygon', async () => {
let ownedNFTsV1 = await nftV1.getOwnedTokens(borrower)
const lengthBeforeBridge = ownedNFTsV1.length
// Bridge NFTs and get their length
await diamond.connect(borrowerSigner).bridgeNFTsV1(ownedNFTsV1[0])
ownedNFTsV1 = await nftV1.getOwnedTokens(borrower)
const lengthAfterBridge = ownedNFTsV1.length
lengthBeforeBridge.should.equal(
lengthAfterBridge + (lengthBeforeBridge - lengthAfterBridge)
)
})
it('should be able to bridge a mock staked NFTV1 to Polygon', async () => {
// mock stake the NFTs
const ownedNFTsV1 = await nftV1.getOwnedTokens(borrower)
await diamond.connect(borrowerSigner).mockStakeNFTsV1(ownedNFTsV1)
// get the staked NFTs v1 of the user
const stakedNFTsV1 = await diamond.getStakedNFTs(borrower)
const lengthBeforeBridge = stakedNFTsV1.length
// bridge one staked NFT
await diamond.connect(borrowerSigner).bridgeNFTsV1(stakedNFTsV1[0])
// get the staked NFTs v1 of the user after we bridge
const stakedNFTsV11 = await diamond.getStakedNFTs(borrower)
const lengthAfterBridge = stakedNFTsV11.length
lengthBeforeBridge.should.equal(
lengthAfterBridge + (lengthBeforeBridge - lengthAfterBridge)
)
})
it('should be able to bridge a staked NFTV1 to Polygon', async () => {
// mock stake the NFTs
const ownedNFTsV1 = await nftV1.getOwnedTokens(borrower)
await diamond.connect(borrowerSigner).stakeNFTs(ownedNFTsV1)
// get the staked NFTs v1 of the user
const stakedNFTsV2BeforeBridge = await diamond.getStakedNFTsV2(
borrower
)
const lengthBeforeBridge = stakedNFTsV2BeforeBridge.staked_.length
// bridge one staked NFT
await diamond
.connect(borrowerSigner)
.bridgeNFTsV2(
stakedNFTsV2BeforeBridge.staked_[0],
stakedNFTsV2BeforeBridge.amounts_[0]
)
// get the staked NFTs v1 of the user after we bridge
const stakedNFTsV2AfterBridge = await diamond.getStakedNFTsV2(
borrower
)
const lengthAfterBridge = stakedNFTsV2BeforeBridge.staked_.length
lengthBeforeBridge.should.equal(
lengthAfterBridge + (lengthBeforeBridge - lengthAfterBridge)
)
})
it('should be able to bridge an unstaked NFTV2 to polygon', async () => {
// get owned nfts before bridge
let ownedNFTsV2 = await nftV2.getOwnedTokens(borrower)
const lengthBeforeBridge = ownedNFTsV2.length
// bridge
await diamond.connect(borrowerSigner).bridgeNFTsV2(ownedNFTsV2[0], 1)
// get owned nfts after bridge
ownedNFTsV2 = await nftV2.getOwnedTokens(borrower)
const lengthAfterBridge = ownedNFTsV2.length
lengthBeforeBridge.should.equal(
lengthAfterBridge + (lengthBeforeBridge - lengthAfterBridge)
)
})
it('should be able to bridge an staked NFTV2 to polygon', async () => {
// get owned nfts before bridge
let ownedNFTsV2 = await nftV2.getOwnedTokens(borrower)
const lengthBeforeBridge = ownedNFTsV2.length
// stake an NFT
await nftV2
.connect(borrowerSigner)
.safeTransferFrom(
borrower,
diamond.address,
ownedNFTsV2[0],
1,
'0x'
)
// get stakedNFTsV2
const stakedNFTsV2 = await diamond.getStakedNFTsV2(borrower)
// bridge a staked NFT
await diamond
.connect(borrowerSigner)
.bridgeNFTsV2(stakedNFTsV2.staked_[0], stakedNFTsV2.amounts_[0])
// get owned nfts after bridge
ownedNFTsV2 = await nftV2.getOwnedTokens(borrower)
const lengthAfterBridge = ownedNFTsV2.length
lengthBeforeBridge.should.equal(
lengthAfterBridge + (lengthBeforeBridge - lengthAfterBridge)
)
})
})
describe('Mock tests', () => {
describe('stake, unstake, deposit to polygon', () => {
it('tier data matches between v1 and v2', async () => {
// we use filter to get the Event that will be emitted when we mint the token
const filter = nftV1.filters.Transfer(
NULL_ADDRESS,
DUMMY_ADDRESS,
null
)
// array of v1 tiers
const arrayOfTiers = [0, 1, 2, 3, 8, 9, 10, 11]
// mint the token on the tier index, then retrieve the emitted event using transaction's
// block hash
const mintToken = async (tierIndex: number): Promise<void> => {
const receipt = await nftV1
.connect(deployer)
.mint(tierIndex, DUMMY_ADDRESS)
.then(({ wait }) => wait())
const [event] = await nftV1.queryFilter(filter, receipt.blockHash)
// set the token tier that we just minted according to the tier index. so, minting 2nd NFT
// on tier 1 will result in ID = 20001
await tellerDictionary
.connect(deployer)
.setTokenTierForTokenId(event.args.tokenId, tierIndex)
}
// mint 3 tokens on every tier for the DUMMY_ADDRESS
for (let i = 0; i < arrayOfTiers.length; i++) {
await mintToken(arrayOfTiers[i])
await mintToken(arrayOfTiers[i])
await mintToken(arrayOfTiers[i])
}
// get our token ids and loop through it. for every loop, we check if the V1TokenURI
// is = to the URI of our V2 tokenId
const tokenIds = await nftV1.getOwnedTokens(DUMMY_ADDRESS)
for (let i = 0; i < tokenIds.length; i++) {
// convert token id
const newTokenId = await nftV2.convertV1TokenId(tokenIds[i])
// uris
const v1TokenURI = await nftV1.tokenURI(tokenIds[i])
const v2TokenURI = await nftV2.uri(newTokenId)
v1TokenURI.should.equal(v2TokenURI)
const v1BaseLoanSize = await tellerDictionary.tokenBaseLoanSize(
tokenIds[i]
)
const v2BaseLoanSize = await nftV2.tokenBaseLoanSize(newTokenId)
v1BaseLoanSize.should.eql(v2BaseLoanSize)
const v1ContributionSize =
await tellerDictionary.tokenContributionSize(tokenIds[i])
const v2ContributionSize = await nftV2.tokenContributionSize(
newTokenId
)
v1ContributionSize.should.eql(v2ContributionSize)
const v1ContributionMultiplier =
await tellerDictionary.tokenContributionMultiplier(tokenIds[i])
const v2ContributionMultiplier =
await nftV2.tokenContributionMultiplier(newTokenId)
;(v1ContributionMultiplier * 100).should.eql(
v2ContributionMultiplier
)
}
})
it('migrates an NFT from V1 to V2', async () => {
// mint the token, then transfer it to v2
await nftV1.connect(deployer).mint(0, borrower)
const [nftId] = await nftV1.getOwnedTokens(borrower)
// v2 tokens before should = 0
const v2TokensBefore = await nftV2.getOwnedTokens(borrower)
v2TokensBefore.length.should.equal(2)
// v2 tokens after should = 1
await nftV1
.connect(borrowerSigner)
['safeTransferFrom(address,address,uint256)'](
borrower,
nftV2.address,
nftId
)
const v2TokensAfter = await nftV2.getOwnedTokens(borrower)
v2TokensBefore.length.should.equal(
v2TokensAfter.length +
(v2TokensBefore.length - v2TokensAfter.length)
)
})
})
})
}
})
} | the_stack |
module PhaserAds {
export module AdProvider {
export enum CocoonProvider {
AdMob,
MoPub,
Chartboost,
Heyzap
}
export class CocoonAds implements IProvider {
public adManager: AdManager;
public adsEnabled: boolean = false;
private cocoonProvider: Cocoon.Ad.IAdProvider;
private banner: Cocoon.Ad.IBanner = null;
private bannerShowable: boolean = false;
private interstitial: Cocoon.Ad.IBanner = null;
private interstitialShowable: boolean = false;
private rewarded: Cocoon.Ad.IBanner = null;
public hasRewarded: boolean = false;
constructor(game: Phaser.Game, provider: CocoonProvider, config?: any) {
if ((game.device.cordova || game.device.crosswalk) && (Cocoon && Cocoon.Ad)) {
this.adsEnabled = true;
} else {
return;
}
switch (provider) {
default:
case CocoonProvider.AdMob:
this.cocoonProvider = Cocoon.Ad.AdMob;
break;
case CocoonProvider.Chartboost:
this.cocoonProvider = Cocoon.Ad.Chartboost;
break;
case CocoonProvider.Heyzap:
this.cocoonProvider = Cocoon.Ad.Heyzap;
break;
case CocoonProvider.MoPub:
this.cocoonProvider = Cocoon.Ad.MoPub;
break;
}
this.cocoonProvider.configure(config);
}
public setManager(manager: AdManager): void {
this.adManager = manager;
}
public showAd(adType: AdType): void {
if (!this.adsEnabled) {
this.adManager.unMuteAfterAd();
if (!(adType === AdType.banner)) {
this.adManager.onContentResumed.dispatch();
}
return;
}
if (adType === AdType.banner) {
if (!this.bannerShowable || null === this.banner) {
this.adManager.unMuteAfterAd();
//No banner ad available, skipping
//this.adManager.onContentResumed.dispatch(CocoonAdType.banner);
return;
}
this.adManager.onBannerShown.dispatch(this.banner.width, this.banner.height);
this.adManager.bannerActive = true;
this.banner.show();
}
if (adType === AdType.interstitial) {
if (!this.interstitialShowable || null === this.interstitial) {
this.adManager.unMuteAfterAd();
//No banner ad available, skipping
this.adManager.onContentResumed.dispatch(AdType.interstitial);
return;
}
this.interstitial.show();
}
if (adType === AdType.rewarded) {
if (!this.hasRewarded || null === this.rewarded) {
this.adManager.unMuteAfterAd();
//No banner ad available, skipping
this.adManager.onContentResumed.dispatch(AdType.rewarded);
return;
}
this.rewarded.show();
}
}
public preloadAd(adType: AdType, adId?: string, bannerPosition?: string): void {
if (!this.adsEnabled) {
return;
}
//Some cleanup before preloading a new ad
this.destroyAd(adType);
if (adType === AdType.banner) {
this.banner = this.cocoonProvider.createBanner(adId);
if (bannerPosition) {
this.banner.setLayout(bannerPosition);
}
this.banner.on('load', () => {
this.bannerShowable = true;
});
this.banner.on('fail', () => {
this.bannerShowable = false;
this.banner = null;
});
this.banner.on('click', () => {
this.adManager.onAdClicked.dispatch(AdType.banner);
});
//Banner don't pause or resume content
this.banner.on('show', () => {
/*this.adManager.onBannerShown.dispatch(this.banner.width, this.banner.height);
this.adManager.bannerActive = true;*/
// this.adManager.onContentPaused.dispatch(AdType.banner);
});
this.banner.on('dismiss', () => {
/*this.adManager.bannerActive = false;
this.adManager.onBannerHidden.dispatch(this.banner.width, this.banner.height);*/
// this.adManager.onContentResumed.dispatch(AdType.banner);
// this.bannerShowable = false;
// this.banner = null;
});
this.banner.load();
}
if (adType === AdType.interstitial) {
this.interstitial = this.cocoonProvider.createInterstitial(adId);
this.interstitial.on('load', () => {
this.interstitialShowable = true;
});
this.interstitial.on('fail', () => {
this.interstitialShowable = false;
this.interstitial = null;
});
this.interstitial.on('click', () => {
this.adManager.onAdClicked.dispatch(AdType.interstitial);
});
this.interstitial.on('show', () => {
this.adManager.onContentPaused.dispatch(AdType.interstitial);
});
this.interstitial.on('dismiss', () => {
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch(AdType.interstitial);
this.interstitialShowable = false;
this.interstitial = null;
});
this.interstitial.load();
}
if (adType === AdType.rewarded) {
this.rewarded = this.cocoonProvider.createRewardedVideo(adId);
this.rewarded.on('load', () => {
this.hasRewarded = true;
});
this.rewarded.on('fail', () => {
this.hasRewarded = false;
this.rewarded = null;
});
this.rewarded.on('click', () => {
this.adManager.onAdClicked.dispatch(AdType.rewarded);
});
this.rewarded.on('show', () => {
this.adManager.onContentPaused.dispatch(AdType.rewarded);
});
this.rewarded.on('dismiss', () => {
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch(AdType.rewarded);
this.hasRewarded = false;
this.rewarded = null;
});
this.rewarded.on('reward', () => {
this.adManager.unMuteAfterAd();
this.adManager.onAdRewardGranted.dispatch(AdType.rewarded);
this.hasRewarded = false;
this.rewarded = null;
});
this.rewarded.load();
}
}
public destroyAd(adType: AdType): void {
if (!this.adsEnabled) {
return;
}
if (adType === AdType.banner && null !== this.banner) {
//Releasing banners will fail on cocoon due to:
// https://github.com/ludei/atomic-plugins-ads/pull/12
try {
this.cocoonProvider.releaseBanner(this.banner);
} catch (e) {
//silently ignore
}
this.banner = null;
this.bannerShowable = false;
}
if (adType === AdType.interstitial && null !== this.interstitial) {
this.cocoonProvider.releaseInterstitial(this.interstitial);
this.interstitial = null;
this.interstitialShowable = false;
}
}
public hideAd(adType: AdType): void {
if (!this.adsEnabled) {
return;
}
if (adType === AdType.interstitial && null !== this.interstitial) {
this.interstitial.hide();
// this.adManager.onContentResumed.dispatch(AdType.interstitial);
}
if (adType === AdType.banner && null !== this.banner) {
if (this.adManager.bannerActive) {
this.adManager.bannerActive = false;
this.adManager.onBannerHidden.dispatch(this.banner.width, this.banner.height);
}
this.banner.hide();
// this.adManager.onContentResumed.dispatch(AdType.banner);
}
if (adType === AdType.rewarded && null !== this.rewarded) {
this.rewarded.hide();
// this.adManager.onContentResumed.dispatch(AdType.rewarded);
}
}
/*public setLayout(bannerPosition: string): void {
this.banner.setLayout(bannerPosition);
}
public setPosition(x: number, y: number): void {
this.banner.setPosition(x, y);
}*/
}
}
} | the_stack |
import __Utils = require("./Utils")
export import Utils = __Utils.Utils;
import __Vec3 = require("./Vec3")
export import Vec3 = __Vec3.Vec3;
/**
* A two-component vector type.
*/
export class Vec2 {
x: number;
y: number;
// TODO:
// GetAngleBetween
/**
* Default initializes the vector to all zero.
*/
constructor(x: number = 0, y: number = 0) { // [tested]
this.x = x;
this.y = y;
}
/**
* Returns a duplicate of this vector.
*/
Clone(): Vec2 { // [tested]
return new Vec2(this.x, this.y);
}
/**
* Returns a duplicate of this as a Vec3, with the provided value as z.
*/
CloneAsVec3(z: number = 0): Vec3 { // [NOT tested (fails to compile)]
return new Vec3(this.x, this.y, z);
}
/**
* Returns a vector with all components set to zero.
*/
static ZeroVector(): Vec2 { // [tested]
return new Vec2(0, 0);
}
/**
* Returns a vector with all components set to one.
*/
static OneVector(): Vec2 { // [tested]
return new Vec2(1, 1);
}
/**
* Returns the vector (1, 0)
*/
static UnitAxisX(): Vec2 { // [tested]
return new Vec2(1, 0);
}
/**
* Returns the vector (0, 1)
*/
static UnitAxisY(): Vec2 { // [tested]
return new Vec2(0, 1);
}
/**
* Sets all components to the given values.
*/
Set(x: number, y: number): void { // [tested]
this.x = x;
this.y = y;
}
/**
* Copies all component values from rhs.
*/
SetVec2(rhs: Vec2): void { // [tested]
this.x = rhs.x;
this.y = rhs.y;
}
/**
* Sets all components to the value 'val'.
*/
SetAll(val: number): void { // [tested]
this.x = val;
this.y = val;
}
/**
* Sets all components to zero.
*/
SetZero(): void { // [tested]
this.x = 0;
this.y = 0;
}
/**
* Returns the squared length of the vector.
*/
GetLengthSquared(): number { // [tested]
return this.x * this.x + this.y * this.y;
}
/**
* Returns the length of the vector.
*/
GetLength(): number { // [tested]
return Math.sqrt(this.x * this.x + this.y * this.y);
}
/**
* Computes and returns the length of the vector, and normalizes the vector.
* This is more efficient than calling GetLength() followed by Normalize().
*/
GetLengthAndNormalize(): number { // [tested]
let length = this.GetLength();
let invLength = 1.0 / length;
this.x *= invLength;
this.y *= invLength;
return length;
}
/**
* Normalizes the vector. Afterwards its length will be one.
* This only works on non-zero vectors. Calling Normalize() on a zero-vector is an error.
*/
Normalize(): void { // [tested]
let invLength = 1.0 / this.GetLength();
this.x *= invLength;
this.y *= invLength;
}
/**
* Returns a normalized duplicate of this vector.
* Calling this on a zero-vector is an error.
*/
GetNormalized(): Vec2 { // [tested]
let norm = this.Clone();
norm.Normalize();
return norm;
}
/**
* Normalizes the vector as long as it is not a zero-vector (within the given epsilon).
* If it is determined to be too close to zero, it is set to 'fallback'.
*
* @param fallback The value to use in case 'this' is too close to zero.
* @param epsilon The epsilon within this vector is considered to be a zero-vector.
* @returns true if the vector was normalized regularly, false if the vector was close to zero and 'fallback' was used instead.
*/
NormalizeIfNotZero(fallback: Vec2 = new Vec2(1, 0), epsilon: number = 0.000001): boolean { // [tested]
let length = this.GetLength();
if (length >= -epsilon && length <= epsilon) {
this.SetVec2(fallback);
return false;
}
this.DivNumber(length);
return true;
}
/**
* Checks whether all components of this are close to zero.
*/
IsZero(epsilon: number = 0): boolean { // [tested]
if (epsilon != 0) {
return this.x >= -epsilon && this.x <= epsilon &&
this.y >= -epsilon && this.y <= epsilon;
}
else {
return this.x == 0 && this.y == 0;
}
}
/**
* Checks whether this is normalized within some epsilon.
*/
IsNormalized(epsilon: number = 0.001): boolean { // [tested]
let length = this.GetLength();
return (length >= 1.0 - epsilon) && (length <= 1.0 + epsilon);
}
/**
* Returns a negated duplicate of this.
*/
GetNegated(): Vec2 { // [tested]
return new Vec2(-this.x, -this.y);
}
/**
* Negates all components of this.
*/
Negate(): void { // [tested]
this.x = -this.x;
this.y = -this.y;
}
/**
* Adds rhs component-wise to this.
*/
AddVec2(rhs: Vec2): void { // [tested]
this.x += rhs.x;
this.y += rhs.y;
}
/**
* Subtracts rhs component-wise from this.
*/
SubVec2(rhs: Vec2): void { // [tested]
this.x -= rhs.x;
this.y -= rhs.y;
}
/**
* Multiplies rhs component-wise into this.
*/
MulVec2(rhs: Vec2): void { // [tested]
this.x *= rhs.x;
this.y *= rhs.y;
}
/**
* Divides each component of this by rhs.
*/
DivVec2(rhs: Vec2): void { // [tested]
this.x /= rhs.x;
this.y /= rhs.y;
}
/**
* Multiplies all components of this by 'val'.
*/
MulNumber(val: number): void { // [tested]
this.x *= val;
this.y *= val;
}
/**
* Divides all components of this by 'val'.
*/
DivNumber(val: number): void { // [tested]
let invVal = 1.0 / val;
this.x *= invVal;
this.y *= invVal;
}
/**
* Checks whether this and rhs are exactly identical.
*/
IsIdentical(rhs: Vec2): boolean { // [tested]
return this.x == rhs.x && this.y == rhs.y;
}
/**
* Checks whether this and rhs are approximately equal within a given epsilon.
*/
IsEqual(rhs: Vec2, epsilon: number): boolean { // [tested]
return (this.x >= rhs.x - epsilon && this.x <= rhs.x + epsilon) &&
(this.y >= rhs.y - epsilon && this.y <= rhs.y + epsilon);
}
/**
* Returns the dot-product between this and rhs.
*/
Dot(rhs: Vec2): number { // [tested]
return this.x * rhs.x + this.y * rhs.y;
}
/**
* Returns a vector consisting of the minimum of the respective components of this and rhs.
*/
GetCompMin(rhs: Vec2): Vec2 { // [tested]
return new Vec2(Math.min(this.x, rhs.x), Math.min(this.y, rhs.y));
}
/**
* Returns a vector consisting of the maximum of the respective components of this and rhs.
*/
GetCompMax(rhs: Vec2): Vec2 { // [tested]
return new Vec2(Math.max(this.x, rhs.x), Math.max(this.y, rhs.y));
}
/**
* Returns a vector where each component is set to this component's value, clamped to the respective low and high value.
*/
GetCompClamp(low: Vec2, high: Vec2): Vec2 { // [tested]
let _x = Math.max(low.x, Math.min(high.x, this.x));
let _y = Math.max(low.y, Math.min(high.y, this.y));
return new Vec2(_x, _y);
}
/**
* Returns a vector with each component being the product of this and rhs.
*/
GetCompMul(rhs: Vec2): Vec2 { // [tested]
return new Vec2(this.x * rhs.x, this.y * rhs.y);
}
/**
* Returns a vector with each component being the division of this and rhs.
*/
GetCompDiv(rhs: Vec2): Vec2 { // [tested]
return new Vec2(this.x / rhs.x, this.y / rhs.y);
}
/**
* Returns a vector with each component set to the absolute value of this vector's respective component.
*/
GetAbs(): Vec2 { // [tested]
return new Vec2(Math.abs(this.x), Math.abs(this.y));
}
/**
* Sets this vector's components to the absolute value of lhs's respective components.
*/
SetAbs(lhs: Vec2): void { // [tested]
this.x = Math.abs(lhs.x);
this.y = Math.abs(lhs.y);
}
/**
* Returns a vector that is this vector reflected along the given normal.
*/
GetReflectedVector(normal: Vec2): Vec2 { // [tested]
let res = this.Clone();
let tmp = normal.Clone();
tmp.MulNumber(this.Dot(normal) * 2.0);
res.SubVec2(tmp);
return res;
}
/**
* Sets this vector to be the addition of lhs and rhs.
*/
SetAdd(lhs: Vec2, rhs: Vec2): void { // [tested]
this.x = lhs.x + rhs.x;
this.y = lhs.y + rhs.y;
}
/**
* Sets this vector to be the subtraction of lhs and rhs.
*/
SetSub(lhs: Vec2, rhs: Vec2): void { // [tested]
this.x = lhs.x - rhs.x;
this.y = lhs.y - rhs.y;
}
/**
* Sets this vector to be the product of lhs and rhs.
*/
SetMul(lhs: Vec2, rhs: number): void { // [tested]
this.x = lhs.x * rhs;
this.y = lhs.y * rhs;
}
/**
* Sets this vector to be the division of lhs and rhs.
*/
SetDiv(lhs: Vec2, rhs: number): void { // [tested]
let invRhs = 1.0 / rhs;
this.x = lhs.x * invRhs;
this.y = lhs.y * invRhs;
}
/**
* Returns a random point inside a circle of radius 1 around the origin.
*/
static CreateRandomPointInCircle(): Vec2 { // [tested]
let px: number, py: number;
let len: number = 0.0;
do {
px = Math.random() * 2.0 - 1.0;
py = Math.random() * 2.0 - 1.0;
len = (px * px) + (py * py);
} while (len > 1.0 || len <= 0.000001); // prevent the exact center
return new Vec2(px, py);
}
/**
* Returns a random direction vector.
*/
static CreateRandomDirection(): Vec2 { // [tested]
let res = Vec2.CreateRandomPointInCircle();
res.Normalize();
return res;
}
} | the_stack |
export interface Stylesheet {
rules: Rule[];
}
export type Rule = QualifiedRule | AtRule;
export interface AtRule {
type: 'at-rule';
name: string;
prelude: InputToken[];
block: SimpleBlock;
}
export interface QualifiedRule {
type: 'qualified-rule';
prelude: InputToken[];
block: SimpleBlock;
}
// const nonQuoteURLRegEx = /(:?[^\)\s\t\n\r\f\'\"\(]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*/gym; // TODO: non-printable code points omitted
export type InputToken = '(' | ')' | '{' | '}' | '[' | ']' | ':' | ';' | ',' | ' ' | '^=' | '|=' | '$=' | '*=' | '~=' | '<!--' | '-->' | undefined | /* <EOF-token> */ InputTokenObject | FunctionInputToken | FunctionToken | SimpleBlock | AtKeywordToken;
export const enum TokenObjectType {
/**
* <string-token>
*/
string = 1,
/**
* <delim-token>
*/
delim = 2,
/**
* <number-token>
*/
number = 3,
/**
* <percentage-token>
*/
percentage = 4,
/**
* <dimension-token>
*/
dimension = 5,
/**
* <ident-token>
*/
ident = 6,
/**
* <url-token>
*/
url = 7,
/**
* <function-token>
* This is a token indicating a function's leading: <ident-token>(
*/
functionToken = 8,
/**
* <simple-block>
*/
simpleBlock = 9,
/**
* <comment-token>
*/
comment = 10,
/**
* <at-keyword-token>
*/
atKeyword = 11,
/**
* <hash-token>
*/
hash = 12,
/**
* <function>
* This is a complete consumed function: <function-token>([<component-value> [, <component-value>]*])")"
*/
function = 14,
}
export interface InputTokenObject {
type: TokenObjectType;
text: string;
}
/**
* This is a "<ident>(" token.
*/
export interface FunctionInputToken extends InputTokenObject {
name: string;
}
/**
* This is a completely parsed function like "<ident>([component [, component]*])".
*/
export interface FunctionToken extends FunctionInputToken {
components: any[];
}
export interface SimpleBlock extends InputTokenObject {
associatedToken: InputToken;
values: InputToken[];
}
export type AtKeywordToken = InputTokenObject;
const commentRegEx = /(\/\*(?:[^\*]|\*[^\/])*\*\/)/gmy;
// eslint-disable-next-line no-control-regex
const nameRegEx = /-?(?:(?:[a-zA-Z_]|[^\x00-\x7F]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))(?:[a-zA-Z_0-9\-]*|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)/gmy;
const numberRegEx = /[\+\-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][\+\-]?\d+)?/gmy;
const doubleQuoteStringRegEx = /"((?:[^\n\r\f\"]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?"|$)/gmy; // Besides $n, parse escape
const whitespaceRegEx = /[\s\t\n\r\f]*/gmy;
const singleQuoteStringRegEx = /'((?:[^\n\r\f\']|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?'|$)/gmy; // Besides $n, parse escape
/**
* CSS parser following relatively close:
* CSS Syntax Module Level 3
* https://www.w3.org/TR/css-syntax-3/
*/
export class CSS3Parser {
private nextInputCodePointIndex = 0;
private reconsumedInputToken: InputToken;
private topLevelFlag: boolean;
constructor(private text: string) { }
/**
* For testing purposes.
* This method allows us to run and assert the proper working of the tokenizer.
*/
tokenize(): InputToken[] {
const tokens: InputToken[] = [];
let inputToken: InputToken;
do {
inputToken = this.consumeAToken();
tokens.push(inputToken);
} while (inputToken);
return tokens;
}
/**
* 4.3.1. Consume a token
* https://www.w3.org/TR/css-syntax-3/#consume-a-token
*/
private consumeAToken(): InputToken {
if (this.reconsumedInputToken) {
const result = this.reconsumedInputToken;
this.reconsumedInputToken = null;
return result;
}
const char = this.text[this.nextInputCodePointIndex];
switch (char) {
case '"':
return this.consumeAStringToken();
case "'":
return this.consumeAStringToken();
case '(':
case ')':
case ',':
case ':':
case ';':
case '[':
case ']':
case '{':
case '}':
this.nextInputCodePointIndex++;
return <any>char;
case '#':
return this.consumeAHashToken() || this.consumeADelimToken();
case ' ':
case '\t':
case '\n':
case '\r':
case '\f':
return this.consumeAWhitespace();
case '@':
return this.consumeAtKeyword() || this.consumeADelimToken();
// TODO: Only if this is valid escape, otherwise it is a parse error
case '\\':
return this.consumeAnIdentLikeToken() || this.consumeADelimToken();
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return this.consumeANumericToken();
case 'u':
case 'U':
if (this.text[this.nextInputCodePointIndex + 1] === '+') {
const thirdChar = this.text[this.nextInputCodePointIndex + 2];
if ((thirdChar >= '0' && thirdChar <= '9') || thirdChar === '?') {
// TODO: Handle unicode stuff such as U+002B
throw new Error('Unicode tokens not supported!');
}
}
return this.consumeAnIdentLikeToken() || this.consumeADelimToken();
case '$':
case '*':
case '^':
case '|':
case '~':
return this.consumeAMatchToken() || this.consumeADelimToken();
case '-':
return this.consumeANumericToken() || this.consumeAnIdentLikeToken() || this.consumeCDC() || this.consumeADelimToken();
case '+':
case '.':
return this.consumeANumericToken() || this.consumeADelimToken();
case '/':
return this.consumeAComment() || this.consumeADelimToken();
case '<':
return this.consumeCDO() || this.consumeADelimToken();
case undefined:
return undefined;
default:
return this.consumeAnIdentLikeToken() || this.consumeADelimToken();
}
}
private consumeADelimToken(): InputToken {
return {
type: TokenObjectType.delim,
text: this.text[this.nextInputCodePointIndex++],
};
}
private consumeAWhitespace(): InputToken {
whitespaceRegEx.lastIndex = this.nextInputCodePointIndex;
whitespaceRegEx.exec(this.text);
this.nextInputCodePointIndex = whitespaceRegEx.lastIndex;
return ' ';
}
private consumeAHashToken(): InputTokenObject {
this.nextInputCodePointIndex++;
const hashName = this.consumeAName();
if (hashName) {
return { type: TokenObjectType.hash, text: '#' + hashName.text };
}
this.nextInputCodePointIndex--;
return null;
}
private consumeCDO(): '<!--' | null {
if (this.text.substr(this.nextInputCodePointIndex, 4) === '<!--') {
this.nextInputCodePointIndex += 4;
return '<!--';
}
return null;
}
private consumeCDC(): '-->' | null {
if (this.text.substr(this.nextInputCodePointIndex, 3) === '-->') {
this.nextInputCodePointIndex += 3;
return '-->';
}
return null;
}
private consumeAMatchToken(): '*=' | '$=' | '|=' | '~=' | '^=' | null {
if (this.text[this.nextInputCodePointIndex + 1] === '=') {
const token = this.text.substr(this.nextInputCodePointIndex, 2);
this.nextInputCodePointIndex += 2;
return <'*=' | '$=' | '|=' | '~=' | '^='>token;
}
return null;
}
/**
* 4.3.2. Consume a numeric token
* https://www.w3.org/TR/css-syntax-3/#consume-a-numeric-token
*/
private consumeANumericToken(): InputToken {
numberRegEx.lastIndex = this.nextInputCodePointIndex;
const result = numberRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = numberRegEx.lastIndex;
if (this.text[this.nextInputCodePointIndex] === '%') {
return { type: TokenObjectType.percentage, text: result[0] }; // TODO: Push the actual number and unit here...
}
const name = this.consumeAName();
if (name) {
return {
type: TokenObjectType.dimension,
text: result[0] + name.text,
};
}
return { type: TokenObjectType.number, text: result[0] };
}
/**
* 4.3.3. Consume an ident-like token
* https://www.w3.org/TR/css-syntax-3/#consume-an-ident-like-token
*/
private consumeAnIdentLikeToken(): InputToken {
const name = this.consumeAName();
if (!name) {
return null;
}
if (this.text[this.nextInputCodePointIndex] === '(') {
this.nextInputCodePointIndex++;
if (name.text.toLowerCase() === 'url') {
return this.consumeAURLToken();
}
return <FunctionInputToken>{
type: TokenObjectType.functionToken,
name: name.text,
text: name.text + '(',
};
}
return name;
}
/**
* 4.3.4. Consume a string token
* https://www.w3.org/TR/css-syntax-3/#consume-a-string-token
*/
private consumeAStringToken(): InputTokenObject {
const char = this.text[this.nextInputCodePointIndex];
let result: RegExpExecArray;
if (char === "'") {
singleQuoteStringRegEx.lastIndex = this.nextInputCodePointIndex;
result = singleQuoteStringRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = singleQuoteStringRegEx.lastIndex;
} else if (char === '"') {
doubleQuoteStringRegEx.lastIndex = this.nextInputCodePointIndex;
result = doubleQuoteStringRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = doubleQuoteStringRegEx.lastIndex;
}
// TODO: Handle bad-string.
// TODO: Perform string escaping.
return { type: TokenObjectType.string, text: result[0] };
}
/**
* 4.3.5. Consume a url token
* https://www.w3.org/TR/css-syntax-3/#consume-a-url-token
*/
private consumeAURLToken(): InputToken {
const start = this.nextInputCodePointIndex - 3 /* url */ - 1; /* ( */
const urlToken: InputToken = {
type: TokenObjectType.url,
text: undefined,
};
this.consumeAWhitespace();
if (this.nextInputCodePointIndex >= this.text.length) {
return urlToken;
}
const nextInputCodePoint = this.text[this.nextInputCodePointIndex];
if (nextInputCodePoint === '"' || nextInputCodePoint === "'") {
const stringToken = this.consumeAStringToken();
// TODO: Handle bad-string.
// TODO: Set value instead.
urlToken.text = stringToken.text;
this.consumeAWhitespace();
if (this.text[this.nextInputCodePointIndex] === ')' || this.nextInputCodePointIndex >= this.text.length) {
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
urlToken.text = this.text.substring(start, end);
return urlToken;
} else {
// TODO: Handle bad-url.
return null;
}
}
while (this.nextInputCodePointIndex < this.text.length) {
const char = this.text[this.nextInputCodePointIndex++];
switch (char) {
case ')':
return urlToken;
case ' ':
case '\t':
case '\n':
case '\r':
case '\f':
this.consumeAWhitespace();
if (this.text[this.nextInputCodePointIndex] === ')') {
this.nextInputCodePointIndex++;
return urlToken;
} else {
// TODO: Bar url! Consume remnants.
return null;
}
case '"':
case "'":
// TODO: Parse error! Bar url! Consume remnants.
return null;
case '\\':
// TODO: Escape!
throw new Error('Escaping not yet supported!');
default:
// TODO: Non-printable chars - error.
urlToken.text += char;
}
}
return urlToken;
}
/**
* 4.3.11. Consume a name
* https://www.w3.org/TR/css-syntax-3/#consume-a-name
*/
private consumeAName(): InputTokenObject {
nameRegEx.lastIndex = this.nextInputCodePointIndex;
const result = nameRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = nameRegEx.lastIndex;
// TODO: Perform string escaping.
return { type: TokenObjectType.ident, text: result[0] };
}
private consumeAtKeyword(): InputTokenObject {
this.nextInputCodePointIndex++;
const name = this.consumeAName();
if (name) {
return { type: TokenObjectType.atKeyword, text: name.text };
}
this.nextInputCodePointIndex--;
return null;
}
private consumeAComment(): InputToken {
if (this.text[this.nextInputCodePointIndex + 1] === '*') {
commentRegEx.lastIndex = this.nextInputCodePointIndex;
const result = commentRegEx.exec(this.text);
if (!result) {
return null; // TODO: Handle <bad-comment>
}
this.nextInputCodePointIndex = commentRegEx.lastIndex;
// The CSS spec tokenizer does not emmit comment tokens
return this.consumeAToken();
}
return null;
}
private reconsumeTheCurrentInputToken(currentInputToken: InputToken) {
this.reconsumedInputToken = currentInputToken;
}
/**
* 5.3.1. Parse a stylesheet
* https://www.w3.org/TR/css-syntax-3/#parse-a-stylesheet
*/
public parseAStylesheet(): Stylesheet {
this.topLevelFlag = true;
return {
rules: this.consumeAListOfRules(),
};
}
/**
* 5.4.1. Consume a list of rules
* https://www.w3.org/TR/css-syntax-3/#consume-a-list-of-rules
*/
public consumeAListOfRules(): Rule[] {
const rules: Rule[] = [];
let inputToken: InputToken;
while ((inputToken = this.consumeAToken())) {
switch (inputToken) {
case ' ':
continue;
case '<!--':
case '-->': {
if (this.topLevelFlag) {
continue;
}
this.reconsumeTheCurrentInputToken(inputToken);
const atRule = this.consumeAnAtRule();
if (atRule) {
rules.push(atRule);
}
continue;
}
}
if ((<InputTokenObject>inputToken).type === TokenObjectType.atKeyword) {
this.reconsumeTheCurrentInputToken(inputToken);
const atRule = this.consumeAnAtRule();
if (atRule) {
rules.push(atRule);
}
continue;
}
this.reconsumeTheCurrentInputToken(inputToken);
const qualifiedRule = this.consumeAQualifiedRule();
if (qualifiedRule) {
rules.push(qualifiedRule);
}
}
return rules;
}
/**
* 5.4.2. Consume an at-rule
* https://www.w3.org/TR/css-syntax-3/#consume-an-at-rule
*/
public consumeAnAtRule(): AtRule {
let inputToken = this.consumeAToken();
const atRule: AtRule = {
type: 'at-rule',
name: (<AtKeywordToken>inputToken).text,
prelude: [],
block: undefined,
};
while ((inputToken = this.consumeAToken())) {
if (inputToken === ';') {
return atRule;
} else if (inputToken === '{') {
atRule.block = this.consumeASimpleBlock(inputToken);
return atRule;
} else if ((<InputTokenObject>inputToken).type === TokenObjectType.simpleBlock && (<SimpleBlock>inputToken).associatedToken === '{') {
atRule.block = <SimpleBlock>inputToken;
return atRule;
}
this.reconsumeTheCurrentInputToken(inputToken);
const component = this.consumeAComponentValue();
if (component) {
atRule.prelude.push(component);
}
}
return atRule;
}
/**
* 5.4.3. Consume a qualified rule
* https://www.w3.org/TR/css-syntax-3/#consume-a-qualified-rule
*/
public consumeAQualifiedRule(): QualifiedRule {
const qualifiedRule: QualifiedRule = {
type: 'qualified-rule',
prelude: [],
block: undefined,
};
let inputToken: InputToken;
while ((inputToken = this.consumeAToken())) {
if (inputToken === '{') {
qualifiedRule.block = this.consumeASimpleBlock(inputToken);
return qualifiedRule;
} else if ((<InputTokenObject>inputToken).type === TokenObjectType.simpleBlock) {
const simpleBlock: SimpleBlock = <SimpleBlock>inputToken;
if (simpleBlock.associatedToken === '{') {
qualifiedRule.block = simpleBlock;
return qualifiedRule;
}
}
this.reconsumeTheCurrentInputToken(inputToken);
const componentValue = this.consumeAComponentValue();
if (componentValue) {
qualifiedRule.prelude.push(componentValue);
}
}
// TODO: This is a parse error, log parse errors!
return null;
}
/**
* 5.4.6. Consume a component value
* https://www.w3.org/TR/css-syntax-3/#consume-a-component-value
*/
private consumeAComponentValue(): InputToken {
// const inputToken = this.consumeAToken();
const inputToken = this.consumeAToken();
switch (inputToken) {
case '{':
case '[':
case '(':
this.nextInputCodePointIndex++;
return this.consumeASimpleBlock(inputToken);
}
if (typeof inputToken === 'object' && inputToken.type === TokenObjectType.functionToken) {
return this.consumeAFunction((<FunctionInputToken>inputToken).name);
}
return inputToken;
}
/**
* 5.4.7. Consume a simple block
* https://www.w3.org/TR/css-syntax-3/#consume-a-simple-block
*/
private consumeASimpleBlock(associatedToken: InputToken): SimpleBlock {
const endianToken: ']' | '}' | ')' = {
'[': ']',
'{': '}',
'(': ')',
}[<any>associatedToken];
const start = this.nextInputCodePointIndex - 1;
const block: SimpleBlock = {
type: TokenObjectType.simpleBlock,
text: undefined,
associatedToken,
values: [],
};
let nextInputToken;
while ((nextInputToken = this.text[this.nextInputCodePointIndex])) {
if (nextInputToken === endianToken) {
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
block.text = this.text.substring(start, end);
return block;
}
const value = this.consumeAComponentValue();
if (value) {
block.values.push(value);
}
}
block.text = this.text.substring(start);
return block;
}
/**
* 5.4.8. Consume a function
* https://www.w3.org/TR/css-syntax-3/#consume-a-function
*/
private consumeAFunction(name: string): InputToken {
const start = this.nextInputCodePointIndex;
const funcToken: FunctionToken = {
type: TokenObjectType.function,
name,
text: undefined,
components: [],
};
do {
if (this.nextInputCodePointIndex >= this.text.length) {
funcToken.text = name + '(' + this.text.substring(start);
return funcToken;
}
const nextInputToken = this.text[this.nextInputCodePointIndex];
switch (nextInputToken) {
case ')': {
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
funcToken.text = name + '(' + this.text.substring(start, end);
return funcToken;
}
default: {
const component = this.consumeAComponentValue();
if (component) {
funcToken.components.push(component);
}
}
// TODO: Else we won't advance
}
} while (true);
}
} | the_stack |
import { ClassType, getObjectKeysSize, isArray } from '@deepkit/core';
import { AppModule } from '@deepkit/app';
import { http, HttpBody, httpClass, HttpQueries, JSONResponse } from '@deepkit/http';
import { Database, DatabaseRegistry, Query, UniqueConstraintFailure } from '@deepkit/orm';
import { InlineRuntimeType, Maximum, Positive, ReflectionClass, ReflectionKind, TypeUnion, ValidationError } from '@deepkit/type';
function applySelect(query: Query<any>, select: string[] | string): Query<any> {
const names: string[] = isArray(select) ? select.map(v => v.trim()) : select.replace(/\s+/g, '').split(',');
try {
return query.select(...names);
} catch (error: any) {
throw ValidationError.from([{ message: String(error.message), path: 'select', code: 'invalid_select' }]);
}
}
function applyJoins(query: Query<any>, joins: { [name: string]: string }): Query<any> {
for (const [field, projection] of Object.entries(joins)) {
if (!query.classSchema.hasProperty(field)) throw new Error(`Join '${field}' does not exist`);
let join = query.useJoinWith(field);
if (projection.length && projection !== '*') {
join = join.select(...projection.split(','));
}
query = join.end();
}
return query;
}
interface AutoCrudOptions {
/**
* To limit the route generation to a subset of operations, specify an array of
* 'create' | 'read' | 'readMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany'.
*
* ```typescript
* {limitOperations: ['create', 'read', 'readMany']}
* ```
*/
limitOperations?: ('create' | 'read' | 'readMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany')[];
/**
* Defaults to the primary key.
* If you have an additional unique field, you can specify here its name.
*/
identifier?: string;
/**
* Per default all fields are selectable in list/get routes.
*
* Specify each field to limit the selection.
*/
selectableFields?: string[];
/**
* Per default all fields are sortable in list/get routes.
*
* Specify each field to limit the selection.
*/
sortFields?: string[];
/**
* Per default the identifier/primary key can not be changed.
*
* Set this to true to allow it.
*/
identifierChangeable?: true;
/**
* Per default all joins are selectable in list/get routes.
*
* Specify each field to limit the selection.
*/
joins?: string[];
/**
* Per default max is 1000.
*/
maxLimit?: number;
/**
* Per default limit is 30.
*/
defaultLimit?: number;
}
function createController(schema: ReflectionClass<any>, options: AutoCrudOptions = {}): ClassType {
if (!schema.name) throw new Error(`Class ${schema.getClassName()} needs an entity name via @entity.name()`);
const joinNames: string[] = options.joins || schema.getProperties().filter(v => v.isReference() || v.isBackReference()).map(v => v.name);
const sortNames: string[] = options.sortFields || schema.getProperties().filter(v => !v.isReference() && !v.isBackReference()).map(v => v.name);
const selectNames: string[] = options.selectableFields || schema.getProperties().filter(v => !v.isReference() && !v.isBackReference()).map(v => v.name);
const joinNamesType: TypeUnion = { kind: ReflectionKind.union, types: joinNames.map(v => ({ kind: ReflectionKind.literal, literal: v })) };
const sortNamesType: TypeUnion = { kind: ReflectionKind.union, types: sortNames.map(v => ({ kind: ReflectionKind.literal, literal: v })) };
const selectNamesType: TypeUnion = { kind: ReflectionKind.union, types: selectNames.map(v => ({ kind: ReflectionKind.literal, literal: v })) };
type JoinNames = InlineRuntimeType<typeof joinNamesType>;
type SortNames = InlineRuntimeType<typeof sortNamesType>;
type SelectNames = InlineRuntimeType<typeof selectNamesType>;
//note: only shallows clone (including members shallow copy)
const selectSchema = schema.clone();
//make sure references are `PrimaryKey<T> | T`
for (const property of selectSchema.getProperties().slice()) {
if ((property.isReference() || property.isBackReference()) && !property.isArray()) {
selectSchema.removeProperty(property.name);
const foreign = property.getResolvedReflectionClass();
selectSchema.addProperty({
...property.property,
type: { kind: ReflectionKind.union, types: [foreign.getPrimary().type, property.type] }
});
}
}
type SchemaType = InlineRuntimeType<typeof selectSchema>;
const identifier = options.identifier ? schema.getProperty(options.identifier) : schema.getPrimary();
const identifierType = identifier.type;
type IdentifierType = InlineRuntimeType<typeof identifierType>
const maxLimit = options.maxLimit || 1000;
interface ListQuery {
filter?: Partial<SchemaType>;
/**
* @description List of or string of comma separated field names
*/
select?: SelectNames[] | string;
orderBy?: { [name in SortNames]?: 'asc' | 'desc' };
/**
* @description Each entry with field names, comma separated, or all with '*'.
*/
joins?: { [name in JoinNames]?: string };
offset?: number & Positive;
limit?: number & Positive & Maximum<InlineRuntimeType<typeof maxLimit>>;
}
interface GetQuery {
/**
* @description List of or string of comma separated field names.
*/
select?: SelectNames[] | string;
joins?: { [name in JoinNames]?: string };
}
interface ErrorMessage {
message: string;
}
const identifierChangeable = options && options.identifierChangeable ? true : false;
@http.controller('/entity/' + schema.name).group('crud')
class RestController {
constructor(protected registry: DatabaseRegistry) {
}
protected getDatabase(): Database {
return this.registry.getDatabaseForEntity(schema);
}
@http.GET('')
.description(`A list of ${schema.name}.`)
.response<SchemaType[]>(200, `List of ${schema.name}.`)
.response<ValidationError>(400, `When parameter validation failed.`)
async readMany(listQuery: HttpQueries<ListQuery>) {
listQuery.limit = Math.min(options.maxLimit || 1000, listQuery.limit || options.defaultLimit || 30);
let query = this.getDatabase().query(schema);
if (listQuery.joins) query = applyJoins(query, listQuery.joins as any);
if (listQuery.select) query = applySelect(query, listQuery.select);
if (listQuery.orderBy && getObjectKeysSize(listQuery.orderBy) > 0) {
for (const field of Object.keys(listQuery.orderBy)) {
if (!schema.hasProperty(field)) throw new Error(`Can not order by '${field}' since it does not exist.`);
}
query.model.sort = listQuery.orderBy;
}
return await query
.filter(listQuery.filter)
.limit(listQuery.limit ? listQuery.limit : undefined)
.skip(listQuery.offset)
.find();
}
@http.POST('')
.description(`Add a new ${schema.name}.`)
.response<SchemaType>(201, 'When successfully created.')
.response<ValidationError>(400, `When parameter validation failed`)
.response<ErrorMessage>(409, 'When unique entity already exists.')
async create(body: HttpBody<SchemaType>) {
//body is automatically validated
//is cast really necessary?
// const item = cast(body, undefined, undefined, schema.type);
const item = body;
try {
await this.getDatabase().persist(item);
} catch (e) {
if (e instanceof UniqueConstraintFailure) {
return new JSONResponse({ message: `This ${schema.name} already exists` }).status(409);
}
throw e;
}
return new JSONResponse(item).status(201);
}
@http.DELETE(':' + identifier.name)
.description(`Delete a single ${schema.name}.`)
.response<ValidationError>(400, `When parameter validation failed`)
.response<{ deleted: number }>(200, `When deletion was successful`)
async delete(id: IdentifierType) {
const result = await this.getDatabase().query(schema).filter({ [identifier.name]: id }).deleteOne();
return { deleted: result.modified };
}
@http.GET(':' + identifier.name)
.description(`Get a single ${schema.name}.`)
.response<SchemaType>(200, `When ${schema.name} was found.`)
.response<ValidationError>(400, `When parameter validation failed`)
.response<ErrorMessage>(404, `When ${schema.name} was not found.`)
async read(
id: IdentifierType,
options: HttpQueries<GetQuery>
) {
let query = this.getDatabase().query(schema).filter({ [identifier.name]: id });
if (options.select) query = applySelect(query, options.select);
if (options.joins) query = applyJoins(query, options.joins as any);
const item = await query.findOneOrUndefined();
if (item) return item;
return new JSONResponse({ message: `${schema.name} not found` }).status(404);
}
@http.PUT(':' + identifier.name)
.description(`Update a single ${schema.name}.`)
.response<SchemaType>(200, `When ${schema.name} was successfully updated.`)
.response<ValidationError>(400, `When parameter validation failed`)
.response<ErrorMessage>(404, `When ${schema.name} was not found.`)
async update(
id: IdentifierType,
body: Partial<SchemaType>,
) {
let query = this.getDatabase().query(schema).filter({ [identifier.name]: id });
const item = await query.findOneOrUndefined();
if (!item) return new JSONResponse({ message: `${schema.name} not found` }).status(404);
if (!identifierChangeable && identifier.name in body) delete body[identifier.name];
Object.assign(item, body);
await this.getDatabase().persist(item);
return item;
}
}
Object.defineProperty(RestController, 'name', { value: 'RestController' + schema.getClassName() });
if (options.limitOperations) {
const data = httpClass._fetch(RestController);
if (!data) throw new Error('httpClass has no RestController');
for (const action of data.actions) {
if (!options.limitOperations.includes(action.methodName as any)) {
data.removeAction(action.methodName);
}
}
}
return RestController;
}
export class CrudAppModule<T> extends AppModule<T> {
}
/**
* Create a module that provides CRUD routes for given entities.
*/
export function createCrudRoutes(schemas: (ClassType | ReflectionClass<any>)[], options: AutoCrudOptions = {}) {
const controllers = schemas.map(v => ReflectionClass.from(v)).map(v => createController(v, options));
return new CrudAppModule({
controllers: controllers
}, 'autoCrud');
} | the_stack |
import { Injectable } from '@angular/core';
import { LoadingController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { IAccount } from '../models/account.model';
import * as firebase from 'firebase';
import * as moment from 'moment';
@Injectable()
export class AuthService {
private authState;
private userauth;
private userdata;
private housedata;
private profilepicdata;
private housepicdata;
private loading: any;
public user;
public storageLang: string;
public storageTouchid: boolean = false;
public storageEmail: string;
public storagePwd: string;
public referrer: string;
public pwdNotes: string;
pages: Array<{id: string, title: string, component: any, icon: string, color: string}>;
constructor(
public storage: Storage,
public afAuth: AngularFireAuth,
public db: AngularFireDatabase,
public loadingCtrl: LoadingController) {
this.authState = afAuth.authState;
this.userdata = firebase.database().ref('/users/');
this.housedata = firebase.database().ref('/houses/');
this.profilepicdata = firebase.storage().ref().child('/profilepics/');
this.housepicdata = firebase.storage().ref().child('/housepics/');
//
// Load default forms
//
this.pages = [
{id: '1', title: '', component: '', icon: 'fa-lock', color: 'cf-fa-color1'},
{id: '2', title: '', component: '', icon: 'fa-id-card-o', color: 'cf-fa-color2'},
{id: '3', title: '', component: '', icon: 'fa-credit-card', color: 'cf-fa-color3'},
{id: '4', title: '', component: '',icon: 'fa-university', color: 'cf-fa-color4'}
/*{id: '5', title: '', component: '', icon: 'fa-umbrella', color: 'cf-fa-color5'}*/
];
}
get authenticated(): boolean {
return this.authState !== null;
}
signInWithEmail(credentials): firebase.Promise<any> {
return new Promise((resolve: () => void, reject: (reason: Error) => void) => {
this.afAuth.auth.signInWithEmailAndPassword(credentials.email, credentials.password)
.then((authData) => {
this.userauth = authData;
this.getUserData();
resolve();
}).catch((error) => {
reject(error);
});
});
}
signUpWithEmail(credentials): firebase.Promise<any> {
return new Promise((resolve: () => void, reject: (reason: Error) => void) => {
this.afAuth.auth.createUserWithEmailAndPassword(credentials.email, credentials.password)
.then((authData) => {
this.userauth = authData;
this.user = credentials;
this.createInitialSetup();
resolve();
}).catch((error) => {
reject(error);
});
});
}
signOut(): void {
this.authState = null;
this.user = null;
this.userauth = null;
this.userdata = null;
this.housedata = null;
}
displayName(): string {
if (this.authState != null) {
return this.authState.facebook.displayName;
} else {
return '';
}
}
getUserEmail(): string {
let user = firebase.auth().currentUser;
return user.email;
}
LoadingControllerShow() {
this.loading = this.loadingCtrl.create({
spinner: 'ios',
content: 'Please wait...',
});
this.loading.present();
}
LoadingControllerDismiss() {
this.loading.dismiss();
}
storageSetLanguage(lang) {
this.storageLang = lang;
this.storage.set('option0', lang);
}
storageSet(isenabled, pwd, email) {
this.storageTouchid = isenabled;
this.storagePwd = pwd;
this.storageEmail = email;
this.storage.set('ml1', isenabled);
this.storage.set('ml2', pwd);
this.storage.set('ml3', email);
}
storageSetEmail(email) {
this.storageEmail = email;
this.storage.set('ml3', email);
}
storageClean() {
this.storageTouchid = false;
this.storagePwd = '';
this.storageEmail = '';
this.storage.set('ml1', false);
this.storage.set('ml2', '');
this.storage.set('ml3', '');
}
RandomHouseCode() {
return Math.floor((Math.random() * 100000000) + 100);
}
//
// SING IN - CREATE USER
//-----------------------------------------------------------------------
createInitialSetup() {
this.createUserProfile();
this.createHouse();
this.createDefaultAccountTypes();
this.createDefaultCategoriesIncome();
this.createDefaultCategoriesExpense();
this.createDefaultPayees();
}
createUserProfile() {
// Set basic user profile defaults
var profile = {
datecreated: firebase.database['ServerValue']['TIMESTAMP'],
defaultbalance: 'Current',
defaultdate: 'None',
email: this.user.email,
enabletouchid: 'false',
fullname: this.user.fullname,
nickname: this.user.fullname,
housename: 'My House',
housenumber: this.RandomHouseCode(),
profilepic: 'http://www.gravatar.com/avatar?d=mm&s=140',
accounttypescount: '6',
paymentplan: 'Free'
};
this.user.defaultbalance = profile.defaultbalance;
this.user.defaultdate = profile.defaultdate;
this.user.enabletouchid = profile.enabletouchid;
this.user.profilepic = profile.profilepic;
// Save user profile
this.userdata.child(this.userauth.uid).update(profile);
}
createHouse() {
// Set basic house defaults
var housemember = {
isadmin: true,
createdby: this.user.email,
dateCreated: firebase.database['ServerValue']['TIMESTAMP'],
};
// Create node under houses and get the key
this.user.houseid = this.housedata.push().key;
// Save key into the user->houseid node
this.userdata.child(this.userauth.uid).update({houseid : this.user.houseid});
// Add member to housemembers node under Houses
this.housedata.child(this.user.houseid + "/housemembers/" + this.userauth.uid).update(housemember);
}
createDefaultAccountTypes() {
// default account types
var refTypes = this.housedata.child(this.user.houseid + "/accounttypes/");
refTypes.push({ name: 'Checking', icon: 'ios-cash-outline' });
refTypes.push({ name: 'Savings', icon: 'ios-cash-outline' });
refTypes.push({ name: 'Credit Card', icon: 'ios-cash-outline' });
refTypes.push({ name: 'Debit Card', icon: 'ios-cash-outline' });
refTypes.push({ name: 'Investment', icon: 'ios-cash-outline' });
refTypes.push({ name: 'Brokerage', icon: 'ios-cash-outline' });
}
createDefaultCategoriesIncome() {
// default income categories
var refCatIncome = this.housedata.child(this.user.houseid + "/categories/Income");
refCatIncome.push({ categoryname: 'Income', categoryparent: '', categorysort: 'Income', categorytype: 'Income' });
refCatIncome.push({ categoryname: 'Beginning Balance', categoryparent: 'Income', categorysort: 'Income:Beginning Balance', categorytype: 'Income' });
}
createDefaultCategoriesExpense() {
// default expense categories
var refCatExpense = this.housedata.child(this.user.houseid + "/categories/Expense");
refCatExpense.push({ categoryname: 'Auto', categoryparent: '', categorysort: 'Auto', categorytype: 'Expense' });
refCatExpense.push({ categoryname: 'Gasoline', categoryparent: 'Auto', categorysort: 'Auto:Gas', categorytype: 'Expense' });
refCatExpense.push({ categoryname: 'Car Payment', categoryparent: 'Auto', categorysort: 'Auto:Car Payment', categorytype: 'Expense' });
}
createDefaultPayees() {
// default payees
var refPayee = this.housedata.child(this.user.houseid + "/payees");
refPayee.push({ lastamount: '', lastcategory: '', lastcategoryid: '', payeename: 'Beginning Balance' });
}
//
// DEFAULT GLOBAL FORMS
//-----------------------------------------------------------------------
getDefaultForms() {
return this.pages;
}
searchForms(nameKey) {
this.searchArray(nameKey, this.pages);
}
searchArray(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
//
// PERSONAL PROFILE
//-----------------------------------------------------------------------
getUserData() {
const thisuser$ : FirebaseObjectObservable<any> = this.db.object('/users/' + this.userauth.uid);
thisuser$.subscribe((val) => {
this.user = val;
});
}
updateName(newname: string) {
this.userdata.child(this.userauth.uid).update({'fullname' : newname});
}
updateEmail(newEmail: string) {
return new Promise((resolve: () => void, reject: (reason: Error) => void) => {
let user = firebase.auth().currentUser;
user.updateEmail(newEmail)
.then(function() {
this.user.email = newEmail;
this.updateEmailNode(newEmail);
resolve();
}).catch(error => {
reject(error);
});
});
}
updatePassword(newPassword: string) {
return new Promise((resolve: () => void, reject: (reason: Error) => void) => {
let user = firebase.auth().currentUser;
user.updatePassword(newPassword)
.then(function() {
resolve();
}).catch(function(error) {
reject(error);
});
});
}
deleteData() {
//
// Delete ALL user data
this.housedata.child(this.user.houseid).remove();
this.userdata.child(firebase.auth().currentUser.uid).remove();
}
deleteUser() {
return new Promise((resolve: () => void, reject: (reason: Error) => void) => {
let user = firebase.auth().currentUser;
user.delete()
.then(function() {
resolve();
}).catch(function(error) {
reject(error);
});
});
}
saveProfilePicture(pic) {
this.profilepicdata.child(firebase.auth().currentUser.uid).child('profilepicture.png')
.putString(pic, 'base64', {contentType: 'image/png'}).then((savedpicture) => {
this.userdata.child(firebase.auth().currentUser.uid).update({'profilepic' : savedpicture.downloadURL});
});
}
savePhoto(pic, source, key) {
let photoname = moment().valueOf() + '.png';
switch (source) {
case 'DriverLicensePage': {
this.housepicdata.child(firebase.auth().currentUser.uid + '/driverlicensephotos/').child(photoname)
.putString(pic, 'base64', {contentType: 'image/png'}).then((savedphoto) => {
this.housedata.child(this.user.houseid + '/driverlicenses/' + key + '/photos/').push({'photourl' : savedphoto.downloadURL});
});
break;
}
case 'CreditCardPage': {
this.housepicdata.child(firebase.auth().currentUser.uid + '/creditcardphotos/').child(photoname)
.putString(pic, 'base64', {contentType: 'image/png'}).then((savedphoto) => {
this.housedata.child(this.user.houseid + '/creditcards/' + key + 'photos/').push({'photourl' : savedphoto.downloadURL});
});
break;
}
}
}
updateEmailNode(newemail) {
this.userdata.child(this.userauth.uid).update({'email' : newemail});
}
updateDefaultBalance(newdefaultbalance: string) {
this.userdata.child(this.userauth.uid).update({'defaultbalance' : newdefaultbalance});
}
updateDefaultDate(newdefaultdate: string) {
this.userdata.child(this.userauth.uid).update({'defaultdate' : newdefaultdate});
}
//
// ACCOUNT TYPES
//-----------------------------------------------------------------------
getAccountTypes(): FirebaseListObservable<any[]> {
return this.db.list('/houses/' + this.user.houseid + '/accounttypes');
}
addAccountType(item) {
this.housedata.child(this.user.houseid + "/accounttypes/").push({ name: item.name, icon: item.icon });
this.updateAccountTypesCounter('add');
}
deleteAccountType(item) {
this.housedata.child(this.user.houseid + '/accounttypes/' + item.$key).remove();
this.updateAccountTypesCounter('delete');
}
updateAccountType(item) {
this.housedata.child(this.user.houseid + '/accounttypes/' + item.$key).update({ 'name' : item.name, 'icon' : item.icon });
}
updateAccountTypesCounter(operation: string) {
var count = parseInt(this.user.accounttypescount);
if (operation === 'add') {
count++;
} else {
count--;
}
this.userdata.child(this.userauth.uid).update({'accounttypescount' : count});
}
//
// ACCOUNTS
//-----------------------------------------------------------------------
getAllAccounts() {
return this.housedata.child(this.user.houseid + '/accounts').orderByChild('accounttype');
}
getAccounts(myChild, mySubject): FirebaseListObservable<any> {
return this.db.list('/houses/' + this.user.houseid + '/accounts/', {
query: {
orderByChild: myChild,
equalTo: mySubject
}
}).map((array) => array.reverse()) as FirebaseListObservable<any[]>;
}
getAccount(key) {
return this.housedata.child(this.user.houseid + '/accounts/' + key);
}
addAccount(item) {
this.housedata.child(this.user.houseid + "/accounts/").push(item);
}
updateAccount(item, key) {
this.housedata.child(this.user.houseid + '/accounts/' + key).update({
'accountname' : item.accountname,
'accounttype' : item.accounttype,
'dateopen' : item.dateopen });
}
deleteAccount(account) {
this.housedata.child(this.user.houseid + '/accounts/' + account.$key).remove();
}
//
// TRANSACTIONS
//-----------------------------------------------------------------------
getAllTransactionsByDate(account) {
return this.housedata.child(this.user.houseid + '/transactions/' + account.$key).orderByChild('date');
}
getTransactionsByDateCustom(account, limit) {
//return this.housedata.child(this.user.houseid + '/transactions/' + account.$key).orderByChild('date').limitToLast(50);
return this.housedata.child(this.user.houseid + '/transactions/' + account.$key).orderByChild('date').limitToLast(limit);
}
// Use Angularfire2
getTransactionsByDate(account): FirebaseListObservable<any> {
return this.db.list('/houses/' + this.user.houseid + '/transactions/' + account.$key, {
query: {
orderByChild: 'date'
}
}).map((array) => array.reverse()) as FirebaseListObservable<any[]>;
}
getFilteredTransactions(account, myChild, mySubject): FirebaseListObservable<any> {
return this.db.list('/houses/' + this.user.houseid + '/transactions/' + account.$key, {
query: {
orderByChild: myChild,
equalTo: mySubject
}
}).map((array) => array.reverse()) as FirebaseListObservable<any[]>;
}
getAllTransactionsByDateAF2(account): FirebaseListObservable<any> {
return this.db.list('/houses/' + this.user.houseid + '/transactions/' + account.$key, { preserveSnapshot: true });
}
addTransaction(transaction, account) {
this.housedata.child(this.user.houseid + '/transactions/' + account.$key + "/").push(transaction.toString());
}
updateTransaction(transaction, account) {
this.housedata.child(this.user.houseid + '/transactions/' + account.$key + "/" + transaction.$key).update(transaction.toString());
}
deleteTransaction(transaction) {
//this.housedata.child(this.user.houseid + '/accounts/' + account.$key).remove();
}
updateAccountWithTotals(account: IAccount) {
// Update account with totals
var refAccount = this.housedata.child(this.user.houseid + '/accounts/' + account.$key);
refAccount.update({
'balancecleared' : account.balancecleared,
'balancecurrent' : account.balancecurrent,
'balancetoday' : account.balancetoday,
'totaltransactions' : account.totaltransactions,
'totalclearedtransactions' : account.totalclearedtransactions,
'totalpendingtransactions' : account.totalpendingtransactions
});
}
//
// CATEGORIES
//-----------------------------------------------------------------------
getAllCategories() {
return this.db.list('/houses/' + this.user.houseid + '/categories', { preserveSnapshot: true});
}
getIncomeCategories() {
return this.housedata.child(this.user.houseid + '/categories/Income').orderByChild('categorysort');
}
getExpenseCategories() {
return this.housedata.child(this.user.houseid + '/categories/Expense').orderByChild('categorysort');
}
getIncomeCategory(key) {
return this.housedata.child(this.user.houseid + '/categories/Income/' + key);
}
getExpenseCategory(key) {
return this.housedata.child(this.user.houseid + '/categories/Expense/' + key);
}
getParentCategories(type) {
return this.housedata.child(this.user.houseid + '/categories/' + type).orderByChild('categorysort');
}
addCategory(item) {
this.housedata.child(this.user.houseid + "/categories/" + item.categorytype).push(item);
}
updateCategory(item, key) {
this.housedata.child(this.user.houseid + '/categories/' + item.categorytype + '/' + key).update({
'categoryname' : item.categoryname,
'categorytype' : item.categorytype,
'categoryparent' : item.categoryparent,
'categorysort' : item.categorysort
});
}
deleteCategory(category) {
this.housedata.child(this.user.houseid + '/categories/' + category.categorytype + '/' + category.$key).remove();
}
//
// PAYEES
//-----------------------------------------------------------------------
getAllPayees() {
return this.housedata.child(this.user.houseid + '/payees').orderByChild('payeesort');
}
getPayee(key) {
return this.housedata.child(this.user.houseid + '/payees/' + key);
}
addPayee(item) {
this.housedata.child(this.user.houseid + "/payees").push(item);
}
updatePayee(item, key) {
this.housedata.child(this.user.houseid + '/payees/' + key).update({ 'payeename': item.payeename, 'payeesort': item.payeesort });
}
deletePayee(payee) {
this.housedata.child(this.user.houseid + '/payees/' + payee.$key).remove();
}
//
// MISCELANEOUS
//-----------------------------------------------------------------------
handleData(snapshot)
{
try {
// Firebase stores everything as an object, but we want an array.
var keys = Object.keys(snapshot.val);
console.log('keys: ', keys, snapshot.val);
// variable to store the todos added
var data = [];
// Loop through the keys and push the todos into an array
for( var i = 0; i < keys.length; ++i)
{
data.push(snapshot.val()[keys[i]]);
}
console.log(data);
}
catch (error) {
console.log('catching', error);
}
}
/*
// Find an item in the array
//http://stackoverflow.com/questions/2713599/how-do-i-select-an-item-out-of-a-javascript-array-when-i-only-know-a-value-for-o
find_in_array(arr, name, value) {
for (var i = 0, len = arr.length; i<len; i++) {
if (name in arr[i] && arr[i][name] == value) return i;
};
return false;
}
var id = find_in_array(measurements.page[0].line, 'lineid', 22);
*/
//
// DATA MAINTENANCE
//-----------------------------------------------------------------------
houseMember() {
}
upgradeData() {
this.copyAccounts();
this.copyAccountTypes();
this.copyCategories();
this.copyPayees();
this.copyTransactions();
this.LoadingControllerDismiss();
}
copyAccounts() {
this.copyFbRecord(this.housedata.child(this.user.houseid + '/memberaccounts'), this.housedata.child(this.user.houseid + '/accounts'));
}
copyAccountTypes() {
this.copyFbRecord(this.housedata.child(this.user.houseid + '/memberaccounttypes'), this.housedata.child(this.user.houseid + '/accounttypes'));
}
copyCategories() {
this.copyFbRecord(this.housedata.child(this.user.houseid + '/membercategories'), this.housedata.child(this.user.houseid + '/categories'));
}
copyPayees() {
this.copyFbRecord(this.housedata.child(this.user.houseid + '/memberpayees'), this.housedata.child(this.user.houseid + '/payees'));
}
copyTransactions() {
this.copyFbRecord(this.housedata.child(this.user.houseid + '/membertransactions'), this.housedata.child(this.user.houseid + '/transactions'));
}
// Move or copy a Firebase path to a new location
// https://gist.github.com/katowulf/6099042
copyFbRecord(oldRef, newRef) {
oldRef.once('value', function(snap) {
newRef.set( snap.val(), function(error) {
if( error && typeof(console) !== 'undefined' && console.error ) { console.error(error); }
});
});
}
moveFbRecord(oldRef, newRef) {
oldRef.once('value', function(snap) {
newRef.set( snap.val(), function(error) {
if( !error ) { oldRef.remove(); }
else if( typeof(console) !== 'undefined' && console.error ) { console.error(error); }
});
});
}
syncAccountBalances(account) {
var totalTransactions = 0;
var totalClearedTransactions = 0;
var runningBal = 0;
var clearedBal = 0;
var todayBal = 0;
var ref = this.housedata.child(this.user.houseid + '/transactions/' + account.$key);
var query = ref.orderByChild('date');
query.once('value', (transactions) => {
transactions.forEach( snapshot => {
var transaction = snapshot.val();
//
// Handle Balances
//
totalTransactions++;
transaction.ClearedClass = '';
if (transaction.iscleared === true) {
transaction.ClearedClass = 'transactionIsCleared';
totalClearedTransactions++;
if (transaction.type === "Income") {
if (!isNaN(transaction.amount)) {
clearedBal = clearedBal + parseFloat(transaction.amount);
}
} else if (transaction.type === "Expense") {
if (!isNaN(transaction.amount)) {
clearedBal = clearedBal - parseFloat(transaction.amount);
}
}
transaction.clearedBal = clearedBal.toFixed(2);
}
if (transaction.type === "Income") {
if (!isNaN(transaction.amount)) {
runningBal = runningBal + parseFloat(transaction.amount);
transaction.runningbal = runningBal.toFixed(2);
}
} else if (transaction.type === "Expense") {
if (!isNaN(transaction.amount)) {
runningBal = runningBal - parseFloat(transaction.amount);
transaction.runningbal = runningBal.toFixed(2);
}
}
//
// Get today's balance
//
var tranDate = moment(transaction.date)
var now = moment();
if (tranDate <= now) {
todayBal = runningBal;
}
//
// Update this transaction
//
ref.child(snapshot.key).update({
runningbal : runningBal.toFixed(2),
clearedBal : clearedBal.toFixed(2),
});
});
var pendingTransactions = totalTransactions - totalClearedTransactions;
// Update account with totals
var refAccount = this.housedata.child(this.user.houseid + '/accounts/' + account.$key);
refAccount.update({
'balancecleared' : clearedBal.toFixed(2),
'balancecurrent' : runningBal.toFixed(2),
'balancetoday' : todayBal.toFixed(2),
'totaltransactions' : totalTransactions.toFixed(0),
'totalclearedtransactions' : totalClearedTransactions.toFixed(0),
'totalpendingtransactions' : pendingTransactions.toFixed(0)
});
});
this.LoadingControllerDismiss();
return false;
}
upgradeAccountData(account) {
var refmeta = this.housedata.child(this.user.houseid + '/transactionsmeta/' + account.$key);
// First, clean the meta data node
refmeta.remove();
var ref = this.housedata.child(this.user.houseid + '/transactions/' + account.$key);
var query = ref.orderByChild('date');
query.once('value', (transactions) => {
transactions.forEach( snapshot => {
let transaction = snapshot.val();
let tempTransaction = {
ClearedClass : '',
accountFrom : transaction.accountFrom,
accountFromId : transaction.accountFromId,
accountTo : transaction.accountTo,
accountToId : transaction.accountToId,
addedby : transaction.addedby,
amount : transaction.amount,
category : transaction.category,
categoryid : transaction.categoryid,
clearedBal : transaction.clearedBal,
date : transaction.date,
iscleared : transaction.iscleared,
isphoto : '',
isrecurring : '',
istransfer : transaction.istransfer,
note : '',
notes : '',
payee : transaction.payee,
payeeid : transaction.payeeid,
photo: transaction.photo,
runningbal: transaction.runningbal,
runningbalance : null,
type : transaction.type,
typedisplay : transaction.typedisplay
};
// Some transactions are missing nodes
// so make sure you add them
if (transaction.isrecurring != undefined) {
tempTransaction.isrecurring = transaction.isrecurring;
}
if (transaction.isphoto != undefined) {
tempTransaction.isphoto = transaction.isphoto;
}
if (transaction.note === undefined) {
// ignore
} else {
if (transaction.note != '') {
tempTransaction.notes = transaction.note;
}
}
// Removed unnecessary nodes
tempTransaction.ClearedClass = null;
tempTransaction.note = null;
//
// UPDATE DATA
//
ref.child(snapshot.key).update(tempTransaction);
//
//
//
// Prepare transaction metadata
let tempMeta = {
addedby : transaction.addedby,
amount : transaction.amount,
category : transaction.category,
clearedBal : transaction.clearedBal,
date : transaction.date,
iscleared : transaction.iscleared,
isphoto : '',
isrecurring : '',
istransfer : transaction.istransfer,
notes : '',
payee : transaction.payee,
runningbal: transaction.runningbal,
type : transaction.type
};
//
// UPDATE META DATA
//
refmeta.child(snapshot.key).update(tempMeta);
//
});
});
this.LoadingControllerDismiss();
}
syncCategories(account) {
//
// Get all the transactions from this account
// and verify that a category exists in the categories node
// If not, create it
//
var ref = this.housedata.child(this.user.houseid + '/transactions/' + account.$key);
var query = ref.orderByChild('date');
var refIncome = this.housedata.child(this.user.houseid + '/categories/Income');
var refExpense = this.housedata.child(this.user.houseid + '/categories/Expense');
var catsort: any;
query.once('value', (transactions) => {
transactions.forEach( snapshot => {
var transaction = snapshot.val();
//
// Handle categories
//
if (transaction.type === 'Income') {
refIncome.child(transaction.categoryid).once('value', (snapshot) => {
var cat = snapshot.val();
if (cat === null) {
catsort = transaction.category.toUpperCase();
this.housedata.child(this.user.houseid + '/categories/Income/' + transaction.categoryid).update({ 'categoryname' : transaction.category, 'categorytype' : 'Income', 'categoryparent' : '', 'categorysort' : catsort });
}
});
} else if (transaction.type === 'Expense') {
refExpense.child(transaction.categoryid).once('value', (snapshot) => {
var cat = snapshot.val();
if (cat === null) {
catsort = transaction.category.toUpperCase();
this.housedata.child(this.user.houseid + '/categories/Expense/' + transaction.categoryid).update({ 'categoryname' : transaction.category, 'categorytype' : 'Income', 'categoryparent' : '', 'categorysort' : catsort });
}
});
} else {
console.log('missing category');
}
});
});
this.LoadingControllerDismiss();
}
syncPayees(account) {
//
// Get all the transactions from this account
// and verify that a payee exists in the payees node
// If not, create it
//
var ref = this.housedata.child(this.user.houseid + '/transactions/' + account.$key);
var query = ref.orderByChild('date');
var refPayee = this.housedata.child(this.user.houseid + '/payees');
query.once('value', (transactions) => {
transactions.forEach( snapshot => {
var transaction = snapshot.val();
//
// Handle categories
//
refPayee.child(transaction.payeeid).once('value', (snapshot) => {
var payee = snapshot.val();
if (payee === null) {
this.housedata.child(this.user.houseid + '/payees/' + transaction.payeeid).update({ 'payeename' : transaction.payee });
}
});
});
});
this.LoadingControllerDismiss();
}
syncPhotos(account) {
//
// Get all the transactions from this account
// and if a photo exists move it to fb storage
//
var ref = this.housedata.child(this.user.houseid + '/transactions/' + account.$key);
var query = ref.orderByChild('date');
//this.transactionphoto = firebase.storage().ref('/profilepics/');
query.once('value', (transactions) => {
transactions.forEach( snapshot => {
var transaction = snapshot.val();
//
// Handle photos
//
if (transaction.photo != '') {
console.log(snapshot.key, transaction);
}
});
});
this.LoadingControllerDismiss();
}
} | the_stack |
import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { ActivatedRoute, ActivatedRouteSnapshot, convertToParamMap } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { AssessmentInstructionsComponent } from 'app/assessment/assessment-instructions/assessment-instructions/assessment-instructions.component';
import { ExampleSubmission } from 'app/entities/example-submission.model';
import { Feedback, FeedbackCorrectionErrorType } from 'app/entities/feedback.model';
import { Result } from 'app/entities/result.model';
import { TextBlock } from 'app/entities/text-block.model';
import { TextExercise } from 'app/entities/text-exercise.model';
import { TextSubmission } from 'app/entities/text-submission.model';
import { TutorParticipationService } from 'app/exercises/shared/dashboards/tutor/tutor-participation.service';
import { ExampleSubmissionService } from 'app/exercises/shared/example-submission/example-submission.service';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { TextAssessmentAreaComponent } from 'app/exercises/text/assess/text-assessment-area/text-assessment-area.component';
import { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';
import { State } from 'app/exercises/text/manage/example-text-submission/example-text-submission-state.model';
import { ExampleTextSubmissionComponent } from 'app/exercises/text/manage/example-text-submission/example-text-submission.component';
import { AlertComponent } from 'app/shared/alert/alert.component';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { ResizeableContainerComponent } from 'app/shared/resizeable-container/resizeable-container.component';
import { ScoreDisplayComponent } from 'app/shared/score-display/score-display.component';
import { MockComponent, MockPipe, MockProvider } from 'ng-mocks';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { of, throwError } from 'rxjs';
import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';
import { ArtemisTestModule } from '../../test.module';
import { TextBlockRef } from 'app/entities/text-block-ref.model';
describe('ExampleTextSubmissionComponent', () => {
let fixture: ComponentFixture<ExampleTextSubmissionComponent>;
let comp: ExampleTextSubmissionComponent;
let exerciseService: ExerciseService;
let exampleSubmissionService: ExampleSubmissionService;
let assessmentsService: TextAssessmentService;
const EXERCISE_ID = 1;
const EXAMPLE_SUBMISSION_ID = 2;
const SUBMISSION_ID = 3;
let exercise: TextExercise;
let exampleSubmission: ExampleSubmission;
let result: Result;
let submission: TextSubmission;
let activatedRouteSnapshot: ActivatedRouteSnapshot;
beforeEach(() => {
const route: ActivatedRoute = {
snapshot: {
paramMap: convertToParamMap({}),
queryParamMap: convertToParamMap({}),
},
} as any;
TestBed.configureTestingModule({
imports: [ArtemisTestModule, FormsModule],
declarations: [
ExampleTextSubmissionComponent,
MockComponent(ResizeableContainerComponent),
MockComponent(ScoreDisplayComponent),
MockComponent(TextAssessmentAreaComponent),
MockComponent(AssessmentInstructionsComponent),
MockPipe(ArtemisTranslatePipe),
MockComponent(AlertComponent),
],
providers: [
{
provide: ActivatedRoute,
useValue: route,
},
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
MockProvider(TranslateService),
],
}).compileComponents();
fixture = TestBed.createComponent(ExampleTextSubmissionComponent);
comp = fixture.componentInstance;
activatedRouteSnapshot = fixture.debugElement.injector.get(ActivatedRoute).snapshot;
exerciseService = fixture.debugElement.injector.get(ExerciseService);
exampleSubmissionService = fixture.debugElement.injector.get(ExampleSubmissionService);
assessmentsService = fixture.debugElement.injector.get(TextAssessmentService);
exercise = new TextExercise(undefined, undefined);
exercise.id = EXERCISE_ID;
exercise.title = 'Test case exercise';
exampleSubmission = new ExampleSubmission();
exampleSubmission.id = EXAMPLE_SUBMISSION_ID;
result = new Result();
submission = result.submission = exampleSubmission.submission = new TextSubmission();
submission.id = SUBMISSION_ID;
});
it('should fetch example submission with result for existing example submission and switch to edit state', async () => {
// GIVEN
// @ts-ignore
activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };
jest.spyOn(exerciseService, 'find').mockReturnValue(httpResponse(exercise));
jest.spyOn(exampleSubmissionService, 'get').mockReturnValue(httpResponse(exampleSubmission));
jest.spyOn(assessmentsService, 'getExampleResult').mockReturnValue(of(result));
// WHEN
await comp.ngOnInit();
// THEN
expect(exerciseService.find).toHaveBeenCalledWith(EXERCISE_ID);
expect(exampleSubmissionService.get).toHaveBeenCalledWith(EXAMPLE_SUBMISSION_ID);
expect(assessmentsService.getExampleResult).toHaveBeenCalledWith(EXERCISE_ID, SUBMISSION_ID);
expect(comp.state.constructor.name).toEqual('EditState');
});
it('should fetch only fetch exercise for new example submission and stay in new state', async () => {
// GIVEN
// @ts-ignore
activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: 'new' };
jest.spyOn(exerciseService, 'find').mockReturnValue(httpResponse(exercise));
jest.spyOn(exampleSubmissionService, 'get').mockImplementation();
jest.spyOn(assessmentsService, 'getExampleResult').mockImplementation();
// WHEN
await comp.ngOnInit();
// THEN
expect(exerciseService.find).toHaveBeenCalledWith(EXERCISE_ID);
expect(exampleSubmissionService.get).toHaveBeenCalledTimes(0);
expect(assessmentsService.getExampleResult).toHaveBeenCalledTimes(0);
expect(comp.state.constructor.name).toEqual('NewState');
});
it('should switch state when starting assessment', async () => {
// GIVEN
// @ts-ignore
activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };
await comp.ngOnInit();
comp.isAtLeastInstructor = true;
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.submission = submission;
jest.spyOn(assessmentsService, 'getExampleResult').mockReturnValue(of(result));
of();
// WHEN
fixture.detectChanges();
await comp.startAssessment();
// THEN
expect(assessmentsService.getExampleResult).toHaveBeenCalledWith(EXERCISE_ID, SUBMISSION_ID);
expect(comp.state.constructor.name).toEqual('NewAssessmentState');
});
it('should save assessment', async () => {
// GIVEN
// @ts-ignore
activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };
await comp.ngOnInit();
comp.isAtLeastInstructor = true;
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.submission = submission;
const textBlock1 = new TextBlock();
textBlock1.startIndex = 0;
textBlock1.endIndex = 4;
textBlock1.setTextFromSubmission(submission);
textBlock1.computeId();
const textBlock2 = new TextBlock();
textBlock2.startIndex = 5;
textBlock2.endIndex = 9;
textBlock2.setTextFromSubmission(submission);
textBlock2.computeId();
submission.blocks = [textBlock1, textBlock2];
comp.result = result;
const feedback = Feedback.forText(textBlock1, 0, 'Test');
result.feedbacks = [feedback];
comp.state.edit();
comp.state.assess();
comp['prepareTextBlocksAndFeedbacks']();
comp.validateFeedback();
jest.spyOn(assessmentsService, 'saveExampleAssessment').mockReturnValue(httpResponse(result));
// WHEN
fixture.detectChanges();
fixture.debugElement.query(By.css('#saveNewAssessment')).nativeElement.click();
// THEN
expect(assessmentsService.saveExampleAssessment).toHaveBeenCalledWith(EXERCISE_ID, EXAMPLE_SUBMISSION_ID, [feedback], [textBlock1]);
});
it('editing submission from assessment state switches state', fakeAsync(() => {
// GIVEN
comp.isAtLeastEditor = true;
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.submission = submission;
const textBlock1 = new TextBlock();
textBlock1.startIndex = 0;
textBlock1.endIndex = 4;
textBlock1.setTextFromSubmission(submission);
textBlock1.computeId();
const textBlock2 = new TextBlock();
textBlock2.startIndex = 5;
textBlock2.endIndex = 9;
textBlock2.setTextFromSubmission(submission);
textBlock2.computeId();
submission.blocks = [textBlock1, textBlock2];
comp.result = result;
const feedback = Feedback.forText(textBlock1, 0, 'Test');
result.feedbacks = [feedback];
comp.state = State.forExistingAssessmentWithContext(comp);
comp['prepareTextBlocksAndFeedbacks']();
comp.validateFeedback();
jest.spyOn(assessmentsService, 'deleteExampleFeedback').mockReturnValue(of());
// WHEN
fixture.detectChanges();
tick();
fixture.debugElement.query(By.css('#editSampleSolution')).nativeElement.click();
tick();
// THEN
expect(comp.state.constructor.name).toEqual('EditState');
expect(assessmentsService.deleteExampleFeedback).toHaveBeenCalledWith(EXERCISE_ID, EXAMPLE_SUBMISSION_ID);
expect(comp.submission?.blocks).toBeUndefined();
expect(comp.result?.feedbacks).toBeUndefined();
expect(comp.textBlockRefs).toHaveLength(0);
expect(comp.unusedTextBlockRefs).toHaveLength(0);
}));
it('it should verify correct tutorial submission', async () => {
// GIVEN
// @ts-ignore
activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };
// @ts-ignore
activatedRouteSnapshot.queryParamMap.params = { toComplete: true };
jest.spyOn(exerciseService, 'find').mockReturnValue(httpResponse(exercise));
jest.spyOn(exampleSubmissionService, 'get').mockReturnValue(httpResponse(exampleSubmission));
const textBlock1 = new TextBlock();
textBlock1.startIndex = 0;
textBlock1.endIndex = 4;
textBlock1.setTextFromSubmission(submission);
textBlock1.computeId();
const textBlock2 = new TextBlock();
textBlock2.startIndex = 5;
textBlock2.endIndex = 9;
textBlock2.setTextFromSubmission(submission);
textBlock2.computeId();
submission.blocks = [textBlock1, textBlock2];
jest.spyOn(assessmentsService, 'getExampleResult').mockReturnValue(of(result));
await comp.ngOnInit();
comp.textBlockRefs[0].initFeedback();
comp.textBlockRefs[0].feedback!.credits = 2;
comp.validateFeedback();
const tutorParticipationService = fixture.debugElement.injector.get(TutorParticipationService);
jest.spyOn(tutorParticipationService, 'assessExampleSubmission').mockReturnValue(httpResponse(null));
// WHEN
fixture.detectChanges();
fixture.debugElement.query(By.css('#checkAssessment')).nativeElement.click();
// THEN
expect(exerciseService.find).toHaveBeenCalledWith(EXERCISE_ID);
expect(exampleSubmissionService.get).toHaveBeenCalledWith(EXAMPLE_SUBMISSION_ID);
expect(assessmentsService.getExampleResult).toHaveBeenCalledWith(EXERCISE_ID, SUBMISSION_ID);
expect(tutorParticipationService.assessExampleSubmission).toHaveBeenCalled();
});
it('when wrong tutor assessment, upon backend response should mark feedback as incorrect', fakeAsync(() => {
// GIVEN
const textBlockRefA = TextBlockRef.new();
textBlockRefA.block!.id = 'ID';
const feedbackA = new Feedback();
feedbackA.reference = textBlockRefA.block!.id;
feedbackA.detailText = 'feedbackA';
textBlockRefA.feedback = feedbackA;
const textBlockRefB = TextBlockRef.new();
const feedbackB = new Feedback();
feedbackB.detailText = 'feebbackB';
textBlockRefB.feedback = feedbackB;
comp.textBlockRefs = [textBlockRefA, textBlockRefB];
expect(feedbackA.correctionStatus).toBeUndefined;
expect(feedbackB.correctionStatus).toBeUndefined;
const tutorParticipationService = fixture.debugElement.injector.get(TutorParticipationService);
const feedbackError = {
reference: feedbackA.reference,
type: FeedbackCorrectionErrorType.INCORRECT_SCORE,
};
const errorResponse = new HttpErrorResponse({
error: { title: JSON.stringify({ errors: [feedbackError] }) },
headers: new HttpHeaders().append('x-artemisapp-error', 'error.invalid_assessment'),
status: 400,
});
jest.spyOn(tutorParticipationService, 'assessExampleSubmission').mockReturnValue(throwError(() => errorResponse));
// WHEN
comp.ngOnInit();
tick();
comp.checkAssessment();
tick();
// THEN
expect(feedbackA.correctionStatus).toEqual(FeedbackCorrectionErrorType.INCORRECT_SCORE);
expect(feedbackB.correctionStatus).toEqual('CORRECT');
}));
const httpResponse = (body: any) => of(new HttpResponse({ body }));
}); | the_stack |
import type GameSim from ".";
import getBestPenaltyResult from "./getBestPenaltyResult";
import type { PlayerGameSim, TeamNum } from "./types";
type PlayEvent =
| {
type: "k";
kickTo: number;
}
| {
type: "onsideKick";
kickTo: number;
}
| {
type: "touchbackKick";
}
| {
type: "kr";
p: PlayerGameSim;
yds: number;
}
| {
type: "onsideKickRecovery";
success: boolean;
p: PlayerGameSim;
yds: number;
}
| {
type: "krTD";
p: PlayerGameSim;
}
| {
type: "p";
p: PlayerGameSim;
yds: number;
}
| {
type: "touchbackPunt";
p: PlayerGameSim;
}
| {
type: "pr";
p: PlayerGameSim;
yds: number;
}
| {
type: "prTD";
p: PlayerGameSim;
}
| {
type: "rus";
p: PlayerGameSim;
yds: number;
}
| {
type: "rusTD";
p: PlayerGameSim;
}
| {
type: "kneel";
p: PlayerGameSim;
yds: number;
}
| {
type: "sk";
qb: PlayerGameSim;
p: PlayerGameSim;
yds: number;
}
| {
type: "dropback";
}
| {
type: "pss";
qb: PlayerGameSim;
target: PlayerGameSim;
}
| {
type: "pssCmp";
qb: PlayerGameSim;
target: PlayerGameSim;
yds: number;
}
| {
type: "pssInc";
defender: PlayerGameSim | undefined;
}
| {
type: "pssTD";
qb: PlayerGameSim;
target: PlayerGameSim;
}
| {
type: "int";
qb: PlayerGameSim;
defender: PlayerGameSim;
ydsReturn: number;
}
| {
type: "intTD";
p: PlayerGameSim;
}
| {
type: "touchbackInt";
}
| {
type: "xp";
p: PlayerGameSim;
distance: number;
made: boolean;
}
| {
type: "fg";
p: PlayerGameSim;
distance: number;
made: boolean;
late: boolean;
}
| {
type: "penalty";
p: PlayerGameSim | undefined;
automaticFirstDown: boolean;
name: string;
penYds: number;
spotYds: number | undefined; // undefined if not spot/tackOn foul
tackOn: boolean;
t: TeamNum;
}
| {
type: "fmb";
pFumbled: PlayerGameSim;
pForced: PlayerGameSim;
yds: number;
}
| {
type: "fmbRec";
pFumbled: PlayerGameSim;
pRecovered: PlayerGameSim;
lost: boolean;
yds: number;
}
| {
type: "fmbTD";
p: PlayerGameSim;
}
| {
type: "twoPointConversion";
t: TeamNum;
}
| {
type: "twoPointConversionDone";
t: TeamNum;
}
| {
type: "defSft";
p: PlayerGameSim;
}
| {
type: "possessionChange";
yds: number;
kickoff?: boolean;
}
| {
type: "tck";
tacklers: Set<PlayerGameSim>;
loss: boolean;
};
type PlayType = PlayEvent["type"];
type PlayEventPenalty = Extract<PlayEvent, { type: "penalty" }>;
type PlayEventNonPenalty = Exclude<PlayEvent, PlayEventPenalty>;
type PlayState = Pick<
GameSim,
| "down"
| "toGo"
| "scrimmage"
| "o"
| "d"
| "isClockRunning"
| "awaitingKickoff"
| "awaitingAfterSafety"
| "awaitingAfterTouchdown"
| "overtimeState"
>;
type StatChange = Parameters<GameSim["recordStat"]>;
export class State {
down: PlayState["down"];
toGo: PlayState["toGo"];
scrimmage: PlayState["scrimmage"];
o: PlayState["o"];
d: PlayState["d"];
isClockRunning: PlayState["isClockRunning"];
awaitingKickoff: PlayState["awaitingKickoff"];
awaitingAfterSafety: PlayState["awaitingAfterSafety"];
awaitingAfterTouchdown: PlayState["awaitingAfterTouchdown"];
overtimeState: PlayState["overtimeState"];
downIncremented: boolean;
firstDownLine: number;
madeLateFG: TeamNum | undefined;
missedXP: TeamNum | undefined;
numPossessionChanges: number;
pts: [number, number];
twoPointConversionTeam: TeamNum | undefined;
turnoverOnDowns: boolean;
constructor(
gameSim: PlayState,
{
downIncremented,
firstDownLine,
madeLateFG,
missedXP,
numPossessionChanges,
pts,
twoPointConversionTeam,
turnoverOnDowns,
}: {
downIncremented: boolean;
firstDownLine: number | undefined;
madeLateFG: TeamNum | undefined;
missedXP: TeamNum | undefined;
numPossessionChanges: number;
pts: [number, number];
twoPointConversionTeam: TeamNum | undefined;
turnoverOnDowns: boolean;
},
) {
this.down = gameSim.down;
this.toGo = gameSim.toGo;
this.scrimmage = gameSim.scrimmage;
this.o = gameSim.o;
this.d = gameSim.d;
this.isClockRunning = gameSim.isClockRunning;
this.awaitingKickoff = gameSim.awaitingKickoff;
this.awaitingAfterSafety = gameSim.awaitingAfterSafety;
this.awaitingAfterTouchdown = gameSim.awaitingAfterTouchdown;
this.overtimeState = gameSim.overtimeState;
this.downIncremented = downIncremented;
this.firstDownLine = firstDownLine ?? this.scrimmage + this.toGo;
this.madeLateFG = madeLateFG;
this.missedXP = missedXP;
this.numPossessionChanges = numPossessionChanges;
this.pts = pts;
this.twoPointConversionTeam = twoPointConversionTeam;
this.turnoverOnDowns = turnoverOnDowns;
}
clone() {
return new State(this, {
downIncremented: this.downIncremented,
firstDownLine: this.firstDownLine,
madeLateFG: this.madeLateFG,
missedXP: this.missedXP,
numPossessionChanges: this.numPossessionChanges,
pts: [...this.pts],
twoPointConversionTeam: this.twoPointConversionTeam,
turnoverOnDowns: this.turnoverOnDowns,
});
}
incrementDown() {
if (!this.downIncremented) {
this.down += 1;
this.downIncremented = true;
}
}
newFirstDown() {
this.down = 1;
this.toGo = Math.min(10, 100 - this.scrimmage);
this.firstDownLine = this.scrimmage + this.toGo;
}
possessionChange() {
if (this.overtimeState === "firstPossession") {
this.overtimeState = "secondPossession";
} else if (this.overtimeState === "secondPossession") {
this.overtimeState = "bothTeamsPossessed";
}
this.scrimmage = 100 - this.scrimmage;
this.o = this.o === 1 ? 0 : 1;
this.d = this.o === 1 ? 0 : 1;
this.newFirstDown();
this.isClockRunning = false;
this.numPossessionChanges += 1;
}
}
const getPts = (event: PlayEvent, twoPointConversion: boolean) => {
let pts;
if (event.type.endsWith("TD")) {
pts = twoPointConversion ? 2 : 6;
} else if (event.type === "xp" && event.made) {
pts = 1;
} else if (event.type === "fg" && event.made) {
pts = 3;
} else if (event.type === "defSft") {
pts = 2;
}
return pts;
};
type WrappedPenaltyEvent = {
event: PlayEventPenalty;
statChanges: StatChange[];
penaltyInfo: {
halfDistanceToGoal: boolean;
penYdsSigned: number;
placeOnOne: boolean;
};
};
export type WrappedPlayEvent =
| {
event: PlayEventNonPenalty;
statChanges: StatChange[];
}
| WrappedPenaltyEvent;
class Play {
g: GameSim;
events: WrappedPlayEvent[];
state: {
initial: State;
current: State;
};
penaltyRollbacks: {
type: "tackOn" | "spotOfEnforcement" | "cleanHandsChangeOfPossession";
indexEvent: number;
}[];
cleanHandsChangeOfPossessionIndexes: number[];
spotOfEnforcementIndexes: number[];
constructor(gameSim: GameSim) {
this.g = gameSim;
this.events = [];
const initialState = new State(gameSim, {
downIncremented: false,
firstDownLine: undefined,
numPossessionChanges: 0,
madeLateFG: undefined,
missedXP: undefined,
pts: [gameSim.team[0].stat.pts, gameSim.team[1].stat.pts],
twoPointConversionTeam: undefined,
turnoverOnDowns: false,
});
this.state = {
initial: initialState,
current: initialState.clone(),
};
this.penaltyRollbacks = [];
this.cleanHandsChangeOfPossessionIndexes = [];
this.spotOfEnforcementIndexes = [];
}
// If there is going to be a possession change related to this yds quantity, do possession change before calling boundedYds
boundedYds(yds: number) {
const scrimmage = this.state.current.scrimmage;
const ydsTD = 100 - scrimmage;
const ydsSafety = -scrimmage;
if (yds > ydsTD) {
return ydsTD;
}
if (yds < ydsSafety) {
return ydsSafety;
}
return yds;
}
// state is state immedaitely before this event happens. But since possession changes happen only in discrete events, state.o is always the team with the ball, even for things like "int" and "kr"
getStatChanges(event: PlayEvent, state: State) {
const statChanges: StatChange[] = [];
// No tracking stats during 2 point conversion attempt
if (!state.awaitingAfterTouchdown || event.type === "xp") {
if (event.type === "penalty") {
const actualPenYds =
event.name === "Pass interference" && event.penYds === 0
? event.spotYds
: event.penYds;
statChanges.push([event.t, event.p, "pen"]);
statChanges.push([event.t, event.p, "penYds", actualPenYds]);
}
if (event.type === "kr") {
statChanges.push([state.o, event.p, "kr"]);
statChanges.push([state.o, event.p, "krYds", event.yds]);
statChanges.push([state.o, event.p, "krLng", event.yds]);
} else if (event.type === "onsideKickRecovery") {
if (!event.success) {
statChanges.push([state.o, event.p, "kr"]);
statChanges.push([state.o, event.p, "krYds", event.yds]);
statChanges.push([state.o, event.p, "krLng", event.yds]);
}
} else if (event.type === "krTD") {
statChanges.push([state.o, event.p, "krTD"]);
} else if (event.type === "p") {
statChanges.push([state.o, event.p, "pnt"]);
statChanges.push([state.o, event.p, "pntYds", event.yds]);
statChanges.push([state.o, event.p, "pntLng", event.yds]);
const kickTo = state.scrimmage + event.yds;
if (kickTo > 80 && kickTo < 100) {
statChanges.push([state.o, event.p, "pntIn20"]);
}
} else if (event.type === "touchbackPunt") {
statChanges.push([state.d, event.p, "pntTB"]);
} else if (event.type === "pr") {
statChanges.push([state.o, event.p, "pr"]);
statChanges.push([state.o, event.p, "prYds", event.yds]);
statChanges.push([state.o, event.p, "prLng", event.yds]);
} else if (event.type === "prTD") {
statChanges.push([state.o, event.p, "prTD"]);
} else if (event.type === "rus") {
statChanges.push([state.o, event.p, "rus"]);
statChanges.push([state.o, event.p, "rusYds", event.yds]);
statChanges.push([state.o, event.p, "rusLng", event.yds]);
} else if (event.type === "rusTD") {
statChanges.push([state.o, event.p, "rusTD"]);
} else if (event.type === "kneel") {
statChanges.push([state.o, event.p, "rus"]);
statChanges.push([state.o, event.p, "rusYds", event.yds]);
statChanges.push([state.o, event.p, "rusLng", event.yds]);
} else if (event.type === "sk") {
statChanges.push([state.o, event.qb, "pssSk"]);
statChanges.push([state.o, event.qb, "pssSkYds", Math.abs(event.yds)]);
statChanges.push([state.d, event.p, "defSk"]);
} else if (event.type === "pss") {
statChanges.push([state.o, event.qb, "pss"]);
statChanges.push([state.o, event.target, "tgt"]);
} else if (event.type === "pssCmp") {
statChanges.push([state.o, event.qb, "pssCmp"]);
statChanges.push([state.o, event.qb, "pssYds", event.yds]);
statChanges.push([state.o, event.qb, "pssLng", event.yds]);
statChanges.push([state.o, event.target, "rec"]);
statChanges.push([state.o, event.target, "recYds", event.yds]);
statChanges.push([state.o, event.target, "recLng", event.yds]);
} else if (event.type === "pssInc") {
if (event.defender) {
statChanges.push([state.d, event.defender, "defPssDef"]);
}
} else if (event.type === "pssTD") {
statChanges.push([state.o, event.qb, "pssTD"]);
statChanges.push([state.o, event.target, "recTD"]);
} else if (event.type === "int") {
statChanges.push([state.d, event.qb, "pssInt"]);
statChanges.push([state.o, event.defender, "defPssDef"]);
statChanges.push([state.o, event.defender, "defInt"]);
const touchback = state.scrimmage + event.ydsReturn <= 0;
if (!touchback) {
statChanges.push([
state.o,
event.defender,
"defIntYds",
event.ydsReturn,
]);
statChanges.push([
state.o,
event.defender,
"defIntLng",
event.ydsReturn,
]);
}
} else if (event.type === "intTD") {
statChanges.push([state.o, event.p, "defIntTD"]);
} else if (event.type === "fg" || event.type === "xp") {
let statAtt;
let statMade;
if (event.type === "xp") {
statAtt = "xpa";
statMade = "xp";
} else if (event.distance < 20) {
statAtt = "fga0";
statMade = "fg0";
} else if (event.distance < 30) {
statAtt = "fga20";
statMade = "fg20";
} else if (event.distance < 40) {
statAtt = "fga30";
statMade = "fg30";
} else if (event.distance < 50) {
statAtt = "fga40";
statMade = "fg40";
} else {
statAtt = "fga50";
statMade = "fg50";
}
statChanges.push([state.o, event.p, statAtt]);
if (event.made) {
statChanges.push([state.o, event.p, statMade]);
if (event.type !== "xp") {
statChanges.push([state.o, event.p, "fgLng", event.distance]);
}
}
} else if (event.type === "fmb") {
statChanges.push([state.o, event.pFumbled, "fmb"]);
statChanges.push([state.d, event.pForced, "defFmbFrc"]);
} else if (event.type === "fmbRec") {
statChanges.push([state.o, event.pRecovered, "defFmbRec"]);
if (event.lost) {
statChanges.push([state.d, event.pFumbled, "fmbLost"]);
}
statChanges.push([state.o, event.pRecovered, "defFmbYds", event.yds]);
statChanges.push([state.o, event.pRecovered, "defFmbLng", event.yds]);
} else if (event.type === "fmbTD") {
statChanges.push([state.o, event.p, "defFmbTD"]);
} else if (event.type === "defSft") {
statChanges.push([state.d, event.p, "defSft"]);
} else if (event.type === "tck") {
for (const tackler of event.tacklers) {
statChanges.push([
state.d,
tackler,
event.tacklers.size === 1 ? "defTckSolo" : "defTckAst",
]);
if (event.loss) {
statChanges.push([state.d, tackler, "defTckLoss"]);
}
}
}
}
// Scoring
const pts = getPts(event, state.twoPointConversionTeam !== undefined);
if (pts !== undefined) {
const scoringTeam = event.type === "defSft" ? state.d : state.o;
statChanges.push([scoringTeam, undefined, "pts", pts]);
}
return statChanges;
}
getPenaltyInfo(state: State, event: PlayEventPenalty) {
const side = state.o === event.t ? "off" : "def";
const penYdsSigned = side === "off" ? -event.penYds : event.penYds;
const halfDistanceToGoal =
side === "off" && state.scrimmage / 2 < event.penYds;
const placeOnOne = side === "def" && state.scrimmage + penYdsSigned > 99;
return {
halfDistanceToGoal,
penYdsSigned,
placeOnOne,
};
}
updateState(state: State, event: PlayEvent) {
const afterKickoff = () => {
if (state.overtimeState === "initialKickoff") {
state.overtimeState = "firstPossession";
}
};
if (event.type === "penalty") {
if (event.spotYds !== undefined && !event.tackOn) {
// Spot foul, apply penalty from here
state.scrimmage += event.spotYds;
}
const { halfDistanceToGoal, penYdsSigned, placeOnOne } =
this.getPenaltyInfo(state, event);
// Adjust penalty yards when near endzones
if (placeOnOne) {
state.scrimmage = 99;
} else if (halfDistanceToGoal) {
state.scrimmage = Math.round(state.scrimmage / 2);
} else {
state.scrimmage += penYdsSigned;
}
if (event.automaticFirstDown || state.numPossessionChanges > 0) {
state.newFirstDown();
}
state.isClockRunning = false;
} else if (event.type === "possessionChange") {
state.scrimmage += event.yds;
state.possessionChange();
if (event.kickoff) {
state.awaitingKickoff = undefined;
state.awaitingAfterSafety = false;
afterKickoff();
}
} else if (event.type === "k" || event.type === "onsideKick") {
state.scrimmage = 100 - event.kickTo;
} else if (event.type === "touchbackKick") {
state.scrimmage = 25;
} else if (event.type === "kr") {
state.scrimmage += event.yds;
} else if (event.type === "onsideKickRecovery") {
state.scrimmage += event.yds;
state.awaitingKickoff = undefined;
state.awaitingAfterSafety = false;
state.newFirstDown();
} else if (event.type === "p") {
state.scrimmage += event.yds;
} else if (event.type === "touchbackPunt") {
state.scrimmage = 20;
} else if (event.type === "touchbackInt") {
state.scrimmage = 20;
} else if (event.type === "pr") {
state.scrimmage += event.yds;
} else if (event.type === "rus") {
state.incrementDown();
state.scrimmage += event.yds;
state.isClockRunning = Math.random() < 0.85;
} else if (event.type === "kneel") {
state.incrementDown();
state.scrimmage += event.yds;
// Set this to false, because we handle running the clock in dt in GameSim
state.isClockRunning = false;
} else if (event.type === "sk") {
state.scrimmage += event.yds;
state.isClockRunning = Math.random() < 0.98;
} else if (event.type === "dropback") {
state.incrementDown();
} else if (event.type === "pssCmp") {
state.scrimmage += event.yds;
state.isClockRunning = Math.random() < 0.75;
} else if (event.type === "pssInc") {
state.isClockRunning = false;
} else if (event.type === "int") {
state.scrimmage += event.ydsReturn;
} else if (event.type === "fg" || event.type === "xp") {
if (event.type === "xp" || event.made) {
state.awaitingKickoff = this.state.initial.o;
}
if (event.type === "xp" && !event.made) {
state.missedXP = state.o;
}
if (event.type === "fg" && event.made && event.late) {
state.madeLateFG = state.o;
}
state.awaitingAfterTouchdown = false;
state.isClockRunning = false;
} else if (event.type === "twoPointConversion") {
state.twoPointConversionTeam = event.t;
state.down = 1;
state.scrimmage = 98;
} else if (event.type === "twoPointConversionDone") {
// Reset off/def teams in case there was a turnover during the conversion attempt
state.o = event.t;
state.d = state.o === 0 ? 1 : 0;
state.twoPointConversionTeam = undefined;
state.awaitingKickoff = event.t;
state.awaitingAfterTouchdown = false;
state.isClockRunning = false;
} else if (event.type === "defSft") {
state.awaitingKickoff = state.o;
state.awaitingAfterSafety = true;
state.isClockRunning = false;
} else if (event.type === "fmb") {
state.scrimmage += event.yds;
} else if (event.type === "fmbRec") {
state.scrimmage += event.yds;
if (event.lost) {
state.isClockRunning = false;
} else {
// Stops if fumbled out of bounds
state.isClockRunning = Math.random() > 0.05;
}
}
if (event.type.endsWith("TD")) {
state.awaitingAfterTouchdown = true;
state.isClockRunning = false;
// This is to prevent weird bugs related to it thinking there is a turnover on downs after a TD is scored, see https://github.com/zengm-games/zengm/issues/397
state.down = 1;
}
// Doesn't really make sense to evaluate these things (TD, safety, touchback) because the play might not be over, could just be a player in their own endzone but maybe they don't want to take a knee for a touchback. So the _IS_POSSIBLE variables filter out when different events can actually happen, to get rid of false positives
let td = false;
let safety = false;
let touchback = false;
const TOUCHDOWN_IS_POSSIBLE: PlayType[] = [
"kr",
"onsideKickRecovery",
"pr",
"rus",
"pssCmp",
"int",
"fmbRec",
];
if (state.scrimmage >= 100 && TOUCHDOWN_IS_POSSIBLE.includes(event.type)) {
td = true;
}
const touchbackIsPossible = () => {
if (state.scrimmage <= 0) {
if (event.type === "int") {
return true;
} else if (event.type === "fmbRec" && event.lost) {
// Touchback only if it's a lost fumble
return true;
}
} else if (state.scrimmage >= 100) {
if (event.type === "p") {
return true;
}
}
return false;
};
touchback = touchbackIsPossible();
if (state.scrimmage <= 0) {
const SAFETY_IS_POSSIBLE: PlayType[] = ["rus", "pssCmp", "sk"];
const safetyIsPossible = () => {
if (SAFETY_IS_POSSIBLE.includes(event.type)) {
return true;
} else if (event.type === "fmbRec" && !event.lost) {
// Safety only if it's not a lost fumble
return true;
}
return false;
};
safety = safetyIsPossible();
}
if (event.type === "fmbRec") {
if (state.scrimmage <= 0) {
if (event.lost) {
state.scrimmage = 20;
touchback = true;
} else {
safety = true;
}
state.isClockRunning = false;
}
}
if (event.type.endsWith("TD")) {
if (
state.overtimeState === "initialKickoff" ||
state.overtimeState === "firstPossession"
) {
state.overtimeState = "over";
}
} else if (event.type === "defSft") {
if (
state.overtimeState === "initialKickoff" ||
state.overtimeState === "firstPossession"
) {
state.overtimeState = "over";
}
}
const pts = getPts(event, state.twoPointConversionTeam !== undefined);
if (pts !== undefined) {
const t = event.type === "defSft" ? state.d : state.o;
state.pts[t] += pts;
if (state.overtimeState === "secondPossession") {
const t2 = t === 0 ? 1 : 0;
if (state.pts[t] > state.pts[t2]) {
state.overtimeState = "over";
}
}
if (pts === 2) {
if (state.overtimeState === "secondPossession") {
const t2 = t === 0 ? 1 : 0;
if (state.pts[t] > state.pts[t2]) {
state.overtimeState = "over";
}
}
}
}
return {
safety,
td,
touchback,
};
}
checkDownAtEndOfPlay(state: State) {
// In endzone at end of play
if (
state.scrimmage >= 100 ||
state.scrimmage <= 0 ||
state.numPossessionChanges > 0
) {
return;
}
// No first down or turnover on downs if extra point or two point conversion - see issue #396
if (state.awaitingAfterTouchdown) {
return;
}
// already given new first down, so this should not apply!
state.toGo = state.firstDownLine - state.scrimmage;
if (state.toGo <= 0) {
state.newFirstDown();
}
state.turnoverOnDowns = state.down > 4;
if (state.turnoverOnDowns) {
state.possessionChange();
}
}
addEvent(event: PlayEvent) {
const statChanges = this.getStatChanges(event, this.state.current);
if (event.type === "penalty") {
if (event.tackOn) {
// Tack on penalty - added to end of play (except incomplete pass)
this.penaltyRollbacks.push({
type: "tackOn",
indexEvent: this.events.length,
});
} else if (event.spotYds !== undefined) {
// Spot foul? Assess at the last spot of enfocement
this.penaltyRollbacks.push({
// state: this.afterLastSpotOfEnforcement.state.clone(),
// indexEvent: this.afterLastSpotOfEnforcement.indexEvent,
type: "spotOfEnforcement",
indexEvent: this.events.length,
});
} else {
// Either assess from initial scrimmage, or the last change of possession if the penalty is after that
this.penaltyRollbacks.push({
// state: this.afterLastCleanHandsChangeOfPossession.state.clone(),
// indexEvent: this.afterLastCleanHandsChangeOfPossession.indexEvent,
type: "cleanHandsChangeOfPossession",
indexEvent: this.events.length,
});
}
const penaltyInfo = this.getPenaltyInfo(this.state.current, event);
// Purposely don't record stat changes!
this.events.push({
event,
statChanges,
penaltyInfo,
});
return {
safety: false,
td: false,
touchback: false,
};
}
for (const statChange of statChanges) {
this.g.recordStat(...statChange);
}
this.events.push({
event,
statChanges,
});
const offenseBefore = this.state.current.o;
const info = this.updateState(this.state.current, event);
const offenseAfter = this.state.current.o;
if (offenseAfter !== offenseBefore) {
// "Clean hands" means that a change of possession occurred while the team gaining possession had no prior penalties on this play
const cleanHands = this.events.every(
event =>
event.event.type !== "penalty" || event.event.t !== offenseAfter,
);
if (cleanHands) {
this.cleanHandsChangeOfPossessionIndexes.push(this.events.length - 1);
}
}
// Basically, anything that affects scrimmage
const UPDATE_SPOT_OF_ENFORCEMENT: PlayType[] = [
"possessionChange",
"k",
"onsideKick",
"touchbackKick",
"kr",
"onsideKickRecovery",
"p",
"touchbackPunt",
"touchbackInt",
"pr",
"rus",
"kneel",
"sk",
"pssCmp",
"int",
"fg",
"xp",
"fmb",
"fmbRec",
];
if (UPDATE_SPOT_OF_ENFORCEMENT.includes(event.type)) {
this.spotOfEnforcementIndexes.push(this.events.length - 1);
}
return info;
}
get numPenalties() {
return this.penaltyRollbacks.length;
}
adjudicatePenalties() {
const penalties = this.events.filter(
event => event.event.type === "penalty",
) as WrappedPenaltyEvent[];
if (penalties.length === 0) {
return;
}
const possessionChangeIndexes: number[] = [];
for (let i = 0; i < this.events.length; i++) {
const event = this.events[i];
if (event.event.type === "possessionChange") {
possessionChangeIndexes.push(i);
}
}
// Each entry in options is a set of decisions on all the penalties. So the inner arrays have the same length as penalties.length
let options: ("decline" | "accept" | "offset")[][] | undefined;
let choosingTeam: TeamNum | undefined;
let offsetStatus: "offset" | "overrule" | undefined;
if (penalties.length === 1) {
options = [["decline"], ["accept"]];
choosingTeam = penalties[0].event.t === 0 ? 1 : 0;
} else if (penalties.length === 2) {
if (penalties[0].event.t === penalties[1].event.t) {
// Same team - other team gets to pick which they want to accept, if any
// console.log("2 penalties - same team", penalties, this.events);
options = [
["decline", "decline"],
["decline", "accept"],
["accept", "decline"],
];
choosingTeam = penalties[0].event.t === 0 ? 1 : 0;
} else {
// Different team - maybe offsetting? Many edge cases http://static.nfl.com/static/content/public/image/rulebook/pdfs/17_Rule14_Penalty_Enforcement.pdf section 3
const penalties5 = penalties.filter(
penalty => penalty.event.penYds === 5,
);
const penalties15 = penalties.filter(
penalty =>
penalty.event.penYds === 15 ||
penalty.event.name === "Pass interference",
);
if (penalties5.length === 1 && penalties15.length === 1) {
choosingTeam = penalties15[0].event.t === 0 ? 1 : 0;
// 5 yd vs 15 yd penalty - only assess the 15 yd penalty
if (penalties15[0] === penalties[0]) {
options = [["accept", "decline"]];
} else {
options = [["decline", "accept"]];
}
offsetStatus = "overrule";
} else {
// Is this okay? Since there can be a decision to make, I guess, maybe?
choosingTeam = 0;
const numPossessionChanges = penalties.map(
(penalty, i) =>
possessionChangeIndexes.filter(
index => index <= this.penaltyRollbacks[i].indexEvent,
).length,
);
if (
numPossessionChanges[0] === numPossessionChanges[1] &&
numPossessionChanges[0] > 0
) {
// Both penalties after change of possession - roll back to spot of the change of possession
options = [["offset", "offset"]];
offsetStatus = "offset";
} else if (
numPossessionChanges[0] > 0 ||
numPossessionChanges[1] > 0
) {
// Clean hands change of possession - apply only the penalty from the team that gained possession
if (numPossessionChanges[0] > numPossessionChanges[1]) {
options = [["accept", "decline"]];
} else {
options = [["decline", "accept"]];
}
offsetStatus = "overrule";
} else {
// Penalties offset - replay down
options = [["offset", "offset"]];
offsetStatus = "offset";
}
}
}
} else {
throw new Error("Not supported");
}
if (options !== undefined && choosingTeam !== undefined) {
const results = options
.map(decisions => {
const indexAccept = decisions.indexOf("accept");
const indexOffset = decisions.indexOf("offset");
const penalty = penalties[indexAccept];
// console.log("decisions", decisions);
// Currently "offset" is every entry in the array or no entry
const offsetting = decisions[0] === "offset";
const subResults: {
// indexEvent is the index of the event to roll back to, if penalty is accepted. undefined means don't add any events onto state, other than the penalty. -1 means roll back everything except the penalty
indexEvent: number | undefined;
state: State;
tackOn: boolean;
}[] = [];
if (indexAccept < 0 && indexOffset < 0) {
subResults.push({
indexEvent: undefined,
state: this.state.current,
tackOn: false,
});
} else {
const penaltyRollback =
this.penaltyRollbacks[indexAccept] ??
this.penaltyRollbacks[indexOffset];
// console.log("penaltyRollback", JSON.parse(JSON.stringify(penaltyRollback)));
// console.log("penalty.event", penalty.event);
// indexEvent = penaltyRollback.indexEvent;
// Figure out what state to replay
if (
penaltyRollback.type === "cleanHandsChangeOfPossession" ||
offsetting
) {
const validIndexes = this.spotOfEnforcementIndexes.filter(
index => index < penaltyRollback.indexEvent,
);
const indexEvent =
validIndexes.length === 0 ? -1 : Math.max(...validIndexes);
subResults.push({
indexEvent,
state: this.state.initial.clone(),
tackOn: false,
});
} else if (penaltyRollback.type === "spotOfEnforcement") {
const validIndexes = this.spotOfEnforcementIndexes.filter(
index => index < penaltyRollback.indexEvent,
);
const indexEvent =
validIndexes.length === 0 ? -1 : Math.max(...validIndexes);
subResults.push({
indexEvent,
state: this.state.initial.clone(),
tackOn: false,
});
} else if (penaltyRollback.type === "tackOn") {
subResults.push({
indexEvent: -1,
state: this.state.initial.clone(),
tackOn: false,
});
const indexEvent = this.spotOfEnforcementIndexes.at(-1);
if (indexEvent > 0) {
subResults.push({
indexEvent,
state: this.state.initial.clone(),
tackOn: true,
});
}
}
for (const { indexEvent, state } of subResults) {
if (indexEvent !== undefined && indexEvent >= 0) {
for (let i = 0; i <= indexEvent; i++) {
const event = this.events[i].event;
// Only one penalty can be applied, this one! And that is done below.
if (event.type !== "penalty") {
this.updateState(state, this.events[i].event);
}
}
}
// No state changes for offsetting penalties
if (offsetStatus === "offset") {
state.isClockRunning = false;
} else {
this.updateState(state, penalty.event);
}
this.checkDownAtEndOfPlay(state);
}
}
let statChanges: NonNullable<typeof penalty>["statChanges"] = [];
if (offsetStatus !== "offset") {
// No stat changes for offsetting penalties
statChanges = penalty?.statChanges;
}
return subResults.map(subResult => ({
indexAccept,
decisions,
statChanges,
...subResult,
}));
})
.flat();
const result = getBestPenaltyResult(
results,
this.state.initial,
choosingTeam,
);
if (result.decisions.length > 1) {
this.g.playByPlay.logEvent("penaltyCount", {
clock: this.g.clock,
count: result.decisions.length,
offsetStatus,
});
}
// Announce declind penalties first, then accepted penalties
for (const type of ["decline", "accept"] as const) {
for (let i = 0; i < penalties.length; i++) {
const decision = result.decisions[i];
if (decision !== type) {
continue;
}
const penalty = penalties[i];
// Special case for pass interference, so it doesn't say "0 yards from the spot of the foul"
let yds = penalty.event.penYds;
let spotFoul = penalty.event.spotYds !== undefined;
if (yds === 0 && spotFoul) {
yds = penalty.event.spotYds as number;
spotFoul = false;
}
this.g.playByPlay.logEvent("penalty", {
clock: this.g.clock,
decision,
offsetStatus,
t: penalty.event.t,
names: penalty.event.p ? [penalty.event.p.name] : [],
automaticFirstDown: penalty.event.automaticFirstDown,
penaltyName: penalty.event.name,
yds,
spotFoul,
halfDistanceToGoal: penalty.penaltyInfo.halfDistanceToGoal,
placeOnOne: penalty.penaltyInfo.placeOnOne,
tackOn: result.tackOn,
});
}
}
// Actually apply result of accepted penalty - ASSUMES JUST ONE IS ACCEPTED
this.state.current = result.state;
if (result.indexAccept >= 0) {
let numPenaltiesSeen = 0;
const statChanges = [
// Apply statChanges from accepted penalty
...result.statChanges,
// Apply negative statChanges from anything after accepted penalty
...this.events
.filter((event, i) => {
// Don't remove the accepted penalty, since we only just added it here! It is not like other events which are added previously
if (event.event.type === "penalty") {
if (result.indexAccept === numPenaltiesSeen) {
numPenaltiesSeen += 1;
return false;
}
numPenaltiesSeen += 1;
}
return result.indexEvent === undefined || i > result.indexEvent;
})
.map(event => event.statChanges)
.map(statChanges => {
return statChanges.map(statChange => {
const newStatChange = [...statChange] as StatChange;
if (newStatChange[3] === undefined) {
newStatChange[3] = 1;
}
newStatChange[4] = true;
return newStatChange;
});
})
.flat(),
];
for (const statChange of statChanges) {
this.g.recordStat(...statChange);
}
}
}
}
commit() {
this.checkDownAtEndOfPlay(this.state.current);
this.adjudicatePenalties();
if (this.state.current.turnoverOnDowns) {
this.g.playByPlay.logEvent("turnoverOnDowns", {
clock: this.g.clock,
});
}
const {
down,
toGo,
scrimmage,
o,
d,
isClockRunning,
awaitingKickoff,
awaitingAfterSafety,
awaitingAfterTouchdown,
overtimeState,
} = this.state.current;
this.g.down = down;
this.g.toGo = toGo;
this.g.scrimmage = scrimmage;
this.g.o = o;
this.g.d = d;
this.g.isClockRunning = isClockRunning;
this.g.awaitingKickoff = awaitingKickoff;
this.g.awaitingAfterSafety = awaitingAfterSafety;
this.g.awaitingAfterTouchdown = awaitingAfterTouchdown;
this.g.overtimeState = overtimeState;
}
}
export default Play; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.